text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Update default smart contract addresses
# -*- coding: utf-8 -*- UINT64_MAX = 2 ** 64 - 1 UINT64_MIN = 0 INT64_MAX = 2 ** 63 - 1 INT64_MIN = -(2 ** 63) UINT256_MAX = 2 ** 256 - 1 # Deployed to Ropsten revival on 2017-08-03 from commit 17aa7671159779ceef22fe90001970bed0685c4d ROPSTEN_REGISTRY_ADDRESS = '25926b6d29f56ba8466601d7ce7dd29985af1f14' ROPSTEN_DISCOVERY_ADDRESS = 'a647336e0b4eaddcee11fe6c13e9163ad2700d6d' DISCOVERY_REGISTRATION_GAS = 500000 MINUTE_SEC = 60 MINUTE_MS = 60 * 1000 NETTINGCHANNEL_SETTLE_TIMEOUT_MIN = 6 # TODO: add this as an attribute of the transport class UDP_MAX_MESSAGE_SIZE = 1200
# -*- coding: utf-8 -*- UINT64_MAX = 2 ** 64 - 1 UINT64_MIN = 0 INT64_MAX = 2 ** 63 - 1 INT64_MIN = -(2 ** 63) UINT256_MAX = 2 ** 256 - 1 # Deployed to Ropsten revival on 2017-06-19 from commit 2677298a69c1b1f35b9ab26beafe457acfdcc0ee ROPSTEN_REGISTRY_ADDRESS = 'aff1f958c69a6820b08a02549ff9041629ae8257' ROPSTEN_DISCOVERY_ADDRESS = 'cf56165f4f6e8ec38bb463854c1fe28a5d320f4f' DISCOVERY_REGISTRATION_GAS = 500000 MINUTE_SEC = 60 MINUTE_MS = 60 * 1000 NETTINGCHANNEL_SETTLE_TIMEOUT_MIN = 6 # TODO: add this as an attribute of the transport class UDP_MAX_MESSAGE_SIZE = 1200
Allow passing other key codes, not just the ones from the list
import Ember from 'ember'; const keyToEventMap = { 27: 'esc', 37: 'leftArrow', 38: 'upArrow', 39: 'rightArrow', 40: 'downArrow' }; export default Ember.Mixin.create({ mergedProperties: ['keyEvents'], keyEvents: {}, setupKeyHandling: function() { this.$(document).on(`keyup.${this.get('elementId')}`, (event) => { var key = (keyToEventMap[event.keyCode]) ? keyToEventMap[event.keyCode] : event.keyCode; var keyEvent = this.get('keyEvents')[key]; if (keyEvent) { keyEvent.call(this, event); } }); }.on('didInsertElement'), tearDownKeyHandling: function() { this.$(document).off(`keyup.${this.get('elementId')}`); }.on('willDestroyElement') });
import Ember from 'ember'; const keyCodeToEventMap = { 27: 'esc', 37: 'leftArrow', 38: 'upArrow', 39: 'rightArrow', 40: 'downArrow' }; export default Ember.Mixin.create({ mergedProperties: ['keyEvents'], keyEvents: {}, setupKeyHandling: function() { this.$(document).on(`keyup.${this.get('elementId')}`, (event) => { var key = keyCodeToEventMap[event.keyCode]; var keyEvent = this.get('keyEvents')[key]; if (keyEvent) { keyEvent.call(this, event); } }); }.on('didInsertElement'), tearDownKeyHandling: function() { this.$(document).off(`keyup.${this.get('elementId')}`); }.on('willDestroyElement') });
Revert "sudo is required to run which <gem-exec> on arch." This reverts commit 15162c58c27bc84f1c7fc0326f782bd693ca4d7e.
from fabric.api import env, run, settings, hide # Default system user env.user = 'ubuntu' # Default puppet environment env.environment = 'prod' # Default puppet module directory env.puppet_module_dir = 'modules/' # Default puppet version # If loom_puppet_version is None, loom installs the latest version env.loom_puppet_version = '3.1.1' # Default librarian version # If loom_librarian_version is None, loom installs the latest version env.loom_librarian_version = '0.9.9' def host_roles(host_string): """ Returns the role of a given host string. """ roles = set() for role, hosts in env.roledefs.items(): if host_string in hosts: roles.add(role) return list(roles) def current_roles(): return host_roles(env.host_string) def has_puppet_installed(): with settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=True): result = run('which puppet') return result.succeeded def has_librarian_installed(): with settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=True): librarian = run('which librarian-puppet') return librarian.succeeded
from fabric.api import env, run, sudo, settings, hide # Default system user env.user = 'ubuntu' # Default puppet environment env.environment = 'prod' # Default puppet module directory env.puppet_module_dir = 'modules/' # Default puppet version # If loom_puppet_version is None, loom installs the latest version env.loom_puppet_version = '3.1.1' # Default librarian version # If loom_librarian_version is None, loom installs the latest version env.loom_librarian_version = '0.9.9' def host_roles(host_string): """ Returns the role of a given host string. """ roles = set() for role, hosts in env.roledefs.items(): if host_string in hosts: roles.add(role) return list(roles) def current_roles(): return host_roles(env.host_string) def has_puppet_installed(): with settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=True): result = sudo('which puppet') return result.succeeded def has_librarian_installed(): with settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=True): librarian = sudo('which librarian-puppet') return librarian.succeeded
Remove needless import of sys module
#!/usr/bin/env python3 # card-fight-thingy - Simplistic battle card game... thingy # # The MIT License (MIT) # # Copyright (c) 2015 The Underscores # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import game import menu menu.init() menu.chooseOption()
#!/usr/bin/env python3 # card-fight-thingy - Simplistic battle card game... thingy # # The MIT License (MIT) # # Copyright (c) 2015 The Underscores # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import sys import game import menu menu.init() menu.chooseOption()
Fix dumb case where errors didn't exist in the send callback.
var server = require('http').createServer() var wr = require('./water_rower.js')({ debug: false} ); var ws = require('ws'); var url = require('url') var WebSocketServer = ws.Server var wsServer = new WebSocketServer({ server: server }); var parseArgs = require('minimist'); var argv = parseArgs( process.argv , { number: [ 'port' ], string: [ 'comport' ], boolean: [ 'debug'] }); var port = argv.port || 'NULL'; var debug = argv.debug || false; var comport = argv.comport; var rower = new wr.WaterRower({ port: comport }); var express = require('express'); var app = express(); app.get('/', express.static(__dirname+'/public') ); rower.on('readings', function _broadcastReadings( msg ) { wsServer.clients.forEach( function(client) { client.send( JSON.stringify(msg), function(err) { if (err) { console.log(err.toString()); } }); }); }); wsServer.on('connection', function connection(sock) { var location = url.parse(sock.upgradeReq.url, true); sock.on('disconnect', function _accounceDisconnect(){ console.log("Socket disconnect."); }); console.log("Socket connect."); }); console.log('Starting water rower.'); server.on('request', app); server.listen(port, function () { console.log('Listening on ' + server.address().port) });
var server = require('http').createServer() var wr = require('./water_rower.js')({ debug: false} ); var ws = require('ws'); var url = require('url') var WebSocketServer = ws.Server var wsServer = new WebSocketServer({ server: server }); var parseArgs = require('minimist'); var argv = parseArgs( process.argv , { number: [ 'port' ], string: [ 'comport' ], boolean: [ 'debug'] }); var port = argv.port || 'NULL'; var debug = argv.debug || false; var comport = argv.comport; var rower = new wr.WaterRower({ port: comport }); var express = require('express'); var app = express(); app.get('/', express.static(__dirname+'/public') ); rower.on('readings', function _broadcastReadings( msg ) { wsServer.clients.forEach( function(client) { client.send( JSON.stringify(msg), function(err) { console.log(err.toString()); }); }); }); wsServer.on('connection', function connection(sock) { var location = url.parse(sock.upgradeReq.url, true); sock.on('disconnect', function _accounceDisconnect(){ console.log("Socket disconnect."); }); console.log("Socket connect."); }); console.log('Starting water rower.'); server.on('request', app); server.listen(port, function () { console.log('Listening on ' + server.address().port) });
Fix tests after the previous commit
/* * Copyright 2018 The RoboZonky Project * * 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 com.github.robozonky.app.configuration; import java.time.Duration; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; class MarketplaceCommandLineFragmentTest { @Test void delayBetweenPrimaryMarketplaceChecks() { final MarketplaceCommandLineFragment f = new MarketplaceCommandLineFragment(); final Duration a = f.getPrimaryMarketplaceCheckDelay(); assertThat(a).isEqualByComparingTo(Duration.ofSeconds(5)); } @Test void delayBetweenSecondaryMarketplaceChecks() { final MarketplaceCommandLineFragment f = new MarketplaceCommandLineFragment(); final Duration a = f.getSecondaryMarketplaceCheckDelay(); assertThat(a).isEqualByComparingTo(Duration.ofSeconds(5)); } }
/* * Copyright 2017 The RoboZonky Project * * 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 com.github.robozonky.app.configuration; import java.time.Duration; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.*; class MarketplaceCommandLineFragmentTest { @Test void delayBetweenPrimaryMarketplaceChecks() { final MarketplaceCommandLineFragment f = new MarketplaceCommandLineFragment(); final Duration a = f.getPrimaryMarketplaceCheckDelay(); assertThat(a).isEqualByComparingTo(Duration.ofSeconds(10)); } @Test void delayBetweenSecondaryMarketplaceChecks() { final MarketplaceCommandLineFragment f = new MarketplaceCommandLineFragment(); final Duration a = f.getSecondaryMarketplaceCheckDelay(); assertThat(a).isEqualByComparingTo(Duration.ofSeconds(10)); } }
Remove the unused import and fix testing library
""" :mod:`zsl.interface.webservice.performers.method` ------------------------------------------------- .. moduleauthor:: Martin Babka """ from __future__ import unicode_literals import logging from importlib import import_module import sys from zsl.router.method import get_method_packages def call_exposers_in_method_packages(): for package in get_method_packages(): if package in sys.modules: module = sys.modules[package] if hasattr(module, '__reloader__'): getattr(module, '__reloader__')() else: module = import_module(package) msg = "Calling exposers in method package {}".format(package) logging.getLogger(__name__).debug(msg) if hasattr(module, '__exposer__'): getattr(module, '__exposer__')()
""" :mod:`zsl.interface.webservice.performers.method` ------------------------------------------------- .. moduleauthor:: Martin Babka """ from __future__ import unicode_literals import logging from importlib import import_module, reload import sys from zsl.router.method import get_method_packages def call_exposers_in_method_packages(): for package in get_method_packages(): if package in sys.modules: module = sys.modules[package] if hasattr(module, '__reloader__'): getattr(module, '__reloader__')() else: module = import_module(package) msg = "Calling exposers in method package {}".format(package) logging.getLogger(__name__).debug(msg) if hasattr(module, '__exposer__'): getattr(module, '__exposer__')()
Fix @typedef name to be dot-separated.
steal('can/util', function (can) { /** * @typedef {{bind:function():*,unbind:function():*}} can.util.bind * * Provides mixin-able bind and unbind methods. `bind()` calls `this._bindsetup` * when the first bind happens and. `unbind()` calls `this._bindteardown` when there * are no more event handlers. * */ // ## Bind helpers can.bindAndSetup = function () { // Add the event to this object can.addEvent.apply(this, arguments); // If not initializing, and the first binding // call bindsetup if the function exists. if (!this._init) { if (!this._bindings) { this._bindings = 1; // setup live-binding if (this._bindsetup) { this._bindsetup(); } } else { this._bindings++; } } return this; }; can.unbindAndTeardown = function (ev, handler) { // Remove the event handler can.removeEvent.apply(this, arguments); if (this._bindings === null) { this._bindings = 0; } else { this._bindings--; } // If there are no longer any bindings and // there is a bindteardown method, call it. if (!this._bindings && this._bindteardown) { this._bindteardown(); } return this; }; return can; });
steal('can/util', function (can) { /** * @typedef {{bind:function():*,unbind:function():*}} can/util/bind * * Provides mixin-able bind and unbind methods. `bind()` calls `this._bindsetup` * when the first bind happens and. `unbind()` calls `this._bindteardown` when there * are no more event handlers. * */ // ## Bind helpers can.bindAndSetup = function () { // Add the event to this object can.addEvent.apply(this, arguments); // If not initializing, and the first binding // call bindsetup if the function exists. if (!this._init) { if (!this._bindings) { this._bindings = 1; // setup live-binding if (this._bindsetup) { this._bindsetup(); } } else { this._bindings++; } } return this; }; can.unbindAndTeardown = function (ev, handler) { // Remove the event handler can.removeEvent.apply(this, arguments); if (this._bindings === null) { this._bindings = 0; } else { this._bindings--; } // If there are no longer any bindings and // there is a bindteardown method, call it. if (!this._bindings && this._bindteardown) { this._bindteardown(); } return this; }; return can; });
Enable import hook by default
"""A python library wrapping the Cap'n Proto C++ library Example Usage:: import capnp addressbook = capnp.load('addressbook.capnp') # Building addresses = addressbook.AddressBook.newMessage() people = addresses.init('people', 1) alice = people[0] alice.id = 123 alice.name = 'Alice' alice.email = '[email protected]' alicePhone = alice.init('phones', 1)[0] alicePhone.type = 'mobile' f = open('example.bin', 'w') addresses.writeTo(f) f.close() # Reading f = open('example.bin') addresses = addressbook.AddressBook.readFrom(f) for person in addresses.people: print(person.name, ':', person.email) for phone in person.phones: print(phone.type, ':', phone.number) """ from .version import version as __version__ from .capnp import * from .capnp import _DynamicStructReader, _DynamicStructBuilder, _DynamicResizableListBuilder, _DynamicListReader, _DynamicListBuilder, _DynamicOrphan, _DynamicResizableListBuilder, _MallocMessageBuilder, _PackedFdMessageReader, _StreamFdMessageReader, _write_message_to_fd, _write_packed_message_to_fd del capnp add_import_hook() # enable import hook by default
"""A python library wrapping the Cap'n Proto C++ library Example Usage:: import capnp addressbook = capnp.load('addressbook.capnp') # Building addresses = addressbook.AddressBook.newMessage() people = addresses.init('people', 1) alice = people[0] alice.id = 123 alice.name = 'Alice' alice.email = '[email protected]' alicePhone = alice.init('phones', 1)[0] alicePhone.type = 'mobile' f = open('example.bin', 'w') addresses.writeTo(f) f.close() # Reading f = open('example.bin') addresses = addressbook.AddressBook.readFrom(f) for person in addresses.people: print(person.name, ':', person.email) for phone in person.phones: print(phone.type, ':', phone.number) """ from .version import version as __version__ from .capnp import * from .capnp import _DynamicStructReader, _DynamicStructBuilder, _DynamicResizableListBuilder, _DynamicListReader, _DynamicListBuilder, _DynamicOrphan, _DynamicResizableListBuilder, _MallocMessageBuilder, _PackedFdMessageReader, _StreamFdMessageReader, _write_message_to_fd, _write_packed_message_to_fd del capnp
Change viewport and zoom factor
var page = require("webpage").create(); var system = require("system"); page.paperSize = { width: '6in', height: '4in', margin: { top: '10px', left: '15px', right: '15px', bottom: '10px' } } page.zoomFactor = 0.7; page.open(system.args[1], function (status) { window.setTimeout(function () { var size = page.evaluate(function () { return {width: width = 940, height : 820 }; }); page.paperSize = size; page.render(system.args[2]); phantom.exit(); }, 3000); }); page.onError = function(msg, trace) { console.log(msg); }
var page = require("webpage").create(); var system = require("system"); page.paperSize = { width: '6in', height: '4in', margin: { top: '10px', left: '15px', right: '15px', bottom: '10px' } } page.zoomFactor = 0.5; page.open(system.args[1], function (status) { window.setTimeout(function () { var size = page.evaluate(function () { return {width: width = 900, height : 850 }; }); page.paperSize = size; page.render(system.args[2]); phantom.exit(); }, 3000); }); page.onError = function(msg, trace) { console.log(msg); }
Change .env variable to KCLS_USER
import requests from bs4 import BeautifulSoup import json from dotenv import load_dotenv import os load_dotenv(".env") s = requests.Session() r = s.get("https://kcls.bibliocommons.com/user/login", verify=False) payload = { "name": os.environ.get("KCLS_USER"), "user_pin": os.environ.get("PIN") } p = s.post("https://kcls.bibliocommons.com/user/login", data=payload) r = s.get("https://kcls.bibliocommons.com/checkedout?display_quantity=50&page=1&view=medium") soup = BeautifulSoup(r.text, "html.parser") checkedOutList = soup.find("div", { "id": "bibList" }) checkedOutItems = [] for title in checkedOutList.find_all("div", { "class": "listItem" }): title_name = title.find("span", { "class": "title" }) due_date = title.find("span", { "class": "item_due_date" }) checkedOutItems.append({ "title": title_name.text.strip(), "due": due_date.text.strip() }) with open("checkedout.json", "w") as f: print "%d title(s) checked out" % len(checkedOutItems) f.write(json.dumps(checkedOutItems))
import requests from bs4 import BeautifulSoup import json from dotenv import load_dotenv import os load_dotenv(".env") s = requests.Session() r = s.get("https://kcls.bibliocommons.com/user/login", verify=False) payload = { "name": os.environ.get("USER"), "user_pin": os.environ.get("PIN") } s.post("https://kcls.bibliocommons.com/user/login", data=payload) r = s.get("https://kcls.bibliocommons.com/checkedout?display_quantity=50&page=1&view=medium") soup = BeautifulSoup(r.text, "html.parser") checkedOutList = soup.find("div", { "id": "bibList" }) checkedOutItems = [] for title in checkedOutList.find_all("div", { "class": "listItem" }): title_name = title.find("span", { "class": "title" }) due_date = title.find("span", { "class": "item_due_date" }) checkedOutItems.append({ "title": title_name.text.strip(), "due": due_date.text.strip() }) with open("checkedout.json", "w") as f: print "%d title(s) checked out" % len(checkedOutItems) f.write(json.dumps(checkedOutItems))
Load addons into resolver AFField instead of global AFField
import Ember from 'ember' import { DEFAULT_CONFIG as FIELD_DEFAULT_CONFIG } from '../components/af-field' import i18n from '../mixins/i18n' import loc from '../mixins/loc' import restless from '../mixins/restless' import validations from '../mixins/validations' const AF_FIELD_MIXINS = { i18n, loc, restless, validations } export default Ember.Service.extend({ config: Object.assign({}, FIELD_DEFAULT_CONFIG, { prompt: 'Select', fieldPlugins: [] }), configure (arg) { if (typeof arg === 'function') { arg(this.config) } else { Ember.$.extend(true, this.config, arg) } let afFieldClass = Ember.getOwner(this).resolveRegistration('component:af-field') this.config.fieldPlugins.forEach((plugin) => { if (plugin instanceof Ember.Mixin) { afFieldClass.reopen(plugin) } else if (AF_FIELD_MIXINS[plugin]) { afFieldClass.reopen(AF_FIELD_MIXINS[plugin]) } else { Ember.warn(`Not a valid plugin: ${plugin}`) } }) return this } })
import Ember from 'ember' import AFField, { DEFAULT_CONFIG as FIELD_DEFAULT_CONFIG } from '../components/af-field' import i18n from '../mixins/i18n' import loc from '../mixins/loc' import restless from '../mixins/restless' import validations from '../mixins/validations' const AF_FIELD_MIXINS = { i18n, loc, restless, validations } export default Ember.Service.extend({ config: Object.assign({}, FIELD_DEFAULT_CONFIG, { prompt: 'Select', fieldPlugins: [] }), configure (arg) { if (typeof arg === 'function') { arg(this.config) } else { Ember.$.extend(true, this.config, arg) } // TODO: localize plugin logic instead of tossing them onto the base class this.config.fieldPlugins.forEach((plugin) => { if (plugin instanceof Ember.Mixin) { AFField.reopen(plugin) } else if (AF_FIELD_MIXINS[plugin]) { AFField.reopen(AF_FIELD_MIXINS[plugin]) } else { Ember.warn(`Not a valid plugin: ${plugin}`) } }) return this } })
Disable secure cookies and csrf for dev
from sleepy.conf.base import * DEBUG = True TEMPLATE_DEBUG = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'sleepy_dev', } } SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '' # noqa SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '' SOCIAL_AUTH_TWITTER_KEY = '' SOCIAL_AUTH_TWITTER_SECRET = '' SOCIAL_AUTH_FACEBOOK_KEY = '' SOCIAL_AUTH_FACEBOOK_SECRET = '' SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] SOCIAL_AUTH_GITHUB_KEY = '' SOCIAL_AUTH_GITHUB_SECRET = '' LOGGING['loggers']['root']['level'] = 'DEBUG' LOGGING['loggers']['celery']['level'] = 'DEBUG' LOGGING['loggers']['sleepy']['level'] = 'DEBUG' SESSION_COOKIE_SECURE = False CSRF_COOKIE_SECURE = False
from sleepy.conf.base import * DEBUG = True TEMPLATE_DEBUG = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'sleepy_dev', } } SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '' # noqa SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '' SOCIAL_AUTH_TWITTER_KEY = '' SOCIAL_AUTH_TWITTER_SECRET = '' SOCIAL_AUTH_FACEBOOK_KEY = '' SOCIAL_AUTH_FACEBOOK_SECRET = '' SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] SOCIAL_AUTH_GITHUB_KEY = '' SOCIAL_AUTH_GITHUB_SECRET = '' LOGGING['loggers']['root']['level'] = 'DEBUG' LOGGING['loggers']['celery']['level'] = 'DEBUG' LOGGING['loggers']['sleepy']['level'] = 'DEBUG'
USe the Enum name, not the toString method when binding the parameter value
package com.vladmihalcea.book.hpjp.hibernate.mapping.enums; import org.hibernate.HibernateException; import org.hibernate.engine.spi.SharedSessionContractImplementor; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Types; /** * @author Vlad Mihalcea */ public class PostgreSQLEnumType extends org.hibernate.type.EnumType { public void nullSafeSet( PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException { st.setObject( index, value != null ? ((Enum) value).name() : null, Types.OTHER ); } }
package com.vladmihalcea.book.hpjp.hibernate.mapping.enums; import org.hibernate.HibernateException; import org.hibernate.engine.spi.SharedSessionContractImplementor; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Types; /** * @author Vlad Mihalcea */ public class PostgreSQLEnumType extends org.hibernate.type.EnumType { public void nullSafeSet( PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException { if (value == null) { st.setNull(index, Types.OTHER); } else { st.setObject(index, value.toString(), Types.OTHER); } } }
Use inline variable declartion to save LOC
WebApp.connectHandlers.use("/package", function(request, response) { var url = `https://atmospherejs.com/a/packages/findByNames\ ?names=${request.url.split('/')[1]}`; var opts = {headers: {'Accept': 'application/json'}}; HTTP.get(url, opts, function(err, res) { var name = '', pl = res.data[0], version, pubDate, starCount, installYear; if (res.data.length !== 0) { name = pl.name; version = pl.latestVersion.version; pubDate = moment(pl.latestVersion.published.$date).format('MMM Do YYYY'); starCount = pl.starCount || 0; installYear = pl['installs-per-year'] || 0; } SSR.compileTemplate('icon', Assets.getText('icon.svg')); var width = 225 + name.length * 6.305555555555555; var icon = SSR.render('icon', {w: width, totalW: width+2, n: name, v: version, p: pubDate, s: starCount, i: installYear}); response.writeHead(200, {"Content-Type": "image/svg+xml"}); response.end(icon); }); });
WebApp.connectHandlers.use("/package", function(request, response) { var url = `https://atmospherejs.com/a/packages/findByNames\ ?names=${request.url.split('/')[1]}`; var opts = {headers: {'Accept': 'application/json'}}; HTTP.get(url, opts, function(err, res) { var name = '', version, pubDate, starCount, installYear; var pl = res.data[0]; if (res.data.length !== 0) { name = pl.name; version = pl.latestVersion.version; pubDate = moment(pl.latestVersion.published.$date).format('MMM Do YYYY'); starCount = pl.starCount || 0; installYear = pl['installs-per-year'] || 0; } SSR.compileTemplate('icon', Assets.getText('icon.svg')); var width = 225 + name.length * 6.305555555555555; var icon = SSR.render('icon', {w: width, totalW: width+2, n: name, v: version, p: pubDate, s: starCount, i: installYear}); response.writeHead(200, {"Content-Type": "image/svg+xml"}); response.end(icon); }); });
Fix `pauseOnHover` default value to true Which is described in README
var defaultProps = { className: '', accessibility: true, adaptiveHeight: false, arrows: true, autoplay: false, autoplaySpeed: 3000, centerMode: false, centerPadding: '50px', cssEase: 'ease', dots: false, dotsClass: 'slick-dots', draggable: true, easing: 'linear', edgeFriction: 0.35, fade: false, focusOnSelect: false, infinite: true, initialSlide: 0, lazyLoad: false, pauseOnHover: true, responsive: null, rtl: false, slide: 'div', slidesToShow: 1, slidesToScroll: 1, speed: 500, swipe: true, swipeToSlide: false, touchMove: true, touchThreshold: 5, useCSS: true, variableWidth: false, vertical: false, waitForAnimate: true, afterChange: null, beforeChange: null, edgeEvent: null, init: null, swipeEvent: null, // nextArrow, prevArrow are react componets nextArrow: null, prevArrow: null }; module.exports = defaultProps;
var defaultProps = { className: '', accessibility: true, adaptiveHeight: false, arrows: true, autoplay: false, autoplaySpeed: 3000, centerMode: false, centerPadding: '50px', cssEase: 'ease', dots: false, dotsClass: 'slick-dots', draggable: true, easing: 'linear', edgeFriction: 0.35, fade: false, focusOnSelect: false, infinite: true, initialSlide: 0, lazyLoad: false, pauseOnHover: false, responsive: null, rtl: false, slide: 'div', slidesToShow: 1, slidesToScroll: 1, speed: 500, swipe: true, swipeToSlide: false, touchMove: true, touchThreshold: 5, useCSS: true, variableWidth: false, vertical: false, waitForAnimate: true, afterChange: null, beforeChange: null, edgeEvent: null, init: null, swipeEvent: null, // nextArrow, prevArrow are react componets nextArrow: null, prevArrow: null }; module.exports = defaultProps;
Remove sent word count from jQuery.
function countWords() { var string = $.trim($("textarea").val()), words = string.replace(/\s+/gi, ' ').split(' ').length chars = string.length; if(!chars)words=0; $(".word-count").contents().filter(function(){ return this.nodeType == 3; })[0].nodeValue = words } function autoSave() { var content = $("textarea").val() $.post('/update_post', {content: content}) } $(document).on('page:change', function() { $(".word-count").hover(function() { $(this).find(".wordz").toggleClass("hidden") }) $(".close").hover(function() { $(".save-exit").toggleClass("hidden") }) // Run this when the page loads so you can get an initial count. // Otherwise, the word count will be zero until you start typing again. countWords() $("textarea").focus().on('input', countWords) setInterval(autoSave, 10000) $(".close").find("a").click(function() { autoSave() }) })
function countWords() { var string = $.trim($("textarea").val()), words = string.replace(/\s+/gi, ' ').split(' ').length chars = string.length; if(!chars)words=0; $(".word-count").contents().filter(function(){ return this.nodeType == 3; })[0].nodeValue = words } function autoSave() { var regex = new RegExp("/\d+/g"); var wordCount = $.trim($(".word-count").html()).match(/\d+/g) var content = $("textarea").val() $.post('/update_post', {word_count: wordCount, content: content}) } $(document).on('page:change', function() { $(".word-count").hover(function() { $(this).find(".wordz").toggleClass("hidden") }) $(".close").hover(function() { $(".save-exit").toggleClass("hidden") }) // Run this when the page loads so you can get an initial count. // Otherwise, the word count will be zero until you start typing again. countWords() $("textarea").focus().on('input', countWords) setInterval(autoSave, 10000) $(".close").find("a").click(function() { autoSave() }) })
Change Development Status to Beta, add Python 3.4 support flag.
from setuptools import setup, find_packages import flask_boost entry_points = { "console_scripts": [ "boost = flask_boost.cli:main", ] } with open("requirements.txt") as f: requires = [l for l in f.read().splitlines() if l] setup( name='Flask-Boost', version=flask_boost.__version__, packages=find_packages(), include_package_data=True, description='Flask application generator for boosting your development.', long_description=open('README.rst').read(), url='https://github.com/hustlzp/Flask-Boost', author='hustlzp', author_email='[email protected]', license='MIT', keywords='flask sample generator', install_requires=requires, entry_points=entry_points, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ], )
from setuptools import setup, find_packages import flask_boost entry_points = { "console_scripts": [ "boost = flask_boost.cli:main", ] } with open("requirements.txt") as f: requires = [l for l in f.read().splitlines() if l] setup( name='Flask-Boost', version=flask_boost.__version__, packages=find_packages(), include_package_data=True, description='Flask application generator for boosting your development.', long_description=open('README.rst').read(), url='https://github.com/hustlzp/Flask-Boost', author='hustlzp', author_email='[email protected]', license='MIT', keywords='flask sample generator', install_requires=requires, entry_points=entry_points, classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ], )
Allow passing existing express app to appFactory
var _ = require('lodash'), express = require('express'), STATIC_CACHE_AGE = 365 * 24 * 60 * 60 * 1000; // 1 year; module.exports = function confgureServer(config, app) { var app = app || express(); function serveIndex(request, response) { return response.sendFile('index.html', { root: config.appAssets.html.dest, headers: { 'Cache-Control': 'private' } }); } if (_.get(config, 'server.options.gzip')) { app.use(require('compression')()); } app.use(function checkForIndex(request, response, next) { var isIndex = request.url.match(/index\.html$/); if (isIndex) { serveIndex(request, response); } else { next(); } }); // Serve static assets app.use(express.static(config.destPath, { maxAge: _.get(config, 'server.options.cacheAge', STATIC_CACHE_AGE), index: false })); // Fall back to serving index, if no file is found app.get('*', serveIndex); return app; };
var _ = require('lodash'), express = require('express'), STATIC_CACHE_AGE = 365 * 24 * 60 * 60 * 1000; // 1 year; module.exports = function confgureServer(config) { var app = express(); function serveIndex(request, response) { return response.sendFile('index.html', { root: config.appAssets.html.dest, headers: { 'Cache-Control': 'private' } }); } if (_.get(config, 'server.options.gzip')) { app.use(require('compression')()); } app.use(function checkForIndex(request, response, next) { var isIndex = request.url.match(/index\.html$/); if (isIndex) { serveIndex(request, response); } else { next(); } }); app.use(express.static(config.destPath, { maxAge: _.get(config, 'server.options.cacheAge', STATIC_CACHE_AGE), index: false })); // Fall back to serving index, if no file is found app.get('*', serveIndex); return app; };
Fix install order to fix wrong caret line color
#!/usr/bin/env python # -*- coding: utf-8 -*- """ A simple example that shows how to setup CodeEdit. In this example, we install a syntax highlighter mode (based on pygments), a mode that highlights the current line and a _search and replace_ panel. There are many other modes and panels, feel free to use this example as a starting point to experiment. """ import logging logging.basicConfig(level=logging.DEBUG) import sys from pyqode.core import api from pyqode.core import modes from pyqode.core import panels from pyqode.qt import QtWidgets def main(): app = QtWidgets.QApplication(sys.argv) # create editor and window window = QtWidgets.QMainWindow() editor = api.CodeEdit() window.setCentralWidget(editor) # start the backend as soon as possible editor.backend.start('server.py') # append some modes and panels editor.modes.append(modes.CodeCompletionMode()) editor.modes.append(modes.CaretLineHighlighterMode()) editor.modes.append(modes.PygmentsSyntaxHighlighter(editor.document())) editor.panels.append(panels.SearchAndReplacePanel(), api.Panel.Position.BOTTOM) # open a file editor.file.open(__file__) # run window.show() app.exec_() editor.file.close() if __name__ == "__main__": main()
#!/usr/bin/env python # -*- coding: utf-8 -*- """ A simple example that shows how to setup CodeEdit. In this example, we install a syntax highlighter mode (based on pygments), a mode that highlights the current line and a _search and replace_ panel. There are many other modes and panels, feel free to use this example as a starting point to experiment. """ import logging logging.basicConfig(level=logging.DEBUG) import sys from pyqode.core import api from pyqode.core import modes from pyqode.core import panels from pyqode.qt import QtWidgets def main(): app = QtWidgets.QApplication(sys.argv) # create editor and window window = QtWidgets.QMainWindow() editor = api.CodeEdit() window.setCentralWidget(editor) # start the backend as soon as possible editor.backend.start('server.py') # append some modes and panels editor.modes.append(modes.CodeCompletionMode()) editor.modes.append(modes.PygmentsSyntaxHighlighter(editor.document())) editor.modes.append(modes.CaretLineHighlighterMode()) editor.panels.append(panels.SearchAndReplacePanel(), api.Panel.Position.BOTTOM) # open a file editor.file.open(__file__) # run window.show() app.exec_() editor.file.close() if __name__ == "__main__": main()
Add padding to color swatch headline.
/* @flow */ import React from 'react'; import Box from 'grommet/components/Box'; import Heading from 'grommet/components/Heading'; import { BlockParagraph } from '../BlockParagraph'; import Swatch from './swatch'; export default function BlockColorSwatch(props: { color: ?{ name: string, thumbColor: string, content: string } }) { const { color } = props; if (!color) { return null; } return ( <Box> <Swatch backgroundColor={color.thumbColor} /> <Heading tag="h4" strong margin="none" style={{ paddingTop: '12px' }} > {color.name} </Heading> {color.content && <BlockParagraph content={color.content} /> } </Box> ); }
/* @flow */ import React from 'react'; import Box from 'grommet/components/Box'; import Heading from 'grommet/components/Heading'; import { BlockParagraph } from '../BlockParagraph'; import Swatch from './swatch'; export default function BlockColorSwatch(props: { color: ?{ name: string, thumbColor: string, content: string } }) { const { color } = props; if (!color) { return null; } return ( <Box> <Swatch backgroundColor={color.thumbColor} /> <Heading tag="h4" strong margin="none"> {color.name} </Heading> {color.content && <BlockParagraph content={color.content} /> } </Box> ); }
Remove not essential parameters from config file
<?php return [ // View settings 'view' => [ 'extension' => 'twig' ], // Auth settings 'auth' => [ 'cookie_lifetime' => 86400, 'session_lifetime' => 3600, 'update_gap' => 1800, 'pull_user' => false ], // LDAP settings 'ldap' => [ 'hostname' => 'ldap.example.com', 'port' => 389, 'domain' => 'example.com' ], // Translator settings 'translator' => [ 'default_locale' => 'en' ], ];
<?php return [ // External router settings 'external_router' => [ 'default_url' => 'home', 'prefixes' => [], 'prefix_options' => [], 'data_type' => 'query_string', 'auto_trim' => true, 'auto_null' => true ], // Auth settings 'auth' => [ 'cookie_lifetime' => 86400, 'session_lifetime' => 3600, 'update_gap' => 1800, 'pull_user' => false ], // LDAP settings 'ldap' => [ 'hostname' => 'ldap.example.com', 'port' => 389, 'domain' => 'example.com' ], // Translator settings 'translator' => [ 'default_locale' => 'en' ], ];
Fix app-wrapper tests after merge from master Remove `wrapper` from `beforeEach`.
import React from 'react'; import TestUtils from 'react-dom/test-utils'; import { shallow } from 'enzyme'; import { rootTagTest } from '../../utils/helpers/tags/tags-specs'; import AppWrapper from './app-wrapper'; describe('app wrapper', () => { let instance; beforeEach(() => { instance = TestUtils.renderIntoDocument(<AppWrapper className='foobar'>foo</AppWrapper>); }); it('renders the children', () => { let div = TestUtils.findRenderedDOMComponentWithTag(instance, 'div'); expect(div.textContent).toEqual('foo'); }); it('renders with correct classes', () => { let div = TestUtils.findRenderedDOMComponentWithTag(instance, 'div'); expect(div.className).toEqual('carbon-app-wrapper foobar'); }); it('renders with additional html attributes', () => { instance = TestUtils.renderIntoDocument(<AppWrapper style={{ color: 'red' }}>foo</AppWrapper>); let div = TestUtils.findRenderedDOMComponentWithTag(instance, 'div'); expect(div.style.color).toEqual('red'); }); describe("tags", () => { describe("on component", () => { let wrapper = shallow(<AppWrapper data-element='bar' data-role='baz' />); it('include correct component, element and role data tags', () => { rootTagTest(wrapper, 'app-wrapper', 'bar', 'baz'); }); }); }); });
import React from 'react'; import TestUtils from 'react-dom/test-utils'; import { shallow } from 'enzyme'; import { rootTagTest } from '../../utils/helpers/tags/tags-specs'; import AppWrapper from './app-wrapper'; describe('app wrapper', () => { let instance; beforeEach(() => { instance = TestUtils.renderIntoDocument(<AppWrapper className='foobar'>foo</AppWrapper>); wrapper = shallow(<AppWrapper className='foobar' data-element='app-wrapper' data-role='contacts'>foo</AppWrapper>); }); it('renders the children', () => { let div = TestUtils.findRenderedDOMComponentWithTag(instance, 'div'); expect(div.textContent).toEqual('foo'); }); it('renders with correct classes', () => { let div = TestUtils.findRenderedDOMComponentWithTag(instance, 'div'); expect(div.className).toEqual('carbon-app-wrapper foobar'); }); it('renders with additional html attributes', () => { instance = TestUtils.renderIntoDocument(<AppWrapper style={{ color: 'red' }}>foo</AppWrapper>); let div = TestUtils.findRenderedDOMComponentWithTag(instance, 'div'); expect(div.style.color).toEqual('red'); }); describe("tags", () => { describe("on component", () => { let wrapper = shallow(<AppWrapper data-element='bar' data-role='baz' />); it('include correct component, element and role data tags', () => { rootTagTest(wrapper, 'app-wrapper', 'bar', 'baz'); }); }); }); });
Fix regression in path handling of TenantStaticFileStorage. Fixes #197.
import os from django.contrib.staticfiles.storage import StaticFilesStorage from django_tenants.files.storages import TenantStorageMixin from django.conf import settings from django.core.exceptions import ImproperlyConfigured class TenantStaticFilesStorage(TenantStorageMixin, StaticFilesStorage): """ Implementation that extends core Django's StaticFilesStorage. """ def __init__(self, location=None, base_url=None, *args, **kwargs): super(TenantStaticFilesStorage, self).__init__(location, base_url, *args, **kwargs) if hasattr(settings, "MULTITENANT_RELATIVE_STATIC_ROOT"): self.location = os.path.join(self.location, settings.MULTITENANT_RELATIVE_STATIC_ROOT) """ def path(self, name): if not hasattr(settings, "MULTITENANT_RELATIVE_STATIC_ROOT") or \ not settings.MULTITENANT_RELATIVE_STATIC_ROOT: raise ImproperlyConfigured("You're using the TenantStaticFilesStorage " "without having set the MULTITENANT_RELATIVE_STATIC_ROOT " "setting to a filesystem path.") return super(TenantStaticFilesStorage, self).path(name) """
import os from django.contrib.staticfiles.storage import StaticFilesStorage from django_tenants.files.storages import TenantStorageMixin from django.conf import settings from django.core.exceptions import ImproperlyConfigured class TenantStaticFilesStorage(TenantStorageMixin, StaticFilesStorage): """ Implementation that extends core Django's StaticFilesStorage. """ def __init__(self, location=None, base_url=None, *args, **kwargs): super(TenantStaticFilesStorage, self).__init__(location, base_url, *args, **kwargs) if hasattr(settings, "MULTITENANT_RELATIVE_STATIC_ROOT"): self.location = os.path.join(self.location, settings.MULTITENANT_RELATIVE_STATIC_ROOT) def path(self, name): """ if not hasattr(settings, "MULTITENANT_RELATIVE_STATIC_ROOT") or \ not settings.MULTITENANT_RELATIVE_STATIC_ROOT: raise ImproperlyConfigured("You're using the TenantStaticFilesStorage " "without having set the MULTITENANT_RELATIVE_STATIC_ROOT " "setting to a filesystem path.") """ return super(TenantStaticFilesStorage, self).path(name)
Fix type hint in neon loader trait
<?php /* * This is part of the symfonette/neon-integration package. * * (c) Martin Hasoň <[email protected]> * (c) Webuni s.r.o. <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfonette\NeonIntegration\HttpKernel; use Symfonette\NeonIntegration\DependencyInjection\NeonFileLoader; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\HttpKernel\Config\FileLocator; trait NeonContainerLoaderTrait { protected function getContainerLoader(ContainerInterface $container) { /* @var $loader \Symfony\Component\Config\Loader\Loader */ $loader = parent::getContainerLoader($container); $resolver = $loader->getResolver(); $resolver->addLoader(new NeonFileLoader($container, new FileLocator($this))); return $loader; } }
<?php /* * This is part of the symfonette/neon-integration package. * * (c) Martin Hasoň <[email protected]> * (c) Webuni s.r.o. <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfonette\NeonIntegration\HttpKernel; use Symfonette\NeonIntegration\DependencyInjection\NeonFileLoader; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\HttpKernel\Config\FileLocator; trait NeonContainerLoaderTrait { protected function getContainerLoader(ContainerBuilder $container) { /* @var $loader \Symfony\Component\Config\Loader\Loader */ $loader = parent::getContainerLoader($container); $resolver = $loader->getResolver(); $resolver->addLoader(new NeonFileLoader($container, new FileLocator($this))); return $loader; } }
Remove keyring and change to basic cfg file handling
#!/usr/local/bin/python2.7 -u __author__ = "Peter Shipley" import os import ConfigParser from ISY.IsyEvent import ISYEvent def main() : config = ConfigParser.ConfigParser() config.read(os.path.expanduser('~/home.cfg')) server = ISYEvent() isy_addr = config.get('isy', 'addr') isy_user = config.get('isy', 'user') isy_pass = config.get('isy', 'pass') server.subscribe( addr=isy_addr, userl=isy_user, userp=isy_pass ) server.set_process_func(ISYEvent.print_event, "") try: print('Use Control-C to exit') server.events_loop() #no return except KeyboardInterrupt: print('Exiting') if __name__ == '__main__' : main() exit(0)
#!/usr/local/bin/python2.7 -u __author__ = "Peter Shipley" import os import keyring import ConfigParser from ISY.IsyEvent import ISYEvent def main() : config = ConfigParser.ConfigParser() config.read(os.path.expanduser('~/isy.cfg')) server = ISYEvent() # you can subscribe to multiple devices # server.subscribe('10.1.1.25') isy_addr = config.get('isy', 'addr') isy_user = config.get('isy', 'user') server.subscribe( addr=isy_addr, userl=isy_user, userp=keyring.get_password("isy", isy_user) ) server.set_process_func(ISYEvent.print_event, "") try: print('Use Control-C to exit') server.events_loop() #no return # for d in server.event_iter( ignorelist=["_0", "_11"] ): # server.print_event(d, "") except KeyboardInterrupt: print('Exiting') if __name__ == '__main__' : main() exit(0)
Remove action_runner steps for worldjournal pageset to prevent crashes BUG=skia:3196 NOTRY=true Review URL: https://codereview.chromium.org/795173002
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=W0401,W0614 from telemetry.page import page as page_module from telemetry.page import page_set as page_set_module class SkiaBuildbotDesktopPage(page_module.Page): def __init__(self, url, page_set): super(SkiaBuildbotDesktopPage, self).__init__( url=url, page_set=page_set, credentials_path='data/credentials.json') self.user_agent_type = 'tablet' self.archive_data_file = 'data/skia_worldjournal_nexus10.json' class SkiaWorldjournalNexus10PageSet(page_set_module.PageSet): """ Pages designed to represent the median, not highly optimized web """ def __init__(self): super(SkiaWorldjournalNexus10PageSet, self).__init__( user_agent_type='tablet', archive_data_file='data/skia_worldjournal_nexus10.json') urls_list = [ # Why: Chinese font test case 'http://worldjournal.com/', ] for url in urls_list: self.AddPage(SkiaBuildbotDesktopPage(url, self))
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=W0401,W0614 from telemetry.page import page as page_module from telemetry.page import page_set as page_set_module class SkiaBuildbotDesktopPage(page_module.Page): def __init__(self, url, page_set): super(SkiaBuildbotDesktopPage, self).__init__( url=url, page_set=page_set, credentials_path='data/credentials.json') self.user_agent_type = 'tablet' self.archive_data_file = 'data/skia_worldjournal_nexus10.json' def RunSmoothness(self, action_runner): action_runner.ScrollElement() def RunNavigateSteps(self, action_runner): action_runner.NavigateToPage(self) action_runner.Wait(15) class SkiaWorldjournalNexus10PageSet(page_set_module.PageSet): """ Pages designed to represent the median, not highly optimized web """ def __init__(self): super(SkiaWorldjournalNexus10PageSet, self).__init__( user_agent_type='tablet', archive_data_file='data/skia_worldjournal_nexus10.json') urls_list = [ # Why: Chinese font test case 'http://worldjournal.com/', ] for url in urls_list: self.AddPage(SkiaBuildbotDesktopPage(url, self))
Change max length on home page search form
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from django.core.exceptions import ValidationError from candidates.mapit import BaseMapItException from popolo.models import Area from compat import text_type from .mapit import get_areas_from_postcode class PostcodeForm(forms.Form): q = forms.CharField( label='Enter a candidate name to start', max_length=200, widget=forms.TextInput(attrs={'placeholder': 'Enter a name'}) ) def clean_postcode(self): postcode = self.cleaned_data['postcode'] try: # Go to MapIt to check if this postcode is valid and # contained in a constituency. (If it's valid then the # result is cached, so this doesn't cause a double lookup.) get_areas_from_postcode(postcode) except BaseMapItException as e: raise ValidationError(text_type(e)) return postcode
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from django.core.exceptions import ValidationError from candidates.mapit import BaseMapItException from popolo.models import Area from compat import text_type from .mapit import get_areas_from_postcode class PostcodeForm(forms.Form): q = forms.CharField( label='Enter a candidate name to start', max_length=20, widget=forms.TextInput(attrs={'placeholder': 'Enter a name'}) ) def clean_postcode(self): postcode = self.cleaned_data['postcode'] try: # Go to MapIt to check if this postcode is valid and # contained in a constituency. (If it's valid then the # result is cached, so this doesn't cause a double lookup.) get_areas_from_postcode(postcode) except BaseMapItException as e: raise ValidationError(text_type(e)) return postcode
Make a better public constructor for that thing.
package edu.umass.cs.ciir.waltz.io.galago; import edu.umass.cs.ciir.waltz.io.streams.SkipInputStream; import edu.umass.cs.ciir.waltz.io.streams.StaticStream; import org.lemurproject.galago.utility.btree.disk.DiskBTreeIterator; import org.lemurproject.galago.utility.buffer.CachedBufferDataStream; import org.lemurproject.galago.utility.buffer.ReadableBuffer; import java.io.IOException; /** * @author jfoley */ class ReadableBufferStaticStream implements StaticStream { private final long start; private final long end; private final ReadableBuffer file; // Convenience method, probably shouldn't be here... public ReadableBufferStaticStream(DiskBTreeIterator iterator) throws IOException { this(iterator.input, iterator.getValueStart(), iterator.getValueEnd()); } public ReadableBufferStaticStream(ReadableBuffer file, long start, long end) throws IOException { this.start = start; this.end = end; this.file = file; } @Override public SkipInputStream getNewStream() { return new GalagoSkipInputStream(new CachedBufferDataStream(file, start, end)); } @Override public long length() { return end - start; } }
package edu.umass.cs.ciir.waltz.io.galago; import edu.umass.cs.ciir.waltz.io.streams.SkipInputStream; import edu.umass.cs.ciir.waltz.io.streams.StaticStream; import org.lemurproject.galago.utility.btree.disk.DiskBTreeIterator; import org.lemurproject.galago.utility.buffer.CachedBufferDataStream; import org.lemurproject.galago.utility.buffer.ReadableBuffer; import java.io.IOException; /** * @author jfoley */ class ReadableBufferStaticStream implements StaticStream { private final long start; private final long end; private final ReadableBuffer file; public ReadableBufferStaticStream(DiskBTreeIterator iterator) throws IOException { this.start = iterator.getValueStart(); this.end = iterator.getValueEnd(); this.file = iterator.input; } @Override public SkipInputStream getNewStream() { return new GalagoSkipInputStream(new CachedBufferDataStream(file, start, end)); } @Override public long length() { return end - start; } }
Remove the extra angular declaration from tests Browserify has already bundled angular on the main script.
'use strict'; var istanbul = require('browserify-istanbul'); var isparta = require('isparta'); module.exports = function(config) { config.set({ basePath: '../', frameworks: ['jasmine', 'browserify'], preprocessors: { 'app/js/**/*.js': ['browserify', 'babel', 'coverage'] }, browsers: ['Chrome'], reporters: ['progress', 'coverage'], autoWatch: true, browserify: { debug: true, transform: [ 'bulkify', istanbul({ instrumenter: isparta, ignore: ['**/node_modules/**', '**/test/**'] }) ] }, proxies: { '/': 'http://localhost:9876/' }, urlRoot: '/__karma__/', files: [ // app-specific code 'app/js/main.js', // 3rd-party resources 'node_modules/angular-mocks/angular-mocks.js', // test files 'test/unit/**/*.js' ] }); };
'use strict'; var istanbul = require('browserify-istanbul'); var isparta = require('isparta'); module.exports = function(config) { config.set({ basePath: '../', frameworks: ['jasmine', 'browserify'], preprocessors: { 'app/js/**/*.js': ['browserify', 'babel', 'coverage'] }, browsers: ['Chrome'], reporters: ['progress', 'coverage'], autoWatch: true, browserify: { debug: true, transform: [ 'bulkify', istanbul({ instrumenter: isparta, ignore: ['**/node_modules/**', '**/test/**'] }) ] }, proxies: { '/': 'http://localhost:9876/' }, urlRoot: '/__karma__/', files: [ // 3rd-party resources 'node_modules/angular/angular.min.js', 'node_modules/angular-mocks/angular-mocks.js', // app-specific code 'app/js/main.js', // test files 'test/unit/**/*.js' ] }); };
Add todo in jei plugin
package info.u_team.u_team_core.integration.jei; // TODO uncomment when jei is available again //import java.util.List; //import java.util.stream.Collectors; // //import info.u_team.u_team_core.UCoreMod; //import info.u_team.u_team_core.api.dye.IDyeableItem; //import mezz.jei.api.*; //import mezz.jei.api.constants.VanillaTypes; //import mezz.jei.api.registration.IRecipeRegistration; //import net.minecraft.item.*; //import net.minecraft.util.ResourceLocation; //import net.minecraftforge.registries.ForgeRegistries; // //@JeiPlugin //public class UTeamCoreJeiPlugin implements IModPlugin { // // private final ResourceLocation id = new ResourceLocation(UCoreMod.MODID, "jei"); // // @Override // public ResourceLocation getPluginUid() { // return id; // } // // @Override // public void registerRecipes(IRecipeRegistration registration) { // final List<ItemStack> items = ForgeRegistries.ITEMS.getValues().stream().filter(item -> item instanceof IDyeableItem || item instanceof IDyeableArmorItem).map(ItemStack::new).collect(Collectors.toList()); // registration.addIngredientInfo(items, VanillaTypes.ITEM, "jei.uteamcore.dyeable.info"); // } // //}
package info.u_team.u_team_core.integration.jei; //import java.util.List; //import java.util.stream.Collectors; // //import info.u_team.u_team_core.UCoreMod; //import info.u_team.u_team_core.api.dye.IDyeableItem; //import mezz.jei.api.*; //import mezz.jei.api.constants.VanillaTypes; //import mezz.jei.api.registration.IRecipeRegistration; //import net.minecraft.item.*; //import net.minecraft.util.ResourceLocation; //import net.minecraftforge.registries.ForgeRegistries; // //@JeiPlugin //public class UTeamCoreJeiPlugin implements IModPlugin { // // private final ResourceLocation id = new ResourceLocation(UCoreMod.MODID, "jei"); // // @Override // public ResourceLocation getPluginUid() { // return id; // } // // @Override // public void registerRecipes(IRecipeRegistration registration) { // final List<ItemStack> items = ForgeRegistries.ITEMS.getValues().stream().filter(item -> item instanceof IDyeableItem || item instanceof IDyeableArmorItem).map(ItemStack::new).collect(Collectors.toList()); // registration.addIngredientInfo(items, VanillaTypes.ITEM, "jei.uteamcore.dyeable.info"); // } // //}
Set limit for better sizing.
import React, { PropTypes, Component } from 'react'; import CakeChart from 'cake-chart'; function findParentNode(node, child, parent = null) { if (node === child) return parent; for (let c of child.children || []) { const p = findParentNode(node, c, child); if (p) return p; } } class AllTime extends Component { constructor(props) { super(props); this.state = { selectedNode: this.props.data }; } onClick(node) { if (node === this.state.selectedNode) { /* user clicked on the chart center - rendering parent node */ this.setState({ selectedNode: findParentNode(node, this.props.data) || this.props.data }); } else { this.setState({ selectedNode: node }); } } render() { return ( <div> <h4>Division 1 winners</h4> <CakeChart data={this.state.selectedNode} onClick={this.onClick} coreRadius={200} ringWidth={200} limit={2}/> </div> ); } } export default AllTime;
import React, { PropTypes, Component } from 'react'; import CakeChart from 'cake-chart'; function findParentNode(node, child, parent = null) { if (node === child) return parent; for (let c of child.children || []) { const p = findParentNode(node, c, child); if (p) return p; } } class AllTime extends Component { constructor(props) { super(props); this.state = { selectedNode: this.props.data }; } onClick(node) { if (node === this.state.selectedNode) { /* user clicked on the chart center - rendering parent node */ this.setState({ selectedNode: findParentNode(node, this.props.data) || this.props.data }); } else { this.setState({ selectedNode: node }); } } render() { return ( <div> <h4>Division 1 winners</h4> <CakeChart data={this.state.selectedNode} onClick={this.onClick} coreRadius={200} ringWidth={100}/> </div> ); } } export default AllTime;
Fix story parsing to support both windows and linux style newlines; Allow extra newlines between nodes
package bloople.net.stories; import java.io.IOException; import java.io.Reader; import java.util.Scanner; /** * Created by i on 27/05/2016. */ public class StoryParser { private Scanner scanner; public StoryParser(Reader reader) { scanner = new Scanner(reader); scanner.useDelimiter("(?:\r?\n){2,}+"); } public void parse(Story story) throws IOException { while(scanner.hasNext()) { story.add(next()); } } public Node next() throws IOException { String content = scanner.next(); if(content.startsWith("#")) { return NodeFactory.heading(content); } else { return NodeFactory.paragraph(content); } } }
package bloople.net.stories; import java.io.IOException; import java.io.Reader; import java.util.Scanner; /** * Created by i on 27/05/2016. */ public class StoryParser { private Scanner scanner; public StoryParser(Reader reader) { scanner = new Scanner(reader); scanner.useDelimiter("\n\n"); } public void parse(Story story) throws IOException { while(scanner.hasNext()) { story.add(next()); } } public Node next() throws IOException { String content = scanner.next(); if(content.startsWith("#")) { return NodeFactory.heading(content); } else { return NodeFactory.paragraph(content); } } }
Disable submit button while loading relations in unpublish dialog
(function () { "use strict"; function UnpublishController($scope, $controller, editorState, service) { var vm = this; angular.extend(this, $controller('Umbraco.Overlays.UnpublishController', { $scope: $scope })); vm.loading = true; vm.relations = []; vm.showLanguageColumn = false; $scope.model.disableSubmitButton = true; function init() { service.checkRelations(editorState.current.udi).then(function (data) { $scope.model.disableSubmitButton = false; vm.relations = data; vm.loading = false; }); } init(); } angular.module("umbraco").controller("Our.Umbraco.Nexu.Controllers.UnpublishController", [ '$scope', '$controller', 'editorState', 'Our.Umbraco.Nexu.Services.RelationCheckServive', UnpublishController]); })();
(function () { "use strict"; function UnpublishController($scope, $controller, editorState, service) { var vm = this; angular.extend(this, $controller('Umbraco.Overlays.UnpublishController', { $scope: $scope })); vm.loading = true; vm.relations = []; function init() { service.checkRelations(editorState.current.udi).then(function(data) { vm.relations = data; vm.loading = false; }); } init(); } angular.module("umbraco").controller("Our.Umbraco.Nexu.Controllers.UnpublishController", [ '$scope', '$controller', 'editorState', 'Our.Umbraco.Nexu.Services.RelationCheckServive', UnpublishController]); })();
Revert "Started exploring using argument but realizing this is a rabbit hole" This reverts commit b899d5613c0f4425aa4cc69bac9561b503ba83d4.
from os import path import shutil import sublime import sublime_plugin SUBLIME_ROOT = path.normpath(path.join(sublime.packages_path(), '..')) COMMANDS_FILEPATH = path.join('Packages', 'User', 'Commands.sublime-commands') COMMANDS_FULL_FILEPATH = path.join(SUBLIME_ROOT, COMMANDS_FILEPATH) COMMANDS_SOURCE_FULL_FILEPATH = path.abspath('default-prompt.json') class CommandsOpenCommand(sublime_plugin.WindowCommand): def run(self): """Open `Packages/User/Commands.sublime-commands` for custom definitions""" # If the User commands doesn't exist, provide a prompt if not path.exists(COMMANDS_FULL_FILEPATH): shutil.copy(COMMANDS_SOURCE_FULL_FILEPATH, COMMANDS_FULL_FILEPATH) # Open the User commands file view = self.window.open_file(COMMANDS_FULL_FILEPATH) # If the syntax is plain text, move to JSON if view.settings().get('syntax') == path.join('Packages', 'Text', 'Plain text.tmLanguage'): view.set_syntax_file(path.join('Packages', 'JavaScript', 'JSON.tmLanguage'))
from os import path import shutil import sublime import sublime_plugin SUBLIME_ROOT = path.normpath(path.join(sublime.packages_path(), '..')) COMMANDS_FILEPATH = path.join('Packages', 'User', 'Commands.sublime-commands') COMMANDS_FULL_FILEPATH = path.join(SUBLIME_ROOT, COMMANDS_FILEPATH) COMMANDS_SOURCE_FULL_FILEPATH = path.abspath('default-prompt.json') class CommandsOpenCommand(sublime_plugin.WindowCommand): def run(self, **kwargs): """Open `.sublime-commands` file for custom definitions""" # If no file is provided, default to `COMMANDS_FULL_FILEPATH` dest_filepath = kwargs.get('file', COMMANDS_FULL_FILEPATH) # If the file doesn't exist, provide a prompt if not path.exists(dest_filepath): shutil.copy(COMMANDS_SOURCE_FULL_FILEPATH, dest_filepath) # Open the User commands file view = self.window.open_file(dest_filepath) # If the syntax is plain text, move to JSON if view.settings().get('syntax') == path.join('Packages', 'Text', 'Plain text.tmLanguage'): view.set_syntax_file(path.join('Packages', 'JavaScript', 'JSON.tmLanguage'))
Remove trailing spaces in filenames FAT does not support trailing spaces, so we must remove them
package de.danoeh.antennapod.util; import java.util.Arrays; /** Generates valid filenames for a given string. */ public class FileNameGenerator { private static final char[] ILLEGAL_CHARACTERS = { '/', '\\', '?', '%', '*', ':', '|', '"', '<', '>' }; static { Arrays.sort(ILLEGAL_CHARACTERS); } private FileNameGenerator() { } /** * This method will return a new string that doesn't contain any illegal * characters of the given string. */ public static String generateFileName(String string) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); if (Arrays.binarySearch(ILLEGAL_CHARACTERS, c) < 0) { builder.append(c).replaceFirst(" *$",""); } } return builder.toString(); } public static long generateLong(final String str) { return str.hashCode(); } }
package de.danoeh.antennapod.util; import java.util.Arrays; /** Generates valid filenames for a given string. */ public class FileNameGenerator { private static final char[] ILLEGAL_CHARACTERS = { '/', '\\', '?', '%', '*', ':', '|', '"', '<', '>' }; static { Arrays.sort(ILLEGAL_CHARACTERS); } private FileNameGenerator() { } /** * This method will return a new string that doesn't contain any illegal * characters of the given string. */ public static String generateFileName(String string) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); if (Arrays.binarySearch(ILLEGAL_CHARACTERS, c) < 0) { builder.append(c); } } return builder.toString(); } public static long generateLong(final String str) { return str.hashCode(); } }
Replace more occurences of "group" with "category"
package org.monospark.actioncontrol.category; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.util.Collections; import java.util.Set; import java.util.stream.Collectors; import org.monospark.actioncontrol.config.ConfigParseException; import org.monospark.actioncontrol.config.ConfigParser; import org.spongepowered.api.entity.living.player.Player; public final class CategoryRegistry { private static final String PERMISSION_BASE = "actioncontrol.category."; private Set<Category> allCategories; CategoryRegistry() {} public void loadCategories(Path path) throws ConfigParseException { Path categoriesFile = path.resolve("categories.json"); File file = categoriesFile.toFile(); try { if(!file.exists()) { path.toFile().mkdir(); file.createNewFile(); this.allCategories = Collections.emptySet(); } else { this.allCategories = ConfigParser.parseConfig(categoriesFile); } } catch (IOException e) { throw new ConfigParseException(e); } } public Set<Category> getCategories(Player p) { return allCategories.stream() .filter(c -> /* p.hasPermission(PERMISSION_BASE + c.getName()) */ true) .collect(Collectors.toSet()); } }
package org.monospark.actioncontrol.category; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.util.Collections; import java.util.Set; import java.util.stream.Collectors; import org.monospark.actioncontrol.config.ConfigParseException; import org.monospark.actioncontrol.config.ConfigParser; import org.spongepowered.api.entity.living.player.Player; public final class CategoryRegistry { private static final String PERMISSION_BASE = "actioncontrol.category."; private Set<Category> allCategories; CategoryRegistry() {} public void loadCategories(Path path) throws ConfigParseException { Path groupsFile = path.resolve("categories.json"); File file = groupsFile.toFile(); try { if(!file.exists()) { path.toFile().mkdir(); file.createNewFile(); this.allCategories = Collections.emptySet(); } else { this.allCategories = ConfigParser.parseConfig(groupsFile); } } catch (IOException e) { throw new ConfigParseException(e); } } public Set<Category> getCategories(Player p) { return allCategories.stream() .filter(c -> /* p.hasPermission(PERMISSION_BASE + c.getName()) */ true) .collect(Collectors.toSet()); } }
Use __invert__ instead of __not__
import operator from datashape import dshape from .core import Scalar, BinOp, UnaryOp class BooleanInterface(Scalar): def __invert__(self): return Invert(self) def __and__(self, other): return And(self, other) def __or__(self, other): return Or(self, other) class Boolean(BooleanInterface): @property def dshape(self): return dshape('bool') class Relational(BinOp, Boolean): pass class Eq(Relational): symbol = '==' op = operator.eq class Ne(Relational): symbol = '!=' op = operator.ne class Ge(Relational): symbol = '>=' op = operator.ge class Le(Relational): symbol = '<=' op = operator.le class Gt(Relational): symbol = '>' op = operator.gt class Lt(Relational): symbol = '<' op = operator.lt class And(BinOp, Boolean): symbol = '&' op = operator.and_ class Or(BinOp, Boolean): symbol = '|' op = operator.or_ class Not(UnaryOp, Boolean): symbol = '~' op = operator.not_ Invert = Not BitAnd = And BitOr = Or
import operator from datashape import dshape from .core import Scalar, BinOp, UnaryOp class BooleanInterface(Scalar): def __not__(self): return Not(self) def __and__(self, other): return And(self, other) def __or__(self, other): return Or(self, other) class Boolean(BooleanInterface): @property def dshape(self): return dshape('bool') class Relational(BinOp, Boolean): pass class Eq(Relational): symbol = '==' op = operator.eq class Ne(Relational): symbol = '!=' op = operator.ne class Ge(Relational): symbol = '>=' op = operator.ge class Le(Relational): symbol = '<=' op = operator.le class Gt(Relational): symbol = '>' op = operator.gt class Lt(Relational): symbol = '<' op = operator.lt class And(BinOp, Boolean): symbol = '&' op = operator.and_ class Or(BinOp, Boolean): symbol = '|' op = operator.or_ class Not(UnaryOp, Boolean): op = operator.not_ Invert = Not BitAnd = And BitOr = Or
Add IOError custom message when rsa key file is missing.
from django.conf import settings as django_settings from django.core.urlresolvers import reverse from oidc_provider import settings def get_issuer(): """ Construct the issuer full url. Basically is the site url with some path appended. """ site_url = settings.get('SITE_URL') path = reverse('oidc_provider:provider_info') \ .split('/.well-known/openid-configuration/')[0] issuer = site_url + path return issuer def get_rsa_key(): """ Load the rsa key previously created with `creatersakey` command. """ file_path = settings.get('OIDC_RSA_KEY_FOLDER') + '/OIDC_RSA_KEY.pem' try: with open(file_path, 'r') as f: key = f.read() except IOError: raise IOError('We could not find your key file on: ' + file_path) return key
from django.conf import settings as django_settings from django.core.urlresolvers import reverse from oidc_provider import settings def get_issuer(): """ Construct the issuer full url. Basically is the site url with some path appended. """ site_url = settings.get('SITE_URL') path = reverse('oidc_provider:provider_info') \ .split('/.well-known/openid-configuration/')[0] issuer = site_url + path return issuer def get_rsa_key(): """ Load the rsa key previously created with `creatersakey` command. """ file_path = settings.get('OIDC_RSA_KEY_FOLDER') + '/OIDC_RSA_KEY.pem' with open(file_path, 'r') as f: key = f.read() return key
Fix compatibility with Node.js v4.x The callback for the `message` event on the cluster is invoked without the `worker` argument in Node.js v4.x. This commit fixes the issue by using the `message` event that is emitted on the workers.
'use strict'; const impl = process.argv[2]; if (!impl) { console.error('No implementation provided'); process.exit(1); } switch (impl) { case 'ws': case 'uws': case 'faye': break; default: console.error(`Implementation: ${impl} not valid`); process.exit(1); } const cluster = require('cluster'); const numCPUs = require('os').cpus().length; if (cluster.isMaster) { const onMessage = function (msg) { Object.keys(cluster.workers).forEach((id) => { if (+id !== this.id) { cluster.workers[id].send(msg); } }); }; cluster.on('fork', (worker) => worker.on('message', onMessage)); // Fork workers. for (var i = 0; i < numCPUs; i++) { cluster.fork(); } const onExit = () => { cluster.removeAllListeners('exit'); Object.keys(cluster.workers).forEach((id) => { cluster.workers[id].kill(); }); }; process .on('SIGINT', onExit) .on('SIGTERM', onExit); cluster.on('exit', (worker, code, signal) => { console.log(`worker ${worker.process.pid} died`); setTimeout(() => cluster.fork(), 1000); }); } else { require(`./${impl}/`); }
'use strict'; const impl = process.argv[2]; if (!impl) { console.error('No implementation provided'); process.exit(1); } switch (impl) { case 'ws': case 'uws': case 'faye': break; default: console.error(`Implementation: ${impl} not valid`); process.exit(1); } const cluster = require('cluster'); const numCPUs = require('os').cpus().length; if (cluster.isMaster) { // Fork workers. for (var i = 0; i < numCPUs; i++) { cluster.fork(); } let onExit = () => { cluster.removeAllListeners('exit'); Object.keys(cluster.workers).forEach((id) => { cluster.workers[id].kill(); }); }; process .on('SIGINT', onExit) .on('SIGTERM', onExit); cluster.on('exit', (worker, code, signal) => { console.log(`worker ${worker.process.pid} died`); setTimeout(() => cluster.fork(), 1000); }); cluster.on('message', (worker, msg) => { Object.keys(cluster.workers).forEach((id) => { if (parseInt(id) !== worker.id) { cluster.workers[id].send(msg); } }); }); } else { require(`./${impl}/`); }
Change yield to yield from ...because yield from does actually work with 2.0.x-dev and PHP 7. I'm sorry. :(
#!/usr/bin/env php <?php require dirname(__DIR__) . '/vendor/autoload.php'; use Icicle\Coroutine; use Icicle\Dns\Resolver\Resolver; use Icicle\Loop; if (2 > $argc) { throw new InvalidArgumentException('Too few arguments provided. Usage: {DomainName}'); } $domain = $argv[1]; $coroutine = Coroutine\create(function ($query, $timeout = 1) { printf("Query: %s\n", $query); $resolver = new Resolver(); $ips = yield from $resolver->resolve($query, ['timeout' => $timeout]); foreach ($ips as $ip) { printf("IP: %s\n", $ip); } }, $domain); $coroutine->capture(function (Exception $e) { printf("Exception: %s\n", $e->getMessage()); }); Loop\run();
#!/usr/bin/env php <?php require dirname(__DIR__) . '/vendor/autoload.php'; use Icicle\Coroutine; use Icicle\Dns\Resolver\Resolver; use Icicle\Loop; if (2 > $argc) { throw new InvalidArgumentException('Too few arguments provided. Usage: {DomainName}'); } $domain = $argv[1]; $coroutine = Coroutine\create(function ($query, $timeout = 1) { printf("Query: %s\n", $query); $resolver = new Resolver(); $ips = yield $resolver->resolve($query, ['timeout' => $timeout]); foreach ($ips as $ip) { printf("IP: %s\n", $ip); } }, $domain); $coroutine->capture(function (Exception $e) { printf("Exception: %s\n", $e->getMessage()); }); Loop\run();
[core] Add try/catch around asset importing and emit error to stream
import through from 'through2' import getAssetImporter from './getAssetImporter' import promiseEach from 'promise-each-concurrency' const batchSize = 10 const concurrency = 6 export default options => { const assetImporter = getAssetImporter(options) const documents = [] return through.obj(onChunk, onFlush) async function uploadAssets(stream, cb) { try { await promiseEach(documents, assetImporter.processDocument, {concurrency}) } catch (err) { cb(err) return } while (documents.length > 0) { stream.push(documents.shift()) } cb() } function onChunk(chunk, enc, cb) { const newLength = documents.push(chunk) if (newLength !== batchSize) { return cb() } return uploadAssets(this, cb) } function onFlush(cb) { if (documents.length === 0) { cb() return } uploadAssets(this, cb) } }
import through from 'through2' import getAssetImporter from './getAssetImporter' import promiseEach from 'promise-each-concurrency' const batchSize = 10 const concurrency = 6 export default options => { const assetImporter = getAssetImporter(options) const documents = [] return through.obj(onChunk, onFlush) async function uploadAssets(stream, cb) { await promiseEach(documents, assetImporter.processDocument, {concurrency}) while (documents.length > 0) { stream.push(documents.shift()) } cb() } function onChunk(chunk, enc, cb) { const newLength = documents.push(chunk) if (newLength !== batchSize) { return cb() } return uploadAssets(this, cb) } function onFlush(cb) { if (documents.length === 0) { cb() return } uploadAssets(this, cb) } }
Fix exception when trying to login with non-existing user
package se.kits.gakusei.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import se.kits.gakusei.user.model.User; import se.kits.gakusei.user.repository.UserRepository; @Service("userDetailsService") public class UserDetailsServiceImpl implements UserDetailsService { private final UserRepository repository; @Autowired public UserDetailsServiceImpl(UserRepository repository) { this.repository = repository; } @Override public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException { User user = this.repository.findByUsername(name); if (user == null) throw new UsernameNotFoundException("User not found: " + name); return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), AuthorityUtils.createAuthorityList(user.getRole())); } }
package se.kits.gakusei.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import se.kits.gakusei.user.model.User; import se.kits.gakusei.user.repository.UserRepository; @Service("userDetailsService") public class UserDetailsServiceImpl implements UserDetailsService { private final UserRepository repository; @Autowired public UserDetailsServiceImpl(UserRepository repository) { this.repository = repository; } @Override public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException { User user = this.repository.findByUsername(name); return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), AuthorityUtils.createAuthorityList(user.getRole())); } }
Fix max number to use parseInt
process.stdin.resume(); process.stdin.setEncoding('utf8'); var input = ''; process.stdin.on('data', function(chunk) { input += chunk; }); process.stdin.on('end', function() { var lines = input.trim().split('\n'); if (lines.length > 0) { var max = parseInt(lines[0], 10); for (var i = 0; i < max; i++) { var n = i + 1; if ((n % 3 === 0) && (n % 5 === 0)) { console.log('Fizz Buzz'); } else if (n % 3 === 0) { console.log('Fizz'); } else if (n % 5 === 0) { console.log('Buzz'); } else { console.log(n); } } } });
process.stdin.resume(); process.stdin.setEncoding('utf8'); var input = ''; process.stdin.on('data', function(chunk) { input += chunk; }); process.stdin.on('end', function() { var lines = input.trim().split('\n'); if (lines.length > 0) { var max = lines[0]; for (var i = 0; i < max; i++) { var n = i + 1; if ((n % 3 === 0) && (n % 5 === 0)) { console.log('Fizz Buzz'); } else if (n % 3 === 0) { console.log('Fizz'); } else if (n % 5 === 0) { console.log('Buzz'); } else { console.log(n); } } } });
CDEC-72: Add trial.codenvy.com package as IM download option
/* * CODENVY CONFIDENTIAL * __________________ * * [2012] - [2014] Codenvy, S.A. * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Codenvy S.A. and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Codenvy S.A. * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Codenvy S.A.. */ package com.codenvy.im.artifacts; import static com.codenvy.im.utils.InjectorBootstrap.INJECTOR; /** @author Anatoliy Bazko */ public class ArtifactFactory { /** Artifact factory. */ public static Artifact createArtifact(String name) { switch (name) { case CDECArtifact.NAME: return INJECTOR.getInstance(CDECArtifact.class); case InstallManagerArtifact.NAME: return INJECTOR.getInstance(InstallManagerArtifact.class); case TrialCDECArtifact.NAME: return INJECTOR.getInstance(TrialCDECArtifact.class); } throw new IllegalArgumentException("Artifact '" + name + "' not found"); } }
/* * CODENVY CONFIDENTIAL * __________________ * * [2012] - [2014] Codenvy, S.A. * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Codenvy S.A. and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Codenvy S.A. * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Codenvy S.A.. */ package com.codenvy.im.artifacts; import static com.codenvy.im.utils.InjectorBootstrap.INJECTOR; /** @author Anatoliy Bazko */ public class ArtifactFactory { /** Artifact factory. */ public static Artifact createArtifact(String name) { switch (name) { case CDECArtifact.NAME: return INJECTOR.getInstance(CDECArtifact.class); case InstallManagerArtifact.NAME: return INJECTOR.getInstance(InstallManagerArtifact.class); } throw new IllegalArgumentException("Artifact '" + name + "' not found"); } }
Replace `replaceAll` with `replace` for better perfomance if the first argument is not a real regular expression, String::replace does exactly the same thing as String::replaceAll without the performance drawback.
package de.retest.recheck.persistence.xml.util; import javax.xml.bind.Marshaller; import de.retest.recheck.ui.descriptors.IdentifyingAttributesAdapter; import de.retest.recheck.ui.descriptors.RenderContainedElementsAdapter; import de.retest.recheck.ui.descriptors.StateAttributesAdapter; public class XmlUtil { private XmlUtil() {} public static String clean( final Object input ) { if ( input == null ) { return null; } String result = input.toString().trim(); result = result.replace( "&", "&amp;" ); result = result.replace( "<", "&lt;" ); result = result.replace( ">", "&gt;" ); result = result.replace( "\"", "'" ); return result; } public static void addLightWeightAdapter( final Marshaller marshaller ) { marshaller.setAdapter( new RenderContainedElementsAdapter( true ) ); marshaller.setAdapter( new StateAttributesAdapter( true ) ); marshaller.setAdapter( new IdentifyingAttributesAdapter( true ) ); } }
package de.retest.recheck.persistence.xml.util; import javax.xml.bind.Marshaller; import de.retest.recheck.ui.descriptors.IdentifyingAttributesAdapter; import de.retest.recheck.ui.descriptors.RenderContainedElementsAdapter; import de.retest.recheck.ui.descriptors.StateAttributesAdapter; public class XmlUtil { private XmlUtil() {} public static String clean( final Object input ) { if ( input == null ) { return null; } String result = input.toString().trim(); result = result.replaceAll( "&", "&amp;" ); result = result.replaceAll( "<", "&lt;" ); result = result.replaceAll( ">", "&gt;" ); result = result.replaceAll( "\"", "'" ); return result; } public static void addLightWeightAdapter( final Marshaller marshaller ) { marshaller.setAdapter( new RenderContainedElementsAdapter( true ) ); marshaller.setAdapter( new StateAttributesAdapter( true ) ); marshaller.setAdapter( new IdentifyingAttributesAdapter( true ) ); } }
Fix a tab/space issue coming up on github
/** * Has Vowels * * hasVowel tests if the String calling the function has a vowels * * @param {void} * @return {Boolean} returns true or false indicating if the string * has a vowel or not */ String.prototype.hasVowels = function() { var inputString = this; return /[aeiou]/gi.test(inputString); }; /** * To Upper * * toUpper converts its calling string to all uppercase characters * * @param {void} * @return {String} returns an upperCase version of the calling string */ String.prototype.toUpper = function() { // the 'this' keyword represents the string calling the function return this.replace(/[a-z]/g, function(item, position, string) { return String.fromCharCode(string.charCodeAt(position)-32); }); }; String.prototype.toLower = function() { // the 'this' keyword represents the string calling the function return this.replace(/[A-Z]/g, function(item, position, string) { return String.fromCharCode(string.charCodeAt(position)+32); }); }; /** * Uc First * * ucFirst capitalises the first character of its calling string * * @param {void} * @return {String} returns the calling string with the first character * capitalised */ String.prototype.ucFirst = function() { // get the first character return this.replace(/^[a-z]/g, function(item, position, string) { return item.toUpper(); }); };
/** * Has Vowels * * hasVowel tests if the String calling the function has a vowels * * @param {void} * @return {Boolean} returns true or false indicating if the string * has a vowel or not */ String.prototype.hasVowels = function() { var inputString = this; return /[aeiou]/gi.test(inputString); }; /** * To Upper * * toUpper converts its calling string to all uppercase characters * * @param {void} * @return {String} returns an upperCase version of the calling string */ String.prototype.toUpper = function() { // the 'this' keyword represents the string calling the function return this.replace(/[a-z]/g, function(item, position, string) { return String.fromCharCode(string.charCodeAt(position)-32); }); }; String.prototype.toLower = function() { // the 'this' keyword represents the string calling the function return this.replace(/[A-Z]/g, function(item, position, string) { return String.fromCharCode(string.charCodeAt(position)+32); }); }; /** * Uc First * * ucFirst capitalises the first character of its calling string * * @param {void} * @return {String} returns the calling string with the first character * capitalised */ String.prototype.ucFirst = function() { return this.replace(/^[a-z]/g, function(item, position, string) { return item.toUpper(); }); };
Fix api key in http request header Follow the header name of skygear-server.
package model import ( "net/http" "strconv" "github.com/skygeario/skygear-server/pkg/core/config" ) type KeyType int const ( // NoAccessKey means no correct access key NoAccessKey KeyType = iota // APIAccessKey means request is using api key APIAccessKey // MasterAccessKey means request is using master key MasterAccessKey ) func header(i interface{}) http.Header { switch i.(type) { case *http.Request: return (i.(*http.Request)).Header case http.ResponseWriter: return (i.(http.ResponseWriter)).Header() default: panic("Invalid type") } } func GetAccessKeyType(i interface{}) KeyType { ktv, err := strconv.Atoi(header(i).Get("X-Skygear-AccessKeyType")) if err != nil { return NoAccessKey } return KeyType(ktv) } func SetAccessKeyType(i interface{}, kt KeyType) { header(i).Set("X-Skygear-AccessKeyType", strconv.Itoa(int(kt))) } func GetAPIKey(i interface{}) string { return header(i).Get("X-Skygear-Api-Key") } func CheckAccessKeyType(config config.TenantConfiguration, apiKey string) KeyType { if apiKey == config.APIKey { return APIAccessKey } if apiKey == config.MasterKey { return MasterAccessKey } return NoAccessKey }
package model import ( "net/http" "strconv" "github.com/skygeario/skygear-server/pkg/core/config" ) type KeyType int const ( // NoAccessKey means no correct access key NoAccessKey KeyType = iota // APIAccessKey means request is using api key APIAccessKey // MasterAccessKey means request is using master key MasterAccessKey ) func header(i interface{}) http.Header { switch i.(type) { case *http.Request: return (i.(*http.Request)).Header case http.ResponseWriter: return (i.(http.ResponseWriter)).Header() default: panic("Invalid type") } } func GetAccessKeyType(i interface{}) KeyType { ktv, err := strconv.Atoi(header(i).Get("X-Skygear-AccessKeyType")) if err != nil { return NoAccessKey } return KeyType(ktv) } func SetAccessKeyType(i interface{}, kt KeyType) { header(i).Set("X-Skygear-AccessKeyType", strconv.Itoa(int(kt))) } func GetAPIKey(i interface{}) string { return header(i).Get("X-Skygear-APIKey") } func CheckAccessKeyType(config config.TenantConfiguration, apiKey string) KeyType { if apiKey == config.APIKey { return APIAccessKey } if apiKey == config.MasterKey { return MasterAccessKey } return NoAccessKey }
Make sure vertices really get added to the graph. Duh. git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@4044 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3
package edu.umd.cs.findbugs.ba.ch; import java.util.HashMap; import java.util.Map; import edu.umd.cs.findbugs.graph.AbstractGraph; public class ClassHierarchyGraph extends AbstractGraph<ClassHierarchyGraphEdge, ClassHierarchyGraphVertex> { private Map<String, ClassHierarchyGraphVertex> vertexMap; public ClassHierarchyGraph() { this.vertexMap = new HashMap<String, ClassHierarchyGraphVertex>(); } public ClassHierarchyGraphVertex lookupVertex(String className) { return vertexMap.get(className); } public ClassHierarchyGraphVertex addVertex( String className, ClassHierarchyGraphVertexType vertexType) { ClassHierarchyGraphVertex vertex = lookupVertex(className); if (vertex == null) { vertex = new ClassHierarchyGraphVertex(className, vertexType); vertexMap.put(className, vertex); addVertex(vertex); } return vertex; } //@Override protected ClassHierarchyGraphEdge allocateEdge(ClassHierarchyGraphVertex source, ClassHierarchyGraphVertex target) { return new ClassHierarchyGraphEdge(source, target); } }
package edu.umd.cs.findbugs.ba.ch; import java.util.HashMap; import java.util.Map; import edu.umd.cs.findbugs.graph.AbstractGraph; public class ClassHierarchyGraph extends AbstractGraph<ClassHierarchyGraphEdge, ClassHierarchyGraphVertex> { private Map<String, ClassHierarchyGraphVertex> vertexMap; public ClassHierarchyGraph() { this.vertexMap = new HashMap<String, ClassHierarchyGraphVertex>(); } public ClassHierarchyGraphVertex lookupVertex(String className) { return vertexMap.get(className); } public ClassHierarchyGraphVertex addVertex( String className, ClassHierarchyGraphVertexType vertexType) { ClassHierarchyGraphVertex vertex = lookupVertex(className); if (vertex == null) { vertex = new ClassHierarchyGraphVertex(className, vertexType); vertexMap.put(className, vertex); } return vertex; } //@Override protected ClassHierarchyGraphEdge allocateEdge(ClassHierarchyGraphVertex source, ClassHierarchyGraphVertex target) { return new ClassHierarchyGraphEdge(source, target); } }
Add beginning and end args to GetGames
import logging from version import __version__ logger = logging.getLogger(__name__) logger.debug('Loading %s ver %s' % (__name__, __version__)) # Actions represents the available textual items that can be passed to main # to drive dispatch. These should be all lower case, no spaces or underscores. actions = [ 'collect', 'update', 'testignore', # Allows the bin app to be run without calling into here. ] def GetDataForGame(game): pass def GetDataForGames(games=[]): for game in games: GetDataForGame(game) def GetGames(active=True, beginning=None, end=None): """ Return a tuple of games. Updates gets finished games to check for updated stats, if False (default) it returns active games. beginning and end allow you set a range for the search, with no end indicating until the time. """ def main(action='collect'): """ The main entry point for the application """ logger.debug('Dispatching action %s' % action) # By default, we collect info on current games if action == 'collect': GetDataForGames(GetGames(active=True)) # Otherwise we can look to update finished games elif action == 'update': GetDataForGames(GetGames(active=False)) elif action in actions: raise NotImplementedError('Action "%s" is known, but not (yet?) implemented' % action) else: raise ValueError('Unknown action "%s"' % action)
import logging from version import __version__ logger = logging.getLogger(__name__) logger.debug('Loading %s ver %s' % (__name__, __version__)) # Actions represents the available textual items that can be passed to main # to drive dispatch. These should be all lower case, no spaces or underscores. actions = [ 'collect', 'update', 'testignore', # Allows the bin app to be run without calling into here. ] def GetDataForGame(game): pass def GetDataForGames(games=[]): for game in games: GetDataForGame(game) def GetGames(active=True): """ Return a tuple of games. Updates gets finished games to check for updated stats, if False (default) it returns active games. """ def main(action='collect'): """ The main entry point for the application """ logger.debug('Dispatching action %s' % action) # By default, we collect info on current games if action == 'collect': GetDataForGames(GetGames(active=True)) # Otherwise we can look to update finished games elif action == 'update': GetDataForGames(GetGames(active=False)) elif action in actions: raise NotImplementedError('Action "%s" is known, but not (yet?) implemented' % action) else: raise ValueError('Unknown action "%s"' % action)
BAP-11409: Create Language entity - updated unit test
<?php namespace Oro\Bundle\TranslationBundle\Tests\Unit\Entity; use Oro\Bundle\OrganizationBundle\Entity\Organization; use Oro\Bundle\TranslationBundle\Entity\Language; use Oro\Bundle\UserBundle\Entity\User; use Oro\Component\Testing\Unit\EntityTestCaseTrait; class LanguageTest extends \PHPUnit_Framework_TestCase { use EntityTestCaseTrait; public function testAccessors() { $this->assertPropertyAccessors(new Language(), [ ['id', 1], ['code', 'test_code'], ['enabled', true], ['installedBuildDate', new \DateTime()], ['owner', new User()], ['organization', new Organization()], ['createdAt', new \DateTime()], ['updatedAt', new \DateTime()], ]); } }
<?php namespace Oro\Bundle\TranslationBundle\Tests\Unit\Entity; use Oro\Bundle\OrganizationBundle\Entity\Organization; use Oro\Bundle\TranslationBundle\Entity\Language; use Oro\Bundle\UserBundle\Entity\User; use Oro\Component\Testing\Unit\EntityTestCaseTrait; class LanguageTest extends \PHPUnit_Framework_TestCase { use EntityTestCaseTrait; public function testAccessors() { $this->assertPropertyAccessors(new Language(), [ ['id', 1], ['code', 'test_code'], ['installedBuildDate', new \DateTime()], ['owner', new User()], ['organization', new Organization()], ['createdAt', new \DateTime()], ['updatedAt', new \DateTime()], ]); } }
Move QGL import inside function A channel library is not always available
from . import bbn import auspex.config from auspex.log import logger def pulse_marker(marker_name, length = 100e-9): """ Utility to generate a square pulse on a APS2 marker. Used for instance to switch a signal between spectrum analyzer and input line marker_name as defined in measure.yaml """ from QGL import * ChannelLibrary() settings = auspex.config.load_meas_file(auspex.config.find_meas_file()) mkr = settings['markers'][marker_name] marker = MarkerFactory(marker_name) APS_name = mkr.split()[0] APS = bbn.APS2() APS.connect(settings['instruments'][APS_name]['address']) APS.set_trigger_source('Software') seq = [[TRIG(marker,length)]] APS.set_seq_file(compile_to_hardware(seq, 'Switch\Switch').replace('meta.json', APS_name+'.h5')) APS.run() APS.trigger() APS.stop() APS.disconnect() logger.info('Switched marker {} ({})'.format(marker_name, mkr))
from . import bbn import auspex.config from auspex.log import logger from QGL import * ChannelLibrary() def pulse_marker(marker_name, length = 100e-9): """ Utility to generate a square pulse on a APS2 marker. Used for instance to switch a signal between spectrum analyzer and input line marker_name as defined in measure.yaml """ settings = auspex.config.load_meas_file(auspex.config.find_meas_file()) mkr = settings['markers'][marker_name] marker = MarkerFactory(marker_name) APS_name = mkr.split()[0] APS = bbn.APS2() APS.connect(settings['instruments'][APS_name]['address']) APS.set_trigger_source('Software') seq = [[TRIG(marker,length)]] APS.set_seq_file(compile_to_hardware(seq, 'Switch\Switch').replace('meta.json', APS_name+'.h5')) APS.run() APS.trigger() APS.stop() APS.disconnect() logger.info('Switched marker {} ({})'.format(marker_name, mkr))
Set editing border color to lightgrey
var rows = 0; var cols = 10; var table; var edit_border = "thin dotted lightgrey"; function text(str) { return document.createTextNode(str); } function cellContents(rowindex, colindex) { return "&nbsp;"; } function init() { table = document.getElementById("wftable"); addRows(4); } function addRows(numrows) { numrows += rows; if (table.tBodies.length < 1) { table.appendChild(document.createElement('tbody')); } for (; rows < numrows; rows++) { table.tBodies[table.tBodies.length - 1].appendChild(text("\n")); var row = table.insertRow(-1); row.appendChild(text("\n")); for (c = 0; c < cols; c++) { var cell = row.insertCell(-1); cell.innerHTML = cellContents(rows, c); cell.style.border = edit_border; row.appendChild(text("\n")); } } } function addCols(numcols) { cols += numcols; for (r = 0; r < rows; r++) { var row = table.rows[r]; for (c = row.cells.length; c < cols; c++) { var cell = row.insertCell(-1); cell.innerHTML = cellContents(r, c); cell.style.border = edit_border; row.appendChild(text("\n")); } } }
var rows = 0; var cols = 10; var table; var edit_border = "thin dotted grey"; function text(str) { return document.createTextNode(str); } function cellContents(rowindex, colindex) { return "&nbsp;"; } function init() { table = document.getElementById("wftable"); addRows(4); } function addRows(numrows) { numrows += rows; if (table.tBodies.length < 1) { table.appendChild(document.createElement('tbody')); } for (; rows < numrows; rows++) { table.tBodies[table.tBodies.length - 1].appendChild(text("\n")); var row = table.insertRow(-1); row.appendChild(text("\n")); for (c = 0; c < cols; c++) { var cell = row.insertCell(-1); cell.innerHTML = cellContents(rows, c); cell.style.border = edit_border; row.appendChild(text("\n")); } } } function addCols(numcols) { cols += numcols; for (r = 0; r < rows; r++) { var row = table.rows[r]; for (c = row.cells.length; c < cols; c++) { var cell = row.insertCell(-1); cell.innerHTML = cellContents(r, c); cell.style.border = edit_border; row.appendChild(text("\n")); } } }
Fix test to pass model not nothing We were passing a value that doesn't exist and we need to pass the model into administeredSchools.
import { currentURL, visit } from '@ember/test-helpers'; import { module, test } from 'qunit'; import setupAuthentication from 'ilios/tests/helpers/setup-authentication'; import { percySnapshot } from 'ember-percy'; import { setupApplicationTest } from 'ember-qunit'; import setupMirage from 'ember-cli-mirage/test-support/setup-mirage'; import { getElementText, getText } from 'ilios/tests/helpers/custom-helpers'; module('Acceptance: assign students', function(hooks) { setupApplicationTest(hooks); setupMirage(hooks); hooks.beforeEach(async function () { const school = this.server.create('school'); await setupAuthentication({ school, administeredSchools: [school] }); this.server.create('school'); }); test('visiting /admin/assignstudents', async function(assert) { await visit('/admin/assignstudents'); assert.equal(await getElementText('.schoolsfilter'), getText('school 0')); assert.equal(currentURL(), '/admin/assignstudents'); percySnapshot(assert); }); });
import { currentURL, visit } from '@ember/test-helpers'; import { module, test } from 'qunit'; import setupAuthentication from 'ilios/tests/helpers/setup-authentication'; import { percySnapshot } from 'ember-percy'; import { setupApplicationTest } from 'ember-qunit'; import setupMirage from 'ember-cli-mirage/test-support/setup-mirage'; import { getElementText, getText } from 'ilios/tests/helpers/custom-helpers'; module('Acceptance: assign students', function(hooks) { setupApplicationTest(hooks); setupMirage(hooks); hooks.beforeEach(async function () { const school = this.server.create('school'); await setupAuthentication({ school, administeredSchools: [this.school] }); this.server.create('school'); }); test('visiting /admin/assignstudents', async function(assert) { await visit('/admin/assignstudents'); assert.equal(await getElementText('.schoolsfilter'), getText('school 0')); assert.equal(currentURL(), '/admin/assignstudents'); percySnapshot(assert); }); });
Change script to accept non-number versions of sent and para attributes The script relied on numeric sent and para attributes. The code was changed to also accept non-numeric sent and para attributes. In some cases, the sent and para attributes returned by tools are not numeric.
"""Script to generate an HTML page from a KAF file that shows the text contents including line numbers. """ from bs4 import BeautifulSoup with open('data/minnenijd.kaf') as f: xml_doc = BeautifulSoup(f) output_html = ['<html><head>', '<meta http-equiv="Content-Type" content="text/html; ' 'charset=utf-8">', '</head>', '<body>', '<p>'] current_para = None new_para = False current_sent = None for token in xml_doc('wf'): if token['para'] != current_para: current_para = token['para'] output_html.append('</p><p>') new_para = True if token['sent'] != current_sent: current_sent = token['sent'] if not new_para: output_html.append('<br>') output_html.append(str(current_sent)) output_html.append(': ') new_para = False # exctract text from cdata (waarom is dat nou weer zo!) output_html.append(token.text) output_html.append('</p>') html = BeautifulSoup(' '.join(output_html)) print html.prettify().encode('utf-8')
"""Script to generate an HTML page from a KAF file that shows the text contents including line numbers. """ from bs4 import BeautifulSoup with open('data/minnenijd.kaf') as f: xml_doc = BeautifulSoup(f) output_html = ['<html><head>', '<meta http-equiv="Content-Type" content="text/html; ' \ 'charset=utf-8">', '</head>', '<body>', '<p>'] current_para = 1 new_para = False current_sent = 0 for token in xml_doc('wf'): if int(token['para']) > current_para: current_para = int(token['para']) output_html.append('</p><p>') new_para = True if int(token['sent']) > current_sent: current_sent = int(token['sent']) if not new_para: output_html.append('<br>') output_html.append(str(current_sent)) output_html.append(': ') new_para = False output_html.append(token.text) output_html.append('</p>') html = BeautifulSoup(' '.join(output_html)) print html.prettify().encode('utf-8')
Add Scenario repo search method
package com.aemreunal.repository.scenario; /* *************************** * Copyright (c) 2014 * * * * This code belongs to: * * * * @author Ahmet Emre Ünal * * S001974 * * * * [email protected] * * [email protected] * * * * aemreunal.com * *************************** */ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.repository.CrudRepository; import com.aemreunal.domain.Project; import com.aemreunal.domain.Scenario; public interface ScenarioRepo extends CrudRepository<Scenario, Long>, JpaSpecificationExecutor { public Scenario findByScenarioIdAndProject(Long scenarioId, Project project); }
package com.aemreunal.repository.scenario; /* *************************** * Copyright (c) 2014 * * * * This code belongs to: * * * * @author Ahmet Emre Ünal * * S001974 * * * * [email protected] * * [email protected] * * * * aemreunal.com * *************************** */ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.repository.CrudRepository; import com.aemreunal.domain.Scenario; public interface ScenarioRepo extends CrudRepository<Scenario, Long>, JpaSpecificationExecutor { }
Make byte-separator mandatory in MAC addresses This will prevent false positive (from hash values for example).
from __future__ import unicode_literals import re from core.observables import Observable class MacAddress(Observable): regex = r'(?P<search>(([0-9A-Fa-f]{1,2}[.:-]){5,7}([0-9A-Fa-f]{1,2})))' exclude_fields = Observable.exclude_fields DISPLAY_FIELDS = Observable.DISPLAY_FIELDS @classmethod def is_valid(cls, match): value = match.group('search') return len(value) > 0 def normalize(self): value = re.sub(r'[.:\-]', '', self.value).upper() self.value = ':'.join( value[i:i + 2] for i in xrange(0, len(value), 2) )
from __future__ import unicode_literals import re from core.observables import Observable class MacAddress(Observable): regex = r'(?P<search>(([0-9A-Fa-f]{1,2}[.:-]?){5,7}([0-9A-Fa-f]{1,2})))' exclude_fields = Observable.exclude_fields DISPLAY_FIELDS = Observable.DISPLAY_FIELDS @classmethod def is_valid(cls, match): value = match.group('search') return len(value) > 0 def normalize(self): self.value = re.sub(r'[.:\-]', '', self.value) self.value = self.value.upper() self.value = \ ':'.join([self.value[i:i + 2] for i in range(0, len(self.value), 2)])
Check against `this.cacheable` before running Looks like that might not be available when using the loader at backend. Closes #3.
'use strict'; var cheerio = require('cheerio'); var he = require('he'); var hl = require('highlight.js'); var highlightAuto = hl.highlightAuto; var highlight = hl.highlight; module.exports = function(input) { this.cacheable && this.cacheable(); var $ = cheerio.load(input); $('code').replaceWith(function(i, e) { var $e = $(e); var text = $e.text(); if(text.split('\n').length < 2) { return $('<code>' + he.encode(text) + '</code>'); } var text = $e.text(); var klass = $e.attr('class') || ''; var lang = klass.split('lang-').filter(id); lang = lang && lang[0]; if(lang) { return highlight(lang, text).value; } return highlightAuto(text).value; }); $('pre').addClass('hljs'); return $.html(); }; function id(a) {return a;}
'use strict'; var cheerio = require('cheerio'); var he = require('he'); var hl = require('highlight.js'); var highlightAuto = hl.highlightAuto; var highlight = hl.highlight; module.exports = function(input) { this.cacheable(); var $ = cheerio.load(input); $('code').replaceWith(function(i, e) { var $e = $(e); var text = $e.text(); if(text.split('\n').length < 2) { return $('<code>' + he.encode(text) + '</code>'); } var text = $e.text(); var klass = $e.attr('class') || ''; var lang = klass.split('lang-').filter(id); lang = lang && lang[0]; if(lang) { return highlight(lang, text).value; } return highlightAuto(text).value; }); $('pre').addClass('hljs'); return $.html(); }; function id(a) {return a;}
Fix finalOpacity unable to be 0
import Motion from '../motion'; import Tween from '../tween'; import { rAF } from '../concurrency-helpers'; export default class Opacity extends Motion { constructor(sprite, opts) { super(sprite, opts); this.prior = null; this.opacityTween = null; this.opacityFrom = 0; this.opacityTo = 1; if (opts && opts.duration != null) { this.duration = opts.duration; } if (opts && opts.initialOpacity != null) { this.opacityFrom = opts.initialOpacity; } if (opts && opts.finalOpacity != null) { this.opacityTo = opts.finalOpacity; } } interrupted(motions) { this.prior = motions.find(m => m instanceof this.constructor); } * animate() { let { sprite, duration } = this; this.opacityTween = new Tween(this.opacityFrom, this.opacityTo, duration); while (true) { yield rAF(); sprite.applyStyles({ opacity: this.opacityTween.currentValue }); if (this.opacityTween.done) { break; } } } }
import Motion from '../motion'; import Tween from '../tween'; import { rAF } from '../concurrency-helpers'; export default class Opacity extends Motion { constructor(sprite, opts) { super(sprite, opts); this.prior = null; this.opacityTween = null; this.opacityFrom = opts && opts.initialOpacity || 0; this.opacityTo = opts && opts.initialOpacity || 1; if (opts && opts.duration != null) { this.duration = opts.duration; } } interrupted(motions) { this.prior = motions.find(m => m instanceof this.constructor); } * animate() { let { sprite, duration } = this; this.opacityTween = new Tween(this.opacityFrom, this.opacityTo, duration); while (true) { yield rAF(); sprite.applyStyles({ opacity: this.opacityTween.currentValue }); if (this.opacityTween.done) { break; } } } }
Allow sead.Random to be constructed by internal state
class Random: def __init__(self, *param): if len(param) == 1: self.set_seed(param[0]) elif len(param) == 4: self.set_state(*param) else: raise TypeError("Random.__init__ takes either 1 or 4 arguments") def set_seed(self, seed): multiplier = 0x6C078965 temp = seed self.state = [] for i in range(1, 5): temp ^= temp >> 30 temp = (temp * multiplier + i) & 0xFFFFFFFF self.state.append(temp) def set_state(self, s0, s1, s2, s3): self.state = [s0, s1, s2, s3] def u32(self): temp = self.state[0] temp = (temp ^ (temp << 11)) & 0xFFFFFFFF temp ^= temp >> 8 temp ^= self.state[3] temp ^= self.state[3] >> 19 self.state[0] = self.state[1] self.state[1] = self.state[2] self.state[2] = self.state[3] self.state[3] = temp return temp def uint(self, max): return (self.u32() * max) >> 32
class Random: def __init__(self, seed): multiplier = 0x6C078965 temp = seed self.state = [] for i in range(1, 5): temp ^= temp >> 30 temp = (temp * multiplier + i) & 0xFFFFFFFF self.state.append(temp) def u32(self): temp = self.state[0] temp = (temp ^ (temp << 11)) & 0xFFFFFFFF temp ^= temp >> 8 temp ^= self.state[3] temp ^= self.state[3] >> 19 self.state[0] = self.state[1] self.state[1] = self.state[2] self.state[2] = self.state[3] self.state[3] = temp return temp def uint(self, max): return (self.u32() * max) >> 32
Add tenant id to Enrollment Certificate
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans; public class EnrollmentCertificate { String serial; String pem; int tenantId; public int getTenantId() { return tenantId; } public void setTenantId(int tenantId) { this.tenantId = tenantId; } public String getSerial() { return serial; } public void setSerial(String serial) { this.serial = serial; } public String getPem() { return pem; } public void setPem(String pem) { this.pem = pem; } }
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans; public class EnrollmentCertificate { String serial; String pem; public String getSerial() { return serial; } public void setSerial(String serial) { this.serial = serial; } public String getPem() { return pem; } public void setPem(String pem) { this.pem = pem; } }
Update test to use 768 key size and different message
package cryptopals import ( "crypto/rand" "crypto/rsa" "testing" ) func TestDecryptRsaPaddingOracleSimple(t *testing.T) { c := challenge47{} priv, _ := rsa.GenerateKey(rand.Reader, 768) pub := priv.PublicKey expected := "kick it, CC" ciphertext, err := rsa.EncryptPKCS1v15(rand.Reader, &pub, []byte(expected)) if err != nil { t.Fatal(err) } oracle := func(ciphertext []byte) bool { _, err := rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext) return err == nil } actual := string(c.DecryptRsaPaddingOracleSimple(&pub, ciphertext, oracle)) if actual != expected { t.Fatalf("Expected %v, was %v", expected, actual) } }
package cryptopals import ( "crypto/rand" "crypto/rsa" "testing" ) func TestDecryptRsaPaddingOracleSimple(t *testing.T) { c := challenge47{} priv, _ := rsa.GenerateKey(rand.Reader, 1024) pub := priv.PublicKey expected := "Chosen Ciphertext Attacks Against Protocols Based on the RSA Encryption Standard PKCS #1" ciphertext, err := rsa.EncryptPKCS1v15(rand.Reader, &pub, []byte(expected)) if err != nil { t.Fatal(err) } oracle := func(ciphertext []byte) bool { _, err := rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext) return err == nil } actual := string(c.DecryptRsaPaddingOracleSimple(&pub, ciphertext, oracle)) if actual != expected { t.Fatalf("Expected %v, was %v", expected, actual) } }
Update GitHub icon alt text
import React from 'react' import styled from 'styled-components' import { Intro, CheckboxTree } from './components' import data from './data/data.json' import github from './assets/github.svg' const Main = styled.main` display: flex; flex-direction: column; width: 80%; max-width: 64rem; height: 100vh; margin: 0 auto; ` const Section = styled.section` display: flex; flex-direction: column; flex: 1; overflow: auto; ` const Footer = styled.footer` align-self: center; margin: 2rem; ` export const App = () => ( <Main> <header> <Intro /> </header> <Section> <article> <CheckboxTree data={data} /> </article> </Section> <Footer> <a href='https://github.com/joelgeorgev/react-checkbox-tree'> <img src={github} alt='Go to GitHub repository page' /> </a> </Footer> </Main> )
import React from 'react' import styled from 'styled-components' import { Intro, CheckboxTree } from './components' import data from './data/data.json' import github from './assets/github.svg' const Main = styled.main` display: flex; flex-direction: column; width: 80%; max-width: 64rem; height: 100vh; margin: 0 auto; ` const Section = styled.section` display: flex; flex-direction: column; flex: 1; overflow: auto; ` const Footer = styled.footer` align-self: center; margin: 2rem; ` export const App = () => ( <Main> <header> <Intro /> </header> <Section> <article> <CheckboxTree data={data} /> </article> </Section> <Footer> <a href='https://github.com/joelgeorgev/react-checkbox-tree'> <img src={github} alt='GitHub repository' /> </a> </Footer> </Main> )
Change clear command success message
package guitests; import static org.junit.Assert.assertTrue; import org.junit.Test; public class ClearCommandTest extends TaskManagerGuiTest { @Test public void clear() { //verify a non-empty list can be cleared assertTrue(taskListPanel.isListMatching(td.getTypicalTasks())); assertClearCommandSuccess(); //verify other commands can work after a clear command commandBox.runCommand(td.hoon.getAddCommand()); assertTrue(taskListPanel.isListMatching(td.hoon)); commandBox.runCommand("delete 1"); assertListSize(0); //verify clear command works when the list is empty assertClearCommandSuccess(); } private void assertClearCommandSuccess() { commandBox.runCommand("clear"); assertListSize(0); assertResultMessage("Task Manager has been cleared!"); } }
package guitests; import static org.junit.Assert.assertTrue; import org.junit.Test; public class ClearCommandTest extends TaskManagerGuiTest { @Test public void clear() { //verify a non-empty list can be cleared assertTrue(taskListPanel.isListMatching(td.getTypicalTasks())); assertClearCommandSuccess(); //verify other commands can work after a clear command commandBox.runCommand(td.hoon.getAddCommand()); assertTrue(taskListPanel.isListMatching(td.hoon)); commandBox.runCommand("delete 1"); assertListSize(0); //verify clear command works when the list is empty assertClearCommandSuccess(); } private void assertClearCommandSuccess() { commandBox.runCommand("clear"); assertListSize(0); assertResultMessage("Task manager has been cleared!"); } }
Set focus to first input element.
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD // GO AFTER THE REQUIRES BELOW. // //= require jquery //= require jquery_ujs //= require jquery.purr //= require best_in_place //= require twitter/bootstrap //= require_tree . jQuery.ajaxSetup({ 'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")} }); jQuery.fn.submitWithAjax = function() { this.submit(function() { $.post(this.action, $(this).serialize(), null, "script"); return false; }) return this; }; $(document).ready(function() { $('.new_note').submitWithAjax(); $(':input:enabled:visible:first').focus(); }); $(document).on('ajax:success', '.delete_note', function(e) { $(e.currentTarget).closest('div.note').fadeOut(); });
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD // GO AFTER THE REQUIRES BELOW. // //= require jquery //= require jquery_ujs //= require jquery.purr //= require best_in_place //= require twitter/bootstrap //= require_tree . jQuery.ajaxSetup({ 'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")} }) jQuery.fn.submitWithAjax = function() { this.submit(function() { $.post(this.action, $(this).serialize(), null, "script"); return false; }) return this; }; $(document).ready(function() { $('.new_note').submitWithAjax(); }) $(document).on('ajax:success', '.delete_note', function(e) { $(e.currentTarget).closest('div.note').fadeOut(); });
Fix the missing this/other in BoxCollider
'use strict'; export default class BoxCollider { constructor(sprite, x, y, width, height) { this.sprite = sprite; this.x = x; this.y = y; this.width = width; this.height = height; } intersectWith(other) { let selfX1 = this.sprite.position[0] + this.x; let selfY1 = this.sprite.position[1] + this.y; let selfX2 = selfX1 + this.width; let selfY2 = selfY1 + this.height; let otherX1 = other.sprite.position[0] + other.x; let otherY1 = other.sprite.position[1] + other.y; let otherX2 = otherX1 + other.width; let otherY2 = otherY1 + other.height; return !( selfX2 < otherX1 || selfX1 > otherX2 || selfY2 < otherY1 || selfY1 > otherY2 ); } }
'use strict'; export default class BoxCollider { constructor(sprite, x, y, width, height) { this.sprite = sprite; this.x = x; this.y = y; this.width = width; this.height = height; } intersectWith(other) { let selfX1 = this.sprite.position[0] + x; let selfY1 = this.sprite.position[1] + y; let selfX2 = selfX1 + this.width; let selfY2 = selfY1 + this.height; let otherX1 = other.sprite.position[0] + x; let otherY1 = other.sprite.position[1] + y; let otherX2 = otherX1 + other.width; let otherY2 = otherY1 + other.height; return !( selfX2 < otherX1 || selfX1 > otherX2 || selfY2 < otherY1 || selfY1 > otherY2 ); } }
Enable running scripts from files E.g. "xp -e AgeInDays.script.php", which is the equivalent of "cat AgeInDays.script.php | xp -e" Scripts do not have an enclosing class, but rather just start with the code right away (after some optional "use" statements). Example: <?php use util\{Date, DateUtil}; use util\cmd\Console; $span= DateUtil::timespanBetween(new Date($argv[1]), Date::now()); Console::writeLine("Hey, you are ", $span->getDays(), " days old");
<?php namespace xp\runtime; use util\cmd\Console; use lang\XPClass; /** * Evaluates sourcecode * */ class Evaluate { /** * Main * * @param string[] args */ public static function main(array $args) { $argc= sizeof($args); // Read sourcecode from STDIN if no further argument is given if (0 === $argc) { $code= new Code(file_get_contents('php://stdin')); } else if ('--' === $args[0]) { $code= new Code(file_get_contents('php://stdin')); } else if (is_file($args[0])) { $code= new Code(file_get_contents($args[0])); } else { $code= new Code($args[0]); } // Perform $argv= [XPClass::nameOf(__CLASS__)] + $args; return eval($code->head().$code->fragment()); } }
<?php namespace xp\runtime; use util\cmd\Console; use lang\XPClass; /** * Evaluates sourcecode * */ class Evaluate { /** * Main * * @param string[] args */ public static function main(array $args) { $argc= sizeof($args); // Read sourcecode from STDIN if no further argument is given if (0 === $argc) { $code= new Code(file_get_contents('php://stdin')); } else if ('--' === $args[0]) { $code= new Code(file_get_contents('php://stdin')); } else { $code= new Code($args[0]); } // Perform $argv= [XPClass::nameOf(__CLASS__)] + $args; return eval($code->head().$code->fragment()); } }
Fix broken Filter import in FilterSummary
import React from 'react' import { translate } from 'react-i18next' import PropTypes from 'prop-types' import Filter from 'common/components/Filter' import styles from './FiltersSummary.scss' const FiltersSummary = ({ filters, removeFilter, t }) => ( <div> <div className={styles.label}> {filters.length ? t('FiltersSummary.activeFilters', { count: filters.length }) : t('FiltersSummary.noFilters')} </div> {filters.map((filter, idx) => ( <Filter key={idx} detail remove filter={filter} onClick={filter => removeFilter(filter)} /> ))} </div> ) FiltersSummary.propTypes = { filters: PropTypes.array.isRequired, removeFilter: PropTypes.func.isRequired, t: PropTypes.func.isRequired } export default translate('Search')(FiltersSummary)
import React from 'react' import { translate } from 'react-i18next' import PropTypes from 'prop-types' import Filter from 'components/Filter' import styles from './FiltersSummary.scss' const FiltersSummary = ({ filters, removeFilter, t }) => ( <div> <div className={styles.label}> {filters.length ? t('FiltersSummary.activeFilters', { count: filters.length }) : t('FiltersSummary.noFilters')} </div> {filters.map((filter, idx) => ( <Filter key={idx} detail remove filter={filter} onClick={filter => removeFilter(filter)} /> ))} </div> ) FiltersSummary.propTypes = { filters: PropTypes.array.isRequired, removeFilter: PropTypes.func.isRequired, t: PropTypes.func.isRequired } export default translate('Search')(FiltersSummary)
Add ReturnTypeWillChange to count method
<?php namespace Illuminate\Database\Eloquent\Factories; use Countable; class Sequence implements Countable { /** * The sequence of return values. * * @var array */ protected $sequence; /** * The count of the sequence items. * * @var int */ public $count; /** * The current index of the sequence iteration. * * @var int */ public $index = 0; /** * Create a new sequence instance. * * @param array $sequence * @return void */ public function __construct(...$sequence) { $this->sequence = $sequence; $this->count = count($sequence); } /** * Get the current count of the sequence items. * * @return int */ #[\ReturnTypeWillChange] public function count() { return $this->count; } /** * Get the next value in the sequence. * * @return mixed */ public function __invoke() { return tap(value($this->sequence[$this->index % $this->count], $this), function () { $this->index = $this->index + 1; }); } }
<?php namespace Illuminate\Database\Eloquent\Factories; use Countable; class Sequence implements Countable { /** * The sequence of return values. * * @var array */ protected $sequence; /** * The count of the sequence items. * * @var int */ public $count; /** * The current index of the sequence iteration. * * @var int */ public $index = 0; /** * Create a new sequence instance. * * @param array $sequence * @return void */ public function __construct(...$sequence) { $this->sequence = $sequence; $this->count = count($sequence); } /** * Get the current count of the sequence items. * * @return int */ public function count() { return $this->count; } /** * Get the next value in the sequence. * * @return mixed */ public function __invoke() { return tap(value($this->sequence[$this->index % $this->count], $this), function () { $this->index = $this->index + 1; }); } }
Remove the Intended Audience classifier
#!/usr/bin/env python3 # coding: utf-8 """A setuptools based setup module. See: https://packaging.python.org/en/latest/distributing.html https://github.com/pypa/sampleproject """ from setuptools import setup, find_packages import keysmith with open('README.rst') as readme_file: README = readme_file.read() setup( name='keysmith', version=keysmith.__version__, description=keysmith.__doc__, long_description=README, author='David Tucker', author_email='[email protected]', license='LGPLv2+', url='https://github.com/dmtucker/keysmith', packages=find_packages(exclude=['contrib', 'docs', 'tests']), include_package_data=True, entry_points={'console_scripts': ['keysmith = keysmith.__main__:main']}, keywords='password generator keygen', classifiers=[ 'License :: OSI Approved :: ' 'GNU Lesser General Public License v2 or later (LGPLv2+)', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Development Status :: 5 - Production/Stable', ], )
#!/usr/bin/env python3 # coding: utf-8 """A setuptools based setup module. See: https://packaging.python.org/en/latest/distributing.html https://github.com/pypa/sampleproject """ from setuptools import setup, find_packages import keysmith with open('README.rst') as readme_file: README = readme_file.read() setup( name='keysmith', version=keysmith.__version__, description=keysmith.__doc__, long_description=README, author='David Tucker', author_email='[email protected]', license='LGPLv2+', url='https://github.com/dmtucker/keysmith', packages=find_packages(exclude=['contrib', 'docs', 'tests']), include_package_data=True, entry_points={'console_scripts': ['keysmith = keysmith.__main__:main']}, keywords='password generator keygen', classifiers=[ 'License :: OSI Approved :: ' 'GNU Lesser General Public License v2 or later (LGPLv2+)', 'Intended Audience :: End Users/Desktop', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Development Status :: 5 - Production/Stable', ], )
Use Solr for testing with Travis CI
from defaults import * DATABASES = { 'default': { #'ENGINE': 'django.db.backends.postgresql_psycopg2', 'ENGINE': 'django.contrib.gis.db.backends.postgis', # 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'atlas_test', 'USER': 'postgres', 'PASSWORD': '', 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'storybase_geo.search.backends.Solr2155Engine', 'URL': 'http://localhost:8080/solr3', }, }
from defaults import * DATABASES = { 'default': { #'ENGINE': 'django.db.backends.postgresql_psycopg2', 'ENGINE': 'django.contrib.gis.db.backends.postgis', # 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'atlas_test', 'USER': 'postgres', 'PASSWORD': '', 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine' } }
:art: Change Form to FlaskForm (previous is deprecated)
from flask_wtf import FlaskForm from wtforms import ( StringField, PasswordField, BooleanField, SubmitField, ValidationError, ) from wtforms.validators import ( InputRequired, Length, Email, Regexp, EqualTo, ) from app.models import User class LoginForm(FlaskForm): email = StringField('Email', validators=[ InputRequired(), Length(1, 64), Email()]) password = PasswordField('Senha', validators=[InputRequired()]) remember_me = BooleanField('Lembrar') submit = SubmitField('Log In') class RegistrationForm(FlaskForm): email = StringField('Email', validators=[ InputRequired(), Length(1, 64), Email()]) username = StringField('Username', validators=[ InputRequired(), Length(1, 64)]) password = PasswordField('Senha', validators=[ InputRequired(), EqualTo('password2', message='Senhas devem ser iguais')]) password2 = PasswordField('Confirmar senha', validators=[InputRequired()]) submit = SubmitField('Registrar') def validate_email(self, field): if User.query.filter_by(email=field.data).first(): raise ValidationError('Esse email já está em uso!') def validate_username(self, field): if User.query.filter_by(username=field.data).first(): raise ValidationError('Esse usuário já está em uso!')
from flask_wtf import Form from wtforms import ( StringField, PasswordField, BooleanField, SubmitField, ValidationError, ) from wtforms.validators import ( InputRequired, Length, Email, Regexp, EqualTo, ) from app.models import User class LoginForm(Form): email = StringField('Email', validators=[ InputRequired(), Length(1, 64), Email()]) password = PasswordField('Senha', validators=[InputRequired()]) remember_me = BooleanField('Lembrar') submit = SubmitField('Log In') class RegistrationForm(Form): email = StringField('Email', validators=[ InputRequired(), Length(1, 64), Email()]) username = StringField('Username', validators=[ InputRequired(), Length(1, 64)]) password = PasswordField('Senha', validators=[ InputRequired(), EqualTo('password2', message='Senhas devem ser iguais')]) password2 = PasswordField('Confirmar senha', validators=[InputRequired()]) submit = SubmitField('Registrar') def validate_email(self, field): if User.query.filter_by(email=field.data).first(): raise ValidationError('Esse email já está em uso!') def validate_username(self, field): if User.query.filter_by(username=field.data).first(): raise ValidationError('Esse usuário já está em uso!')
Fix Finnish week start to Monday, add format Finns *always* start their week on Mondays. The d.m.yyyy date format is the most common one.
/** * Finnish translation for bootstrap-datepicker * Jaakko Salonen <https://github.com/jsalonen> */ ;(function($){ $.fn.datepicker.dates['fi'] = { days: ["sunnuntai", "maanantai", "tiistai", "keskiviikko", "torstai", "perjantai", "lauantai", "sunnuntai"], daysShort: ["sun", "maa", "tii", "kes", "tor", "per", "lau", "sun"], daysMin: ["su", "ma", "ti", "ke", "to", "pe", "la", "su"], months: ["tammikuu", "helmikuu", "maaliskuu", "huhtikuu", "toukokuu", "kesäkuu", "heinäkuu", "elokuu", "syyskuu", "lokakuu", "marraskuu", "joulukuu"], monthsShort: ["tam", "hel", "maa", "huh", "tou", "kes", "hei", "elo", "syy", "lok", "mar", "jou"], today: "tänään", weekStart: 1, format: "d.m.yyyy" }; }(jQuery));
/** * Finnish translation for bootstrap-datepicker * Jaakko Salonen <https://github.com/jsalonen> */ ;(function($){ $.fn.datepicker.dates['fi'] = { days: ["sunnuntai", "maanantai", "tiistai", "keskiviikko", "torstai", "perjantai", "lauantai", "sunnuntai"], daysShort: ["sun", "maa", "tii", "kes", "tor", "per", "lau", "sun"], daysMin: ["su", "ma", "ti", "ke", "to", "pe", "la", "su"], months: ["tammikuu", "helmikuu", "maaliskuu", "huhtikuu", "toukokuu", "kesäkuu", "heinäkuu", "elokuu", "syyskuu", "lokakuu", "marraskuu", "joulukuu"], monthsShort: ["tam", "hel", "maa", "huh", "tou", "kes", "hei", "elo", "syy", "lok", "mar", "jou"], today: "tänään" }; }(jQuery));
fix: Set default header for transaction handler
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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 io.gravitee.gateway.reactor.handler.transaction; import io.gravitee.gateway.api.Request; import io.gravitee.gateway.api.handler.Handler; import org.springframework.beans.factory.annotation.Value; /** * @author David BRASSELY (david.brassely at graviteesource.com) * @author GraviteeSource Team */ public class TransactionHandlerFactory { @Value("${handlers.request.transaction.header:" + TransactionHandler.DEFAULT_TRANSACTIONAL_ID_HEADER + "}") private String transactionHeader = TransactionHandler.DEFAULT_TRANSACTIONAL_ID_HEADER; public Handler<Request> create(Handler<Request> next) { return new TransactionHandler(transactionHeader, next); } }
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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 io.gravitee.gateway.reactor.handler.transaction; import io.gravitee.gateway.api.Request; import io.gravitee.gateway.api.handler.Handler; import org.springframework.beans.factory.annotation.Value; /** * @author David BRASSELY (david.brassely at graviteesource.com) * @author GraviteeSource Team */ public class TransactionHandlerFactory { @Value("${handlers.request.transaction.header:" + TransactionHandler.DEFAULT_TRANSACTIONAL_ID_HEADER + "}") private String transactionHeader; public Handler<Request> create(Handler<Request> next) { return new TransactionHandler(transactionHeader, next); } }
Handle app boot without cache
function runBlock( // eslint-disable-line max-params $rootScope, jwtHelper, $state, $location, APP_CONFIG, authService, localStorage ) { 'ngInject'; $rootScope.$on('$stateChangeStart', function (e, toState) { if (APP_CONFIG.error && toState.name !== 'error') { e.preventDefault(); $state.go('error'); } else if (toState.name !== 'login' && !authService.verifyAuthCache()) { e.preventDefault(); $state.go('login'); } }); $rootScope.$on('$locationChangeStart', function () { let token = localStorage.get('id_token'); if (token) { if (!authService.verifyAuthCache()) { authService.login(token); } } else { $state.go('login'); } }); } export default runBlock;
function runBlock( // eslint-disable-line max-params $rootScope, jwtHelper, $state, $location, APP_CONFIG, authService, localStorage ) { 'ngInject'; $rootScope.$on('$stateChangeStart', function (e, toState) { if (APP_CONFIG.error && toState.name !== 'error') { e.preventDefault(); $state.go('error'); } else if (toState.name !== 'login' && !authService.isLoggedIn) { e.preventDefault(); $state.go('login'); } }); $rootScope.$on('$locationChangeStart', function () { let token = localStorage.get('id_token'); if (token) { if (!authService.isLoggedIn) { authService.login(token); } } }); } export default runBlock;
TEST Add 'ps' variable to idealized run
from aospy.run import Run test_am2 = Run( name='test_am2', description=( 'Preindustrial control simulation.' ), data_in_direc=('/archive/Yi.Ming/sm2.1_fixed/' 'SM2.1U_Control-1860_lm2_aie_rerun6.YIM/pp'), data_in_dur=5, data_in_start_date='0001-01-01', data_in_end_date='0080-12-31', default_date_range=('0021-01-01', '0080-12-31') ) test_idealized_moist = Run( name='test_idealized_moist', description=( 'Control case at T42 spectral resolution' ), data_in_direc='/archive/skc/idealized_moist_alb_T42/control_gaussian_T42/' 'gfdl.ncrc2-default-prod/1x0m720d_32pe/history', data_in_dir_struc='one_dir', data_in_files={'20-day': {v: '00000.1x20days.nc' for v in ['olr', 'temp', 'ps']}}, )
from aospy.run import Run test_am2 = Run( name='test_am2', description=( 'Preindustrial control simulation.' ), data_in_direc=('/archive/Yi.Ming/sm2.1_fixed/' 'SM2.1U_Control-1860_lm2_aie_rerun6.YIM/pp'), data_in_dur=5, data_in_start_date='0001-01-01', data_in_end_date='0080-12-31', default_date_range=('0021-01-01', '0080-12-31') ) test_idealized_moist = Run( name='test_idealized_moist', description=( 'Control case at T42 spectral resolution' ), data_in_direc='/archive/skc/idealized_moist_alb_T42/control_gaussian_T42/' 'gfdl.ncrc2-default-prod/1x0m720d_32pe/history', data_in_dir_struc='one_dir', data_in_files={'20-day': {v: '00000.1x20days.nc' for v in ['olr', 'temp']}}, )
Allow update of notification text. Allows you to update the message in the notification. I wanted this feature to allow me to show loading percentage in the notification when downloading or uploading data.
var args = _.extend({ duration: 2000, animationDuration: 250, message: '', title: Ti.App.name, elasticity: 0.5, pushForce: 30, usePhysicsEngine: true }, arguments[0] || {}); var That = null; exports.show = function(opt) { if (_.isObject(opt)) _.extend(args, opt); if (_.isString(opt)) _.extend(args, { message: opt }); if (OS_ANDROID && args.view == null) { Ti.API.error("In Android you have to set a view that contain the sliding view. Fallbacking to Ti.UI.Notification."); That = Ti.UI.createNotification({ message: args.message, duration: args.duration }); That.show(); } else { That = Widget.createController('window', args); } }; exports.update = function(message) { That.update(message); }; exports.hide = function() { if (That != null) { That.hide(); } };
var args = _.extend({ duration: 2000, animationDuration: 250, message: '', title: Ti.App.name, elasticity: 0.5, pushForce: 30, usePhysicsEngine: true }, arguments[0] || {}); var That = null; exports.show = function(opt) { if (_.isObject(opt)) _.extend(args, opt); if (_.isString(opt)) _.extend(args, { message: opt }); if (OS_ANDROID && args.view == null) { Ti.API.error("In Android you have to set a view that contain the sliding view. Fallbacking to Ti.UI.Notification."); That = Ti.UI.createNotification({ message: args.message, duration: args.duration }); That.show(); } else { That = Widget.createController('window', args); } }; exports.hide = function() { if (That != null) { That.hide(); } };
Add default value for simulation time
#!/usr/bin/env python TRAJECTORY = 'linear' CONTROLLER = 'euler' # control constants K_X = 0.90 K_Y = 0.90 K_THETA = 0.90 # PID control constants K_P_V = 0.2 K_I_V = 1.905 K_D_V = 0.00 K_P_W = 0.45 K_I_W = 1.25 K_D_W = 0.000 SIMULATION_TIME_IN_SECONDS = 0.0 if TRAJECTORY == 'linear': SIMULATION_TIME_IN_SECONDS = 60.0 MAX_V = 0.075 MAX_W = 1.25 elif TRAJECTORY == 'circular': SIMULATION_TIME_IN_SECONDS = 120.0 MAX_V = 0.11 MAX_W = 1.25 elif TRAJECTORY == 'squared': SIMULATION_TIME_IN_SECONDS = 160.0 MAX_V = 0.055 MAX_W = 1.20 DELTA_T = 0.1 # this is the sampling time STEPS = int(SIMULATION_TIME_IN_SECONDS / DELTA_T) RESULTS_DIRECTORY = '../txt_results/'
#!/usr/bin/env python TRAJECTORY = 'linear' CONTROLLER = 'euler' # control constants K_X = 0.90 K_Y = 0.90 K_THETA = 0.90 # PID control constants K_P_V = 0.2 K_I_V = 1.905 K_D_V = 0.00 K_P_W = 0.45 K_I_W = 1.25 K_D_W = 0.000 if TRAJECTORY == 'linear': SIMULATION_TIME_IN_SECONDS = 60.0 MAX_V = 0.075 MAX_W = 1.25 elif TRAJECTORY == 'circular': SIMULATION_TIME_IN_SECONDS = 120.0 MAX_V = 0.11 MAX_W = 1.25 elif TRAJECTORY == 'squared': SIMULATION_TIME_IN_SECONDS = 160.0 MAX_V = 0.055 MAX_W = 1.20 DELTA_T = 0.1 # this is the sampling time STEPS = int(SIMULATION_TIME_IN_SECONDS / DELTA_T) RESULTS_DIRECTORY = '../txt_results/'
Fix assignment to nil map
package main import ( "github.com/gbl08ma/disturbancesmlx/dataobjects" "github.com/gbl08ma/disturbancesmlx/scraper" ) var annStore AnnouncementStore // AnnouncementStore implements dataobjects.AnnouncementStore type AnnouncementStore struct { scrapers map[string]scraper.AnnouncementScraper } // AddScraper registers all sources provided by this scraper func (as *AnnouncementStore) AddScraper(s scraper.AnnouncementScraper) { if as.scrapers == nil { as.scrapers = make(map[string]scraper.AnnouncementScraper) } for _, source := range s.Sources() { as.scrapers[source] = s } } // AllAnnouncements gets all announcements from all sources, unsorted func (as *AnnouncementStore) AllAnnouncements() []*dataobjects.Announcement { ann := []*dataobjects.Announcement{} for source, scraper := range as.scrapers { ann = append(ann, scraper.Announcements(source)...) } return ann } // SourceAnnouncements gets all announcements from a specific source func (as *AnnouncementStore) SourceAnnouncements(source string) []*dataobjects.Announcement { ann, ok := as.scrapers[source] if !ok { return []*dataobjects.Announcement{} } return ann.Announcements(source) }
package main import ( "github.com/gbl08ma/disturbancesmlx/dataobjects" "github.com/gbl08ma/disturbancesmlx/scraper" ) var annStore AnnouncementStore // AnnouncementStore implements dataobjects.AnnouncementStore type AnnouncementStore struct { scrapers map[string]scraper.AnnouncementScraper } // AddScraper registers all sources provided by this scraper func (as *AnnouncementStore) AddScraper(scraper scraper.AnnouncementScraper) { for _, source := range scraper.Sources() { as.scrapers[source] = scraper } } // AllAnnouncements gets all announcements from all sources, unsorted func (as *AnnouncementStore) AllAnnouncements() []*dataobjects.Announcement { ann := []*dataobjects.Announcement{} for source, scraper := range as.scrapers { ann = append(ann, scraper.Announcements(source)...) } return ann } // SourceAnnouncements gets all announcements from a specific source func (as *AnnouncementStore) SourceAnnouncements(source string) []*dataobjects.Announcement { ann, ok := as.scrapers[source] if !ok { return []*dataobjects.Announcement{} } return ann.Announcements(source) }
Remove .gitignore on bootstrap the project
const fs = require('fs-extra'); const path = require('path'); const chalk = require('chalk'); function copyTemplate(appDir, templatePath) { fs.copySync(templatePath, appDir); fs.removeSync('.gitignore'); fs.moveSync( path.join(appDir, 'gitignore'), path.join(appDir, '.gitignore'), ); } function addPackageScripts(appDir) { const scripts = { start: 'landing-scripts start', build: 'landing-scripts build', }; const packageJson = require(`${appDir}/package.json`); packageJson.scripts = scripts; fs.writeFileSync( path.join(appDir, 'package.json'), JSON.stringify(packageJson, null, 2), ); } function init(appDir, appName, templatePath) { const isUsingYarn = fs.existsSync(path.join(appDir, 'yarn.lock')); const command = isUsingYarn ? 'yarn' : 'npm'; copyTemplate(appDir, templatePath); addPackageScripts(appDir); console.log(chalk.green('Project ready!')); console.log(); console.log('To start the project typing:'); console.log(); console.log(chalk.cyan('cd'), appName); console.log(chalk.cyan(command), 'start'); } module.exports = init;
const fs = require('fs-extra'); const path = require('path'); const chalk = require('chalk'); function copyTemplate(appDir, templatePath) { fs.copySync(templatePath, appDir); fs.moveSync( path.join(appDir, 'gitignore'), path.join(appDir, '.gitignore'), ); } function addPackageScripts(appDir) { const scripts = { start: 'landing-scripts start', build: 'landing-scripts build', }; const packageJson = require(`${appDir}/package.json`); packageJson.scripts = scripts; fs.writeFileSync( path.join(appDir, 'package.json'), JSON.stringify(packageJson, null, 2), ); } function init(appDir, appName, templatePath) { const isUsingYarn = fs.existsSync(path.join(appDir, 'yarn.lock')); const command = isUsingYarn ? 'yarn' : 'npm'; copyTemplate(appDir, templatePath); addPackageScripts(appDir); console.log(chalk.green('Project ready!')); console.log(); console.log('To start the project typing:'); console.log(); console.log(chalk.cyan('cd'), appName); console.log(chalk.cyan(command), 'start'); } module.exports = init;
Update desc for latest too
{ "stable": { "CSIDE_version": "1.1.3", "nw_version": "0.21.4", "desc": "v1.1.3 - Provides a criticial bug fix related to persistent sessions", "target": "https://choicescriptide.github.io/downloads/updates/targets/113.zip" }, "latest": { "CSIDE_version": "1.2.1", "nw_version": "0.21.4", "desc": "v1.2.1 - (1.2.0) Feature release: Custom themes, code folding and more.", "target": "https://choicescriptide.github.io/downloads/updates/targets/121.zip" }, "development": { "CSIDE_version": "1.2.1", "nw_version": "0.21.4", "desc": "v1.2.1 - (1.2.0) Feature release: Custom themes, code folding and more.", "target": "https://choicescriptide.github.io/downloads/updates/targets/121.zip" }, "accessible": { "CSIDE_version": "1.1.2", "nw_version": "0.21.4", "desc": "", "target": "" } }
{ "stable": { "CSIDE_version": "1.1.3", "nw_version": "0.21.4", "desc": "v1.1.3 - Provides a criticial bug fix related to persistent sessions", "target": "https://choicescriptide.github.io/downloads/updates/targets/113.zip" }, "latest": { "CSIDE_version": "1.2.1", "nw_version": "0.21.4", "desc": "v1.2.1 - Provides a criticial bug fix related to persistent sessions", "target": "https://choicescriptide.github.io/downloads/updates/targets/121.zip" }, "development": { "CSIDE_version": "1.2.1", "nw_version": "0.21.4", "desc": "v1.2.1 - (1.2.0) Feature release: Custom themes, code folding and more.", "target": "https://choicescriptide.github.io/downloads/updates/targets/121.zip" }, "accessible": { "CSIDE_version": "1.1.2", "nw_version": "0.21.4", "desc": "", "target": "" } }
Remove actual model downloading from tests
# coding: utf-8 from __future__ import unicode_literals from ..cli.download import download, get_compatibility, get_version, check_error_depr import pytest def test_download_fetch_compatibility(): compatibility = get_compatibility() assert type(compatibility) == dict @pytest.mark.parametrize('model', ['en_core_web_md']) def test_download_get_matching_version_succeeds(model): comp = { model: ['1.7.0', '0.100.0'] } assert get_version(model, comp) @pytest.mark.parametrize('model', ['en_core_web_md']) def test_download_get_matching_version_fails(model): diff_model = 'test_' + model comp = { diff_model: ['1.7.0', '0.100.0'] } with pytest.raises(SystemExit): assert get_version(model, comp) @pytest.mark.parametrize('model', [False, None, '', 'all']) def test_download_no_model_depr_error(model): with pytest.raises(SystemExit): check_error_depr(model)
# coding: utf-8 from __future__ import unicode_literals from ..cli.download import download, get_compatibility, get_version, check_error_depr import pytest def test_download_fetch_compatibility(): compatibility = get_compatibility() assert type(compatibility) == dict @pytest.mark.slow @pytest.mark.parametrize('model', ['en_core_web_md-1.2.0']) def test_download_direct_download(model): download(model, direct=True) @pytest.mark.parametrize('model', ['en_core_web_md']) def test_download_get_matching_version_succeeds(model): comp = { model: ['1.7.0', '0.100.0'] } assert get_version(model, comp) @pytest.mark.parametrize('model', ['en_core_web_md']) def test_download_get_matching_version_fails(model): diff_model = 'test_' + model comp = { diff_model: ['1.7.0', '0.100.0'] } with pytest.raises(SystemExit): assert get_version(model, comp) @pytest.mark.parametrize('model', [False, None, '', 'all']) def test_download_no_model_depr_error(model): with pytest.raises(SystemExit): check_error_depr(model)
Put IIFE brackets inside, improve comment
(function (Andamio) { var methodSplitter = /\s+/; function _bind(target, obj, name, callback, methodName) { if (!callback) { throw new Error('Method "' + methodName + '" was configured as an event handler, but does not exist.'); } target.listenTo(obj, name, callback); } function _unbind(target, obj, name, callback) { target.stopListening(obj, name, callback); } function handler(target, obj, name, methodNames, method) { _.each(methodNames, function (methodName) { var callback = target[methodName]; method(target, obj, name, callback, methodName); }); } // Iterate the bindings and apply corresponding bidning method function iterateEvents(target, obj, bindings, method) { if (!obj || !bindings) { return; } // Iterate the bindings and bind/unbind them _.each(bindings, function (methods, name) { var methodNames = methods.split(methodSplitter); handler(target, obj, name, methodNames, method); }); } Andamio.bindEvents = function (target, obj, bindings) { iterateEvents(target, obj, bindings, _bind); }; Andamio.unbindEvents = function (target, obj, bindings) { iterateEvents(target, obj, bindings, _unbind); }; }(Andamio));
(function (Andamio) { var methodSplitter = /\s+/; function _bind(target, obj, name, callback, methodName) { if (!callback) { throw new Error('Method "' + methodName + '" was configured as an event handler, but does not exist.'); } target.listenTo(obj, name, callback); } function _unbind(target, obj, name, callback) { target.stopListening(obj, name, callback); } function handler(target, obj, name, methodNames, method) { _.each(methodNames, function (methodName) { var callback = target[methodName]; method(target, obj, name, callback, methodName); }); } // Iterate the bindings and apply corresponding bidning method function iterateEvents(target, obj, bindings, method) { if (!obj || !bindings) { return; } // Iterate the bindings and un/bind them _.each(bindings, function (methods, name) { var methodNames = methods.split(methodSplitter); handler(target, obj, name, methodNames, method); }); } Andamio.bindEvents = function (target, obj, bindings) { iterateEvents(target, obj, bindings, _bind); }; Andamio.unbindEvents = function (target, obj, bindings) { iterateEvents(target, obj, bindings, _unbind); }; })(Andamio);
Use image onload and onerror
/* eslint-env node */ const Canvas = require('canvas'); const fs = require('fs'); const { Image } = Canvas; /** * Create a new canvas object with height and width * set to the given values. * * @param width {number} The width of the canvas. * @param height {number} The height of the canvas. * * @return {Canvas} A canvas object with * height and width set to the given values. */ function createCanvas(width, height) { return new Canvas(width, height); } /** * Load the image given by the file path, returning * a promise to the image represented by the given path. * * @parm path {string} The path to the image. * * @return {Image} An image element referring to * the given path. */ function loadImage(path) { return new Promise((resolve, reject) => { fs.readFile(path, (err, data) => { if (err) { reject(err); return; } const image = new Image(); image.onload = () => resolve(image); image.onerror = err => reject(err); image.src = data; return resolve(image); }); }); } module.exports = { createCanvas, loadImage, };
/* eslint-env node */ const Canvas = require('canvas'); const fs = require('fs'); const { Image } = Canvas; /** * Create a new canvas object with height and width * set to the given values. * * @param width {number} The width of the canvas. * @param height {number} The height of the canvas. * * @return {Canvas} A canvas object with * height and width set to the given values. */ function createCanvas(width, height) { return new Canvas(width, height); } /** * Load the image given by the file path, returning * a promise to the image represented by the given path. * * @parm path {string} The path to the image. * * @return {Image} An image element referring to * the given path. */ function loadImage(path) { return new Promise((resolve, reject) => { fs.readFile(path, (err, data) => { if (err) { return reject(err); } const image = new Image(); image.src = data; return resolve(image); }); }); } module.exports = { createCanvas, loadImage, };
Remove superfluous import of shinken.objects in shinken/_init__.py. Every script or test-case importing shinken has all the objects loaded, even if they are not required by the script or test-case at all. Also see <http://sourceforge.net/mailarchive/message.php?msg_id=29553474>.
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2009-2012: # Gabes Jean, [email protected] # Gerhard Lausser, [email protected] # Gregory Starck, [email protected] # Hartmut Goebel, [email protected] # # This file is part of Shinken. # # Shinken 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. # # Shinken 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 Shinken. If not, see <http://www.gnu.org/licenses/>.
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2009-2012: # Gabes Jean, [email protected] # Gerhard Lausser, [email protected] # Gregory Starck, [email protected] # Hartmut Goebel, [email protected] # # This file is part of Shinken. # # Shinken 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. # # Shinken 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 Shinken. If not, see <http://www.gnu.org/licenses/>. # shinken.objects must be imported first: import objects
Remove delete portion endpoint from api
'use strict'; const passport = require('passport'); const main = require('../app/controllers/main'); const api = require('../app/controllers/api'); const auth = require('../app/controllers/auth'); /** * Expose routes */ module.exports = function applyRoutes(app) { app.get('/', main.index); app.post('/auth/token', auth.token); app.post('/auth/google-oauth2', auth.google.callback); app.get('/:type(orders|accounts|portions|vendors)', passport.authenticate('jwt'), api); app.get('/:type(orders|accounts|portions|vendors)/:id', passport.authenticate('jwt'), api); app.patch('/:type(orders|portions)/:id', passport.authenticate('jwt'), api); app.post('/:type(orders|portions|vendors)', passport.authenticate('jwt'), api); app.post('/:type(accounts)', api); app.patch('/:type(accounts)/:id', passport.authenticate('jwt'), api); };
'use strict'; const passport = require('passport'); const main = require('../app/controllers/main'); const api = require('../app/controllers/api'); const auth = require('../app/controllers/auth'); /** * Expose routes */ module.exports = function applyRoutes(app) { app.get('/', main.index); app.post('/auth/token', auth.token); app.post('/auth/google-oauth2', auth.google.callback); app.get('/:type(orders|accounts|portions|vendors)', passport.authenticate('jwt'), api); app.get('/:type(orders|accounts|portions|vendors)/:id', passport.authenticate('jwt'), api); app.patch('/:type(orders|portions)/:id', passport.authenticate('jwt'), api); app.delete('/:type(portions)/:id', passport.authenticate('jwt'), api); app.post('/:type(orders|portions|vendors)', passport.authenticate('jwt'), api); app.post('/:type(accounts)', api); app.patch('/:type(accounts)/:id', passport.authenticate('jwt'), api); };
Handle matches with no name
from common.log import logUtils as log from constants import clientPackets, serverPackets from constants import exceptions from objects import glob def handle(userToken, packetData): try: # get usertoken data userID = userToken.userID # Read packet data packetData = clientPackets.createMatch(packetData) # Make sure the name is valid matchName = packetData["matchName"].strip() if not matchName: raise exceptions.matchCreateError() # Create a match object # TODO: Player number check matchID = glob.matches.createMatch(matchName, packetData["matchPassword"].strip(), packetData["beatmapID"], packetData["beatmapName"], packetData["beatmapMD5"], packetData["gameMode"], userID) # Make sure the match has been created if matchID not in glob.matches.matches: raise exceptions.matchCreateError() with glob.matches.matches[matchID] as match: # Join that match userToken.joinMatch(matchID) # Give host to match creator match.setHost(userID) match.sendUpdates() match.changePassword(packetData["matchPassword"]) except exceptions.matchCreateError: log.error("Error while creating match!") userToken.enqueue(serverPackets.matchJoinFail())
from common.log import logUtils as log from constants import clientPackets from constants import exceptions from objects import glob def handle(userToken, packetData): try: # get usertoken data userID = userToken.userID # Read packet data packetData = clientPackets.createMatch(packetData) # Create a match object # TODO: Player number check matchID = glob.matches.createMatch(packetData["matchName"], packetData["matchPassword"], packetData["beatmapID"], packetData["beatmapName"], packetData["beatmapMD5"], packetData["gameMode"], userID) # Make sure the match has been created if matchID not in glob.matches.matches: raise exceptions.matchCreateError() with glob.matches.matches[matchID] as match: # Join that match userToken.joinMatch(matchID) # Give host to match creator match.setHost(userID) match.sendUpdates() match.changePassword(packetData["matchPassword"]) except exceptions.matchCreateError: log.error("Error while creating match!")
Set download_url to pypi directory.
#!/usr/bin/env python from ez_setup import use_setuptools use_setuptools() import os from setuptools import setup, find_packages here = os.path.dirname(__file__) version_file = os.path.join(here, 'src/iptools/__init__.py') d = {} execfile(version_file, d) version = d['__version__'] setup( name = 'iptools', version = version, description = 'Python utilites for manipulating IP addresses', long_description = "Utilities for manipulating IP addresses including a class that can be used to include CIDR network blocks in Django's INTERNAL_IPS setting.", url = 'http://python-iptools.googlecode.com', download_url = 'http://pypi.python.org/packages/source/i/iptools/', author = 'Bryan Davis', author_email = '[email protected]', license = 'BSD', platforms = ['any',], package_dir = {'': 'src'}, packages = find_packages('src'), include_package_data = True, test_suite='iptools.test_iptools', classifiers = [ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Utilities', 'Topic :: Internet', ], zip_safe=False, )
#!/usr/bin/env python from ez_setup import use_setuptools use_setuptools() import os from setuptools import setup, find_packages here = os.path.dirname(__file__) version_file = os.path.join(here, 'src/iptools/__init__.py') d = {} execfile(version_file, d) version = d['__version__'] setup( name = 'iptools', version = version, description = 'Python utilites for manipulating IP addresses', long_description = "Utilities for manipulating IP addresses including a class that can be used to include CIDR network blocks in Django's INTERNAL_IPS setting.", url = 'http://python-iptools.googlecode.com', author = 'Bryan Davis', author_email = '[email protected]', license = 'BSD', platforms = ['any',], package_dir = {'': 'src'}, packages = find_packages('src'), include_package_data = True, test_suite='iptools.test_iptools', classifiers = [ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Utilities', 'Topic :: Internet', ], zip_safe=False, )
Update module name in example code
'use strict'; var OnlineSGDRegression = require( './../lib' ); var x1; var x2; var y; var i; // Create model: var model = new OnlineSGDRegression({ 'lambda': 1e-4, 'loss': 'leastSquares', 'intercept': true }); // Data comes in... for ( i = 0; i < 100000; i++ ) { x1 = Math.random(); x2 = Math.random(); y = 3.0 * x1 + -3.0 * x2 + 2.0; model.update( y, [ x1, x2 ] ); } // Extract model coefficients: console.log( model.coefs ); // Predict new observations: console.log( 'y_hat = %d; x1 = %d; x2 = %d', model.predict( [0.9,0.1] ), 0.9, 0.1 ); console.log( 'y_hat = %d; x1 = %d; x2 = %d', model.predict( [0.1,0.9] ), 0.1, 0.9 ); console.log( 'y_hat = %d; x1 = %d; x2 = %d', model.predict( [0.9,0.9] ), 0.9, 0.9 );
'use strict'; var OnlineSVM = require( './../lib' ); var x1; var x2; var y; var i; // Create model: var model = new OnlineSVM({ 'lambda': 1e-4, 'loss': 'leastSquares', 'intercept': true }); // Data comes in... for ( i = 0; i < 100000; i++ ) { x1 = Math.random(); x2 = Math.random(); y = 3.0 * x1 + -3.0 * x2 + 2.0; model.update( y, [ x1, x2 ] ); } // Extract model coefficients: console.log( model.coefs ); // Predict new observations: console.log( 'y_hat = %d; x1 = %d; x2 = %d', model.predict( [0.9,0.1] ), 0.9, 0.1 ); console.log( 'y_hat = %d; x1 = %d; x2 = %d', model.predict( [0.1,0.9] ), 0.1, 0.9 ); console.log( 'y_hat = %d; x1 = %d; x2 = %d', model.predict( [0.9,0.9] ), 0.9, 0.9 );
Add bikeracks and Imgur API params to config
var Config = (function() { var rootURL = 'http://john.bitsurge.net/bikeracks'; var imageURL = '/static/images'; return { // API nearbyRacksURL: '/static/data/austin_racks_v1.json', updateRackURL: rootURL + '/cgi-bin/bikeracks.py', getRackURL: rootURL + '/get/', // Imgur API imgurClientID: 'f962410f5a6a13d', rackIconOptions: { iconUrl: imageURL + '/parking_bicycle_0.png', shadowUrl: imageURL + '/parking_bicycle_shadow_0.png', clusterIconUrl: imageURL + '/parking_bicycle_cluster_0.png', clusterShadowUrl: imageURL + '/parking_bicycle_cluster_shadow_0.png', iconAnchor: [13, 32], popupAnchor: [5, -24] }, markerClusterOptions: { maxClusterRadius: 30 }, geoOptions: { enableHighAccuracy: true }, // Map view config defaultZoom: 14 }; })();
var Config = { // API nearbyRacksURL: 'static/data/austin_racks_v1.json', rackIconOptions: { iconUrl: 'static/images/parking_bicycle_0.png', shadowUrl: 'static/images/parking_bicycle_shadow_0.png', clusterIconUrl: 'static/images/parking_bicycle_cluster_0.png', clusterShadowUrl: 'static/images/parking_bicycle_cluster_shadow_0.png', iconAnchor: [13, 32], popupAnchor: [5, -24] }, markerClusterOptions: { maxClusterRadius: 30 }, geoOptions: { enableHighAccuracy: true }, // Map view config defaultZoom: 14 };
Fix of the terminal parser functions passed without context
import { TerminalRuntimeError, TerminalParsingError, } from './TerminalErrors'; function errorHandler(rsp) { throw new TerminalRuntimeError(rsp); } function createSession(rsp) { if ( !rsp[`common_${this.uapi_version}:HostToken`] || !rsp[`common_${this.uapi_version}:HostToken`]._ ) { throw new TerminalParsingError.TerminalSessionTokenMissing(); } return rsp[`common_${this.uapi_version}:HostToken`]._; } function terminalRequest(rsp) { if ( !rsp['terminal:TerminalCommandResponse'] || !rsp['terminal:TerminalCommandResponse']['terminal:Text'] ) { throw new TerminalParsingError.TerminalResponseMissing(); } return rsp['terminal:TerminalCommandResponse']['terminal:Text']; } function closeSession(rsp) { if ( !rsp[`common_${this.uapi_version}:ResponseMessage`] || !rsp[`common_${this.uapi_version}:ResponseMessage`][0] || !rsp[`common_${this.uapi_version}:ResponseMessage`][0]._ || !rsp[`common_${this.uapi_version}:ResponseMessage`][0]._.match(/Terminal End Session Successful/i) ) { throw new TerminalRuntimeError.TerminalCloseSessionFailed(); } return true; } module.exports = { TERMINAL_ERROR: errorHandler, CREATE_SESSION: createSession, TERMINAL_REQUEST: terminalRequest, CLOSE_SESSION: closeSession, };
import { TerminalRuntimeError, TerminalParsingError, } from './TerminalErrors'; const errorHandler = (rsp) => { throw new TerminalRuntimeError(rsp); }; const createSession = (rsp) => { if ( !rsp[`common_${this.uapi_version}:HostToken`] || !rsp[`common_${this.uapi_version}:HostToken`]._ ) { throw new TerminalParsingError.TerminalSessionTokenMissing(); } return rsp[`common_${this.uapi_version}:HostToken`]._; }; const terminalRequest = (rsp) => { if ( !rsp['terminal:TerminalCommandResponse'] || !rsp['terminal:TerminalCommandResponse']['terminal:Text'] ) { throw new TerminalParsingError.TerminalResponseMissing(); } return rsp['terminal:TerminalCommandResponse']['terminal:Text']; }; const closeSession = (rsp) => { if ( !rsp[`common_${this.uapi_version}:ResponseMessage`] || !rsp[`common_${this.uapi_version}:ResponseMessage`][0] || !rsp[`common_${this.uapi_version}:ResponseMessage`][0]._ || !rsp[`common_${this.uapi_version}:ResponseMessage`][0]._.match(/Terminal End Session Successful/i) ) { throw new TerminalRuntimeError.TerminalCloseSessionFailed(); } return true; }; module.exports = { TERMINAL_ERROR: errorHandler, CREATE_SESSION: createSession, TERMINAL_REQUEST: terminalRequest, CLOSE_SESSION: closeSession, };
Use setImmediate instead of process.nextTick (since 0.10)
/** * Convenient Redis Storage mock for testing purposes */ var util = require ('util'); function StorageMocked(data){ data = data || {}; this.currentOutage = data.currentOutage; } exports = module.exports = StorageMocked; StorageMocked.prototype.startOutage = function (service, outageData, callback) { this.currentOutage = outageData; setImmediate(function(){ callback(null); }); }; StorageMocked.prototype.getCurrentOutage = function (service, callback) { var self = this; setImmediate(function(){ callback(null, self.currentOutage); }); }; StorageMocked.prototype.saveLatency = function (service, timestamp, latency, callback) { setImmediate(function(){ callback(null); }); }; StorageMocked.prototype.archiveCurrentOutageIfExists = function (service, callback) { var self = this; setImmediate(function(){ callback(null, self.currentOutage); }); }; StorageMocked.prototype.flush_database = function (callback){ setImmediate(function(){ callback(null); }); };
/** * Convenient Redis Storage mock for testing purposes */ var util = require ('util'); function StorageMocked(data){ data = data || {}; this.currentOutage = data.currentOutage; } exports = module.exports = StorageMocked; StorageMocked.prototype.startOutage = function (service, outageData, callback) { this.currentOutage = outageData; process.nextTick(function(){ callback(null); }); }; StorageMocked.prototype.getCurrentOutage = function (service, callback) { var self = this; process.nextTick(function(){ callback(null, self.currentOutage); }); }; StorageMocked.prototype.saveLatency = function (service, timestamp, latency, callback) { process.nextTick(function(){ callback(null); }); }; StorageMocked.prototype.archiveCurrentOutageIfExists = function (service, callback) { var self = this; process.nextTick(function(){ callback(null, self.currentOutage); }); }; StorageMocked.prototype.flush_database = function (callback){ process.nextTick(function(){ callback(null); }); };
Set instance load in instance creation
package jp.ac.nii.prl.mape.autoscaling.model; import jp.ac.nii.prl.mape.autoscaling.model.dto.InstanceDTO; public class InstanceFactory { public static Instance createInstance(InstanceDTO dto, Deployment deployment) { Instance instance = new Instance(); instance.setInstID(dto.getInstID()); instance.setDeployment(deployment); instance.setInstLoad(dto.getInstLoad()); return instance; } public static Instance createInstance(InstanceDTO dto, Deployment deployment, InstanceType instanceType) { Instance instance = createInstance(dto, deployment); instance.setInstanceType(instanceType); return instance; } public static InstanceDTO createDTO(Instance instance) { InstanceDTO dto = new InstanceDTO(); dto.setInstID(instance.getInstID()); dto.setInstLoad(instance.getInstLoad()); dto.setInstType(instance.getInstanceType().getTypeID()); return dto; } }
package jp.ac.nii.prl.mape.autoscaling.model; import jp.ac.nii.prl.mape.autoscaling.model.dto.InstanceDTO; public class InstanceFactory { public static Instance createInstance(InstanceDTO dto, Deployment deployment) { Instance instance = new Instance(); instance.setInstID(dto.getInstID()); instance.setDeployment(deployment); return instance; } public static Instance createInstance(InstanceDTO dto, Deployment deployment, InstanceType instanceType) { Instance instance = createInstance(dto, deployment); instance.setInstanceType(instanceType); return instance; } public static InstanceDTO createDTO(Instance instance) { InstanceDTO dto = new InstanceDTO(); dto.setInstID(instance.getInstID()); dto.setInstLoad(instance.getInstLoad()); dto.setInstType(instance.getInstanceType().getTypeID()); return dto; } }
Use debug mode in tests
# -*- coding: utf-8 -*- import flask import pytest import webtest import marshmallow as ma class Bunch(object): def __init__(self, **kwargs): self.__dict__.update(**kwargs) def items(self): return self.__dict__.items() @pytest.fixture def app(): app_ = flask.Flask(__name__) app_.debug = True return app_ @pytest.fixture def client(app): return webtest.TestApp(app) @pytest.fixture def models(): class Band(object): def __init__(self, name, genre): self.name = name self.genre = genre return Bunch(Band=Band) @pytest.fixture def schemas(models): class BandSchema(ma.Schema): name = ma.fields.Str() genre = ma.fields.Str() return Bunch(BandSchema=BandSchema)
# -*- coding: utf-8 -*- import flask import pytest import webtest import marshmallow as ma class Bunch(object): def __init__(self, **kwargs): self.__dict__.update(**kwargs) def items(self): return self.__dict__.items() @pytest.fixture def app(): return flask.Flask(__name__) @pytest.fixture def client(app): return webtest.TestApp(app) @pytest.fixture def models(): class Band(object): def __init__(self, name, genre): self.name = name self.genre = genre return Bunch(Band=Band) @pytest.fixture def schemas(models): class BandSchema(ma.Schema): name = ma.fields.Str() genre = ma.fields.Str() return Bunch(BandSchema=BandSchema)
Add table sheet selection capabilit
import xlutils, xypath import databaker import os import databaker.constants from databaker.constants import * # also brings in template import databaker.databakersolo as ds # causes the xypath.loader to be overwritten from databaker.jupybakeutils import HDim, HDimConst, savepreviewhtml, writetechnicalCSV, ConversionSegment def loadxlstabs(inputfile, sheetids="*"): print("Loading %s which has size %d bytes" % (inputfile, os.path.getsize(inputfile))) tableset = xypath.loader.table_set(inputfile, extension='xls') tabs = list(xypath.loader.get_sheets(tableset, sheetids)) print("Table names: %s" % ", ".join([tab.name for tab in tabs])) return tabs import pandas as pd def topandas(conversionsegment): return pd.DataFrame.from_dict(conversionsegment.lookupall())
import xlutils, xypath import databaker import os import databaker.constants from databaker.constants import * # also brings in template import databaker.databakersolo as ds # causes the xypath.loader to be overwritten from databaker.jupybakeutils import HDim, HDimConst, savepreviewhtml, writetechnicalCSV, ConversionSegment def loadxlstabs(inputfile): print("Loading %s which has size %d bytes" % (inputfile, os.path.getsize(inputfile))) tableset = xypath.loader.table_set(inputfile, extension='xls') tabs = list(xypath.loader.get_sheets(tableset, "*")) print("Table names: %s" % ", ".join([tab.name for tab in tabs])) return tabs import pandas as pd def topandas(conversionsegment): return pd.DataFrame.from_dict(conversionsegment.lookupall())
Build before you check in....
package auth import ( "github.com/gin-gonic/gin" "github.com/pufferpanel/apufferi/v4/response" "github.com/pufferpanel/pufferpanel/v2/models" "github.com/pufferpanel/pufferpanel/v2/services" "github.com/pufferpanel/pufferpanel/v2/web/handlers" "net/http" ) func Reauth(c *gin.Context) { db := handlers.GetDatabase(c) ps := &services.Permission{DB: db} user, _ := c.MustGet("user").(*models.User) perms, err := ps.GetForUserAndServer(user.ID, nil) if response.HandleError(c, err, http.StatusInternalServerError) { return } session, err := services.GenerateSession(user.ID) if response.HandleError(c, err, http.StatusInternalServerError) { return } data := &LoginResponse{} data.Session = session data.Scopes = perms.ToScopes() c.JSON(http.StatusOK, data) }
package auth import ( "github.com/gin-gonic/gin" "github.com/pufferpanel/apufferi/v4/response" "github.com/pufferpanel/pufferpanel/v2/models" "github.com/pufferpanel/pufferpanel/v2/services" "github.com/pufferpanel/pufferpanel/v2/web/handlers" "net/http" ) func Reauth(c *gin.Context) { db := handlers.GetDatabase(c) ps := &services.Permission{DB: db} user, _ := c.MustGet("user").(*models.User) perms, err := ps.GetForUserAndServer(user.ID, nil) if response.HandleError(c, err, http.StatusInternalServerError) { return } session, err := services.GenerateSession(user.ID) if response.HandleError(c, err, http.StatusInternalServerError) { return } data := &LoginResponse{} data.Session = session data.Admin = perms.Admin c.JSON(http.StatusOK, data) }
Add random punctuation, and should be done
(function () { 'use strict'; var app = require('express')(); var cors = require('cors'); var bodyParser = require('body-parser'); var http = require('http') .Server(app); app.use(cors()); app.use(bodyParser.urlencoded({ extended: false })); app.use(function (req, res, next) { res.header('Access-Control-Allow-Origin', 'http://localhost:1337'); res.header('Access-Control-Allow-Credentials', true); next(); }); app.post('/', function (req, res) { console.log(req.body); console.log('Received a hodor message!'); var punctuations = ['!', '!!', '?!', ' . . .']; var userName = req.body.user_name; var botPayload = { text: 'Hodor' + punctuations[Math.floor(Math.random() * punctuations.length)] }; // avoid infinite loop if (userName !== 'slackbot') { return res.status(200) .json(botPayload); } else { return res.status(200) .end(); } }); http.listen(process.env.PORT, function () { console.log('API server listening on *:' + process.env.PORT); }); })();
(function () { 'use strict'; var app = require('express')(); var cors = require('cors'); var bodyParser = require('body-parser'); var http = require('http') .Server(app); var API_TOKEN = 'HNRO7R4NKRZrgbVf4JvhoeLY'; app.use(cors()); app.use(bodyParser.urlencoded({ extended: false })); app.use(function (req, res, next) { res.header('Access-Control-Allow-Origin', 'http://localhost:1337'); res.header('Access-Control-Allow-Credentials', true); next(); }); app.post('/', function (req, res) { console.log(req.body); console.log('Received a hodor message!'); var userName = req.body.user_name; var botPayload = { text: 'Hello, ' + userName + '!' }; // avoid infinite loop if (userName !== 'slackbot') { return res.status(200) .json(botPayload); } else { return res.status(200) .end(); } res.send('Thanks!'); }); http.listen(process.env.PORT, function () { console.log('API server listening on *:' + process.env.PORT); }); })();
Add Javadoc to working time properties
package org.synyx.urlaubsverwaltung.workingtime.config; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import org.springframework.validation.annotation.Validated; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import java.util.List; @Component @ConfigurationProperties("uv.workingtime") @Validated public class WorkingTimeProperties { /** * Define the default working days that will be configured for * every newly created person. * * Default values: Monday, Tuesday, Wednesday, Thursday, Friday */ @NotNull private List<@Min(1) @Max(7) Integer> defaultWorkingDays = List.of(1, 2, 3, 4, 5); public List<Integer> getDefaultWorkingDays() { return defaultWorkingDays; } public void setDefaultWorkingDays(List<Integer> defaultWorkingDays) { this.defaultWorkingDays = defaultWorkingDays; } }
package org.synyx.urlaubsverwaltung.workingtime.config; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import org.springframework.validation.annotation.Validated; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import java.util.List; @Component @ConfigurationProperties("uv.workingtime") @Validated public class WorkingTimeProperties { @NotNull private List<@Min(1) @Max(7) Integer> defaultWorkingDays = List.of(1, 2, 3, 4, 5); public List<Integer> getDefaultWorkingDays() { return defaultWorkingDays; } public void setDefaultWorkingDays(List<Integer> defaultWorkingDays) { this.defaultWorkingDays = defaultWorkingDays; } }
Use prefixName abstraction in nano.use
var NanoProxyDbFunctions = function(nano, prefix) { this.nano = nano; this.prefix = prefix; }; NanoProxyDbFunctions.prototype.create = function(name, callback) { return this.nano.db.create(prefixName.call(this, name), callback); }; function prefixName(name) { return [this.prefix, name].join("_"); } NanoProxyDbFunctions.prototype.get = function(name, callback) { }; NanoProxyDbFunctions.prototype.destroy = function(name, callback) { }; NanoProxyDbFunctions.prototype.list = function(callback) { }; NanoProxyDbFunctions.prototype.compact = function(name, designname, callback) { }; NanoProxyDbFunctions.prototype.replicate = function(source, target, opts, callback) { }; NanoProxyDbFunctions.prototype.changes = function(name, params, callback) { }; NanoProxyDbFunctions.prototype.follow = function(name, params, callback) { }; NanoProxyDbFunctions.prototype.use = function(name) { return this.nano.use(prefixName.call(this, name)); }; module.exports = NanoProxyDbFunctions;
var NanoProxyDbFunctions = function(nano, prefix) { this.nano = nano; this.prefix = prefix; }; NanoProxyDbFunctions.prototype.create = function(name, callback) { return this.nano.db.create(prefixName.call(this, name), callback); }; function prefixName(name) { return [this.prefix, name].join("_"); } NanoProxyDbFunctions.prototype.get = function(name, callback) { }; NanoProxyDbFunctions.prototype.destroy = function(name, callback) { }; NanoProxyDbFunctions.prototype.list = function(callback) { }; NanoProxyDbFunctions.prototype.compact = function(name, designname, callback) { }; NanoProxyDbFunctions.prototype.replicate = function(source, target, opts, callback) { }; NanoProxyDbFunctions.prototype.changes = function(name, params, callback) { }; NanoProxyDbFunctions.prototype.follow = function(name, params, callback) { }; NanoProxyDbFunctions.prototype.use = function(name) { return this.nano.use([this.prefix, name].join("_")); }; module.exports = NanoProxyDbFunctions;
Fix bad test runner setup
const Application = require('spectron').Application const assert = require('assert') const path = require('path') describe('application launch', function() { this.timeout(10000) beforeEach(function() { this.app = new Application({ path: path.join(__dirname, '..', 'node_modules', '.bin', 'electron'), args: [path.join(__dirname, '..', 'src', 'main.js')], }) return this.app.start() }) afterEach(function() { if (this.app && this.app.isRunning()) { return this.app.stop() } }) it('shows an initial window', function() { return this.app.client.getWindowCount().then(function(count) { assert.equal(count, 1) }) }) it('renders sarah', function() { return this.app.client.getText('p').then(text => { assert.equal('sarah', text) }) }) })
const Application = require('spectron').Application const assert = require('assert') const path = require('path') describe('application launch', function() { this.timeout(10000) beforeEach(function() { this.app = new Application({ path: path.join(__dirname, '..', 'node_modules', '.bin', 'electron'), args: [path.join(__dirname, '..', 'src')] }) return this.app.start() }) afterEach(function() { if (this.app && this.app.isRunning()) { return this.app.stop() } }) it('shows an initial window', function() { return this.app.client.getWindowCount().then(function(count) { assert.equal(count, 1) }) }) it('renders sarah', function() { return this.app.client.getText('p').then(text => { assert.equal('sarah', text) }) }) })