text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Use KCommandContext::getSubject() instead of $command->caller
<?php /** * @version $Id$ * @package Nooku_Components * @subpackage Files * @copyright Copyright (C) 2011 - 2012 Timble CVBA and Contributors. (http://www.timble.net). * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link http://www.nooku.org */ /** * Folder Name Filter Class * * @author Ercan Ozkaya <http://nooku.assembla.com/profile/ercanozkaya> * @package Nooku_Components * @subpackage Files */ class ComFilesFilterFolderName extends KFilterAbstract { protected $_walk = false; protected function _validate($context) { $value = $context->getSubject()->name; if (strpos($value, '/') !== false) { $context->setError(JText::_('Folder names cannot contain slashes')); return false; } if ($this->_sanitize($value) == '') { $context->setError(JText::_('Invalid folder name')); return false; } } protected function _sanitize($value) { $value = str_replace('/', '', $value); return $this->getService('com://admin/files.filter.path')->sanitize($value); } }
<?php /** * @version $Id$ * @package Nooku_Components * @subpackage Files * @copyright Copyright (C) 2011 - 2012 Timble CVBA and Contributors. (http://www.timble.net). * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link http://www.nooku.org */ /** * Folder Name Filter Class * * @author Ercan Ozkaya <http://nooku.assembla.com/profile/ercanozkaya> * @package Nooku_Components * @subpackage Files */ class ComFilesFilterFolderName extends KFilterAbstract { protected $_walk = false; protected function _validate($context) { $value = $context->caller->name; if (strpos($value, '/') !== false) { $context->setError(JText::_('Folder names cannot contain slashes')); return false; } if ($this->_sanitize($value) == '') { $context->setError(JText::_('Invalid folder name')); return false; } } protected function _sanitize($value) { $value = str_replace('/', '', $value); return $this->getService('com://admin/files.filter.path')->sanitize($value); } }
Update sample config file header
package common const ( usageNotes = `Notes: --roles=node,proxy,auth This flag tells Teleport which services to run. By default it runs all three. In a production environment you may want to separate them. --token=xyz This token is needed to connect a node to an auth server. Obtain it by running "tctl nodes add" on the auth server. It's used once and ignored afterwards. ` usageExamples = ` Examples: > teleport start By default without any configuration, teleport starts running as a single-node cluster. It's the equivalent of running with --roles=node,proxy,auth > teleport start --roles=node --auth-server=10.1.0.1 --token=xyz --nodename=db Starts a node named 'db' running in strictly SSH mode role, joining the cluster serviced by the auth server running on 10.1.0.1 > teleport start --roles=node --auth-server=10.1.0.1 --labels=db=master Same as the above, but the node runs with db=master label and can be connected to using that label in addition to its name.` sampleConfComment = `# # Sample Teleport configuration file # Creates a single proxy, auth and node server. # # Things to update: # 1. ca_pin: Obtain the CA pin hash for joining more nodes by running 'tctl status' # on the auth server once Teleport is running. # 2. cluster-join-token: Update to a more secure static token. For more details, # see https://gravitational.com/teleport/docs/admin-guide/#adding-nodes-to-the-cluster # 3. license-if-using-teleport-enterprise.pem: If you are an Enterprise customer, # obtain this from https://dashboard.gravitational.com/web/ #` )
package common const ( usageNotes = `Notes: --roles=node,proxy,auth This flag tells Teleport which services to run. By default it runs all three. In a production environment you may want to separate them. --token=xyz This token is needed to connect a node to an auth server. Obtain it by running "tctl nodes add" on the auth server. It's used once and ignored afterwards. ` usageExamples = ` Examples: > teleport start By default without any configuration, teleport starts running as a single-node cluster. It's the equivalent of running with --roles=node,proxy,auth > teleport start --roles=node --auth-server=10.1.0.1 --token=xyz --nodename=db Starts a node named 'db' running in strictly SSH mode role, joining the cluster serviced by the auth server running on 10.1.0.1 > teleport start --roles=node --auth-server=10.1.0.1 --labels=db=master Same as the above, but the node runs with db=master label and can be connected to using that label in addition to its name.` sampleConfComment = `# # Sample Teleport configuration file. #` )
Exclude `node_modules` from transpilation explicitly
#!/usr/bin/env node // Native const path = require('path') // Packages const asyncToGen = require('async-to-gen/register') const updateNotifier = require('update-notifier') const {red} = require('chalk') const nodeVersion = require('node-version') const isAsyncSupported = require('is-async-supported') // Ours const pkg = require('../package') // Support for keywords "async" and "await" if (!isAsyncSupported()) { const modulesDir = path.join(__dirname, '..', 'node_modules') asyncToGen({ excludes: new RegExp(`.*${modulesDir}.*`), sourceMaps: false }) } // Throw an error if node version is too low if (nodeVersion.major < 6) { console.error(`${red('Error!')} Serve requires at least version 6 of Node. Please upgrade!`) process.exit(1) } // Let user know if there's an update // This isn't important when deployed to Now if (!process.env.NOW && pkg.dist) { updateNotifier({pkg}).notify() } // Load package core with async/await support require('../lib')
#!/usr/bin/env node // Native const path = require('path') // Packages const asyncToGen = require('async-to-gen/register') const updateNotifier = require('update-notifier') const {red} = require('chalk') const nodeVersion = require('node-version') const isAsyncSupported = require('is-async-supported') // Ours const pkg = require('../package') // Support for keywords "async" and "await" if (!isAsyncSupported()) { const pathSep = process.platform === 'win32' ? '\\\\' : '/' const directoryName = path.parse(path.join(__dirname, '..')).base asyncToGen({ includes: new RegExp(`.*${directoryName}?${pathSep}(lib|bin).*`), excludes: null, sourceMaps: false }) } // Throw an error if node version is too low if (nodeVersion.major < 6) { console.error(`${red('Error!')} Serve requires at least version 6 of Node. Please upgrade!`) process.exit(1) } // Let user know if there's an update // This isn't important when deployed to Now if (!process.env.NOW && pkg.dist) { updateNotifier({pkg}).notify() } // Load package core with async/await support require('../lib')
Fix curl info for php >= 7.4.0 PHP 7.4 does not give back all the options when passed null as second argument. This pull request fixes this.
<?php namespace Picqer\BolPlazaClient\Request; class CurlHttpRequest { protected $ch = null; public function __construct($url) { $this->ch = curl_init($url); } public function setOption($option, $value) { curl_setopt($this->ch, $option, $value); } public function execute() { return curl_exec($this->ch); } public function getInfo($option = null) { if($opt) { return curl_getinfo($this->ch, $option); } else { return curl_getinfo($this->ch); } } public function close() { curl_close($this->ch); } public function getErrorNumber() { return curl_errno($this->ch); } }
<?php namespace Picqer\BolPlazaClient\Request; class CurlHttpRequest { protected $ch = null; public function __construct($url) { $this->ch = curl_init($url); } public function setOption($option, $value) { curl_setopt($this->ch, $option, $value); } public function execute() { return curl_exec($this->ch); } public function getInfo($option = null) { return curl_getinfo($this->ch, $option); } public function close() { curl_close($this->ch); } public function getErrorNumber() { return curl_errno($this->ch); } }
Add support for Django 1.10+
from django.conf import settings from django.db.models.aggregates import Sum class SQLSum(Sum): @property def sql_template(self): if settings.DATABASES['default']['ENGINE'] == \ 'django.db.backends.postgresql_psycopg2': return '%(function)s(%(field)s::int)' return '%(function)s(%(field)s)' class BooleanSum(Sum): def add_to_query(self, query, alias, col, source, is_summary): aggregate = SQLSum(col, source=source, is_summary=is_summary, **self.extra) query.aggregates[alias] = aggregate
from django.conf import settings from django.db.models.aggregates import Sum from django.db.models.sql.aggregates import Sum as BaseSQLSum class SQLSum(BaseSQLSum): @property def sql_template(self): if settings.DATABASES['default']['ENGINE'] == \ 'django.db.backends.postgresql_psycopg2': return '%(function)s(%(field)s::int)' return '%(function)s(%(field)s)' class BooleanSum(Sum): function = None def add_to_query(self, query, alias, col, source, is_summary): aggregate = SQLSum(col, source=source, is_summary=is_summary, **self.extra) query.aggregates[alias] = aggregate
Allow Content-Type header in CORS.
package info.agrueneberg.fhir.filters; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; @Component public class CorsFilter implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE"); response.setHeader("Access-Control-Allow-Headers", "x-requested-with, content-type"); response.setHeader("Access-Control-Max-Age", "3600"); chain.doFilter(req, res); } @Override public void init(FilterConfig filterConfig) { } @Override public void destroy() { } }
package info.agrueneberg.fhir.filters; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; @Component public class CorsFilter implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "x-requested-with"); chain.doFilter(req, res); } @Override public void init(FilterConfig filterConfig) { } @Override public void destroy() { } }
Fix recur bug: Not working when floating task is added
package seedu.ezdo.commons.util; import seedu.ezdo.model.todo.ReadOnlyTask; //@@author A0139177W /** * Utility method for Recur */ public class RecurUtil { /** * Checks if a recurring status is valid with at least a start date and/or * due date present in a task. Floating tasks should not have a recurring * status. * @param task * @return false if the task is a floating task * @return true otherwise */ public static boolean isRecurValid(ReadOnlyTask task) { assert task != null; String taskStartDate = task.getStartDate().toString(); String taskDueDate = task.getDueDate().toString(); final boolean isStartDateMissing = taskStartDate.isEmpty(); final boolean isDueDateMissing = taskDueDate.isEmpty(); final boolean isBothDatesMissing = isStartDateMissing && isDueDateMissing; final boolean isRecurring = task.getRecur().isRecur(); if (isBothDatesMissing && isRecurring) { return false; } return true; } }
package seedu.ezdo.commons.util; import seedu.ezdo.model.todo.ReadOnlyTask; //@@author A0139177W /** * Utility method for Recur */ public class RecurUtil { /** * Checks if a recurring status is valid with at least a start date and/or * due date present in a task. Floating tasks should not have a recurring * status. * @param task * @return false if the task is a floating task * @return true otherwise */ public static boolean isRecurValid(ReadOnlyTask task) { assert task != null; String taskStartDate = task.getStartDate().toString(); String taskDueDate = task.getDueDate().toString(); final boolean isStartDateMissing = taskStartDate.isEmpty(); final boolean isDueDateMissing = taskDueDate.isEmpty(); if (isStartDateMissing && isDueDateMissing) { return false; } else { return true; } } }
Add socket shutdown to prevent bridge from crashing on connection reset.
import socket import time from flask import * import config # TCP port the Yun console listens for connections on. CONSOLE_PORT = 6571 # Create flask application. app = Flask(__name__) # Get activity configuration. activities = config.get_activities() @app.route('/') def root(): return render_template('index.html', activities=activities) @app.route('/activity/<int:index>', methods=['POST']) def activity(index): # Connect to the console socket. console = socket.create_connection(('localhost', CONSOLE_PORT)) # Send all the codes in order that are associated with the activity. for code in activities[index].get('codes', []): console.sendall(code + '\n') # Wait ~500 milliseconds between codes. time.sleep(0.5) console.shutdown(socket.SHUT_RDWR) console.close() return 'OK' if __name__ == '__main__': # Create a server listening for external connections on the default # port 5000. Enable debug mode for better error messages and live # reloading of the server on changes. Also make the server threaded # so multiple connections can be processed at once (very important # for using server sent events). app.run(host='0.0.0.0', debug=True, threaded=True)
import socket import time from flask import * import config # TCP port the Yun console listens for connections on. CONSOLE_PORT = 6571 # Create flask application. app = Flask(__name__) # Get activity configuration. activities = config.get_activities() @app.route('/') def root(): return render_template('index.html', activities=activities) @app.route('/activity/<int:index>', methods=['POST']) def activity(index): # Connect to the console socket. console = socket.create_connection(('localhost', CONSOLE_PORT)) # Send all the codes in order that are associated with the activity. for code in activities[index].get('codes', []): console.sendall(code + '\n') # Wait ~500 milliseconds between codes. time.sleep(0.5) console.close() return 'OK' if __name__ == '__main__': # Create a server listening for external connections on the default # port 5000. Enable debug mode for better error messages and live # reloading of the server on changes. Also make the server threaded # so multiple connections can be processed at once (very important # for using server sent events). app.run(host='0.0.0.0', debug=True, threaded=True)
Use output stream's encoding (if any). Blindly using UTF-8 would break output on Windows terminals.
# -*- coding: utf-8 -*- # Copyright (c) 2013-2015, Sebastian Linke # Released under the Simplified BSD license # (see LICENSE file for details). """ Constants that are used by `shcol` in many places. This is meant to modified (if needed) only *before* running `shcol`, since most of these constants are only read during initialization of the `shcol`-package. """ import logging import os import sys ERROR_STREAM = sys.stderr INPUT_STREAM = sys.stdin LINE_WIDTH = None LINESEP = '\n' LOGGER = logging.getLogger('shol') MAKE_UNIQUE = False ON_WINDOWS = 'windows' in os.getenv('os', '').lower() PY_VERSION = sys.version_info[:2] SORT_ITEMS = False SPACING = 2 STARTER = os.path.join('bin', 'shcol' + ('.bat' if ON_WINDOWS else '')) TERMINAL_STREAM = sys.stdout UNICODE_TYPE = type(u'') ENCODING = TERMINAL_STREAM.encoding or 'utf-8'
# -*- coding: utf-8 -*- # Copyright (c) 2013-2015, Sebastian Linke # Released under the Simplified BSD license # (see LICENSE file for details). """ Constants that are used by `shcol` in many places. This is meant to modified (if needed) only *before* running `shcol`, since most of these constants are only read during initialization of the `shcol`-package. """ import logging import os import sys ENCODING = 'utf-8' ERROR_STREAM = sys.stderr INPUT_STREAM = sys.stdin LINE_WIDTH = None LINESEP = '\n' LOGGER = logging.getLogger('shol') MAKE_UNIQUE = False ON_WINDOWS = 'windows' in os.getenv('os', '').lower() PY_VERSION = sys.version_info[:2] SORT_ITEMS = False SPACING = 2 STARTER = os.path.join('bin', 'shcol' + ('.bat' if ON_WINDOWS else '')) TERMINAL_STREAM = sys.stdout UNICODE_TYPE = type(u'')
Revert "Temporarily disable dynamic cloud-config features in bosh editor" This reverts commit ebcd3f41cbb75a4e78bac00442390848631aeadc.
/******************************************************************************* * Copyright (c) 2016-2017 Pivotal, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Pivotal, Inc. - initial API and implementation *******************************************************************************/ package org.springframework.ide.vscode.bosh; import java.io.IOException; import org.springframework.ide.vscode.bosh.models.BoshCommandCloudConfigProvider; import org.springframework.ide.vscode.commons.languageserver.LaunguageServerApp; public class Main { public static void main(String[] args) throws IOException, InterruptedException { LaunguageServerApp.start(() -> new BoshLanguageServer( new BoshCommandCloudConfigProvider(), (dc) -> null //TODO: real model provider here! )); } }
/******************************************************************************* * Copyright (c) 2016-2017 Pivotal, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Pivotal, Inc. - initial API and implementation *******************************************************************************/ package org.springframework.ide.vscode.bosh; import java.io.IOException; import org.springframework.ide.vscode.commons.languageserver.LaunguageServerApp; public class Main { public static void main(String[] args) throws IOException, InterruptedException { LaunguageServerApp.start(() -> new BoshLanguageServer( (dc) -> null, //TODO: temporarily disabled.. reenable: new BoshCommandCloudConfigProvider(), (dc) -> null //TODO: real model provider here! )); } }
Update make WM ontmap with SOFIA
import sys from indra.sources import eidos from indra.sources.hume.make_hume_tsv import make_file as mht from indra.sources.sofia.make_sofia_tsv import make_file as mst from indra.java_vm import autoclass eidos_package = 'org.clulab.wm.eidos' if __name__ == '__main__': sofia_ont_path = sys.argv[1] hume_path = 'hume_ontology_examaples.tsv' mht(hume_path) sofia_path = 'sofia_ontology_examples.tsv' mst(sofia_ont_path, sofia_path) om = autoclass(eidos_package + '.apps.OntologyMapper') eidos = autoclass(eidos_package + '.EidosSystem') es = eidos(autoclass('java.lang.Object')()) example_weight = 0.8 parent_weight = 0.1 topn = 10 table_str = om.mapOntologies(es, hume_path, sofia_path, example_weight, parent_weight, topn)
from indra.sources import eidos from indra.sources.hume.make_hume_tsv import make_file from indra.java_vm import autoclass eidos_package = 'org.clulab.wm.eidos' if __name__ == '__main__': bbn_path = 'hume_examaples.tsv' make_file(bbn_path) sofia_path = 'sofia_examples.tsv' om = autoclass(eidos_package + '.apps.OntologyMapper') eidos = autoclass(eidos_package + '.EidosSystem') es = eidos(autoclass('java.lang.Object')()) example_weight = 0.8 parent_weight = 0.1 topn = 10 table_str = om.mapOntologies(es, bbn_path, sofia_path, example_weight, parent_weight, topn)
Add note about model/transform modules not depending on the browser
// !! // This module defines ProseMirror's document model, the data // structure used to define and inspect content documents. It // includes: // // * The [node](#Node) type that represents document elements // // * The [schema](#Schema) types used to tag and constrain the // document structure // // * The data type for document [positions](#Pos) // // This module does not depend on the browser API being available // (i.e. you can load it into any JavaScript environment). export {Node} from "./node" export {Fragment, emptyFragment} from "./fragment" export {Mark} from "./mark" export {SchemaSpec, Schema, SchemaError, NodeType, Block, Textblock, Inline, Text, MarkType, Attribute} from "./schema" export {defaultSchema, Doc, BlockQuote, OrderedList, BulletList, ListItem, HorizontalRule, Paragraph, Heading, CodeBlock, Image, HardBreak, CodeMark, EmMark, StrongMark, LinkMark} from "./defaultschema" export {Pos} from "./pos" export {findDiffStart, findDiffEnd} from "./diff"
// !! // This module defines ProseMirror's document model, the data // structure used to define and inspect content documents. It // includes: // // * The [node](#Node) type that represents document elements // // * The [schema](#Schema) types used to tag and constrain the // document structure // // * The data type for document [positions](#Pos) export {Node} from "./node" export {Fragment, emptyFragment} from "./fragment" export {Mark} from "./mark" export {SchemaSpec, Schema, SchemaError, NodeType, Block, Textblock, Inline, Text, MarkType, Attribute} from "./schema" export {defaultSchema, Doc, BlockQuote, OrderedList, BulletList, ListItem, HorizontalRule, Paragraph, Heading, CodeBlock, Image, HardBreak, CodeMark, EmMark, StrongMark, LinkMark} from "./defaultschema" export {Pos} from "./pos" export {findDiffStart, findDiffEnd} from "./diff"
Move bookkeeping of page_model to start().
/*** Intro Screen Controller Responsible for handling the intro screen controls ***/ define(['require', 'jsclass/min/core', 'client/base/controller', 'client/models/model_top_images', 'client/configuration'], function (require) { 'use strict'; var Controller = require('client/base/controller'), ModelTopImages = require('client/models/model_top_images'), CONFIGURATION = require('client/configuration'); return new JS.Class(Controller, { 'initialize': function(parent_controller, view) { this.callSuper(); }, 'start': function() { this.callSuper(); this.page_model = this.models[0]; this.top_images_model = new ModelTopImages(); this.top_images_model.loadFromServer( 0, CONFIGURATION.INTRO_TOP_X_IMAGES_COUNT ); this.view.setTopImagesModel( this.top_images_model ); }, 'onStartPressed': function() { this.page_model.changeScreen( "IN_GAME" ); } }); });
/*** Intro Screen Controller Responsible for handling the intro screen controls ***/ define(['require', 'jsclass/min/core', 'client/base/controller', 'client/models/model_top_images', 'client/configuration'], function (require) { 'use strict'; var Controller = require('client/base/controller'), ModelTopImages = require('client/models/model_top_images'), CONFIGURATION = require('client/configuration'); return new JS.Class(Controller, { 'initialize': function(parent_controller, view, page_model ) { this.callSuper(); this.page_model = page_model; }, 'start': function() { this.callSuper(); this.top_images_model = new ModelTopImages(); this.top_images_model.loadFromServer( 0, CONFIGURATION.INTRO_TOP_X_IMAGES_COUNT ); this.view.setTopImagesModel( this.top_images_model ); }, 'onStartPressed': function() { this.page_model.changeScreen( "IN_GAME" ); } }); });
Use IRB to run code
var app = require('http').createServer(), io = require('socket.io').listen(app), spawn = require('child_process').spawn, fs = require('fs'); var tones = io.of('/ruby').on('connection', function(socket) { var ruby = spawn('irb'); ruby.stdout.on('data', function(data) { console.log('stdout: ' + data); socket.emit('terminalOutput', { output: data.toString() }); }); ruby.stderr.on('data', function(data) { console.log('stderr: ' + data); socket.emit('terminalOutput', { output: data.toString() }); }); ruby.on('close', function(code) { console.log('Exit code: ' + code); }); socket.on('fileInput', function(data) { console.log(data); ruby.stdin.write('exec($0)\n', function() { ruby.stdin.write(data.input + '\n'); }); }); socket.on('terminalInput', function(data) { console.log(data); ruby.stdin.write(data.input + '\n'); }); socket.emit('ready', { output: 'Enter valid ruby code...' }); }); app.listen(process.env.PORT || 8888);
var app = require('http').createServer(), io = require('socket.io').listen(app), exec = require('child_process').execFile; var tones = io.of('/ruby').on('connection', function(socket) { socket.on('terminalInput', function(data) { console.log(data); exec('ruby', ['-e', data.input], function (err, stdout, stderr) { console.log(stdout); console.log(stderr); socket.emit('terminalOutput', { output: stderr || stdout }); }); }); socket.emit('ready', { output: 'Enter valid ruby code...' }); }); app.listen(process.env.PORT || 8888);
Clean up lookupdomain int test
<?php use OpenSRS\domains\lookup\LookupDomain; class LookupDomainIntegrationTest extends PHPUnit_Framework_TestCase { /** * Should be able to do a lookup on google.com * * * @return void */ public function testlookupGoogle() { $data = (object) array ( 'func' => 'lookupDomain', 'data' => (object) array ( 'domain' => 'google.com', ), ); $ld = new LookupDomain('array', $data); $this->assertEquals($ld->resultRaw[0]['status'], 'taken'); } }
<?php use OpenSRS\domains\lookup\LookupDomain; class LookupDomainIntegrationTest extends PHPUnit_Framework_TestCase { /** * Should be able to do a lookup on google.com * * * @return void */ public function testlookupGoogle() { $data = (object) array ( 'func' => 'premiumDomain', 'data' => (object) array ( 'domain' => 'google.com', 'selected' => '.com', ), ); $ld = new LookupDomain('array', $data); $this->assertEquals($ld->resultRaw[0]['status'], 'taken'); } }
Fix test failing on python 3
#!/usr/bin/env python # vim:fileencoding=utf-8 # License: Apache 2.0 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> from __future__ import absolute_import, division, print_function, unicode_literals import sys from __init__ import TestCase from html5_parser import parse HTML = ''' <html lang="en" xml:lang="en"> <head><script>a < & " b</script><title>title</title></head> <body> <p>A <span>test</span> of text and tail <p><svg viewbox="v"><image xlink:href="h"> </body> <!-- A -- comment ---> </html> ''' class AdaptTest(TestCase): def test_etree(self): from xml.etree.ElementTree import tostring root = parse(HTML, treebuilder='etree') self.ae(root.tag, 'html') self.ae(root.attrib, {'xml:lang': 'en', 'lang': 'en'}) self.ae(root.find('./head/script').text, 'a < & " b') self.ae( tostring(root.find('body').find('p'), method='text').decode('ascii'), 'A test of text and tail\n') if sys.version_info.major > 2: self.assertIn('<!-- A -- comment --->', tostring(root).decode('ascii'))
#!/usr/bin/env python # vim:fileencoding=utf-8 # License: Apache 2.0 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> from __future__ import absolute_import, division, print_function, unicode_literals import sys from __init__ import TestCase from html5_parser import parse HTML = ''' <html lang="en" xml:lang="en"> <head><script>a < & " b</script><title>title</title></head> <body> <p>A <span>test</span> of text and tail <p><svg viewbox="v"><image xlink:href="h"> </body> <!-- A -- comment ---> </html> ''' class AdaptTest(TestCase): def test_etree(self): from xml.etree.ElementTree import tostring root = parse(HTML, treebuilder='etree') self.ae(root.tag, 'html') self.ae(root.attrib, {'xml:lang': 'en', 'lang': 'en'}) self.ae(root.find('./head/script').text, 'a < & " b') self.ae( tostring(root.find('body').find('p'), method='text').decode('ascii'), 'A test of text and tail\n') if sys.version_info.major > 2: self.assertIn('<!-- A -- comment --->', tostring(root))
Make the alt attribute for avatar image better
import { readOnly } from '@ember/object/computed'; import Component from '@glimmer/component'; export default class UserAvatar extends Component { get width() { if (this.args.size === 'medium') { return 85; } else if (this.args.size === 'medium-small') { return 32; } else { return 22; // small } } @readOnly('width') height; get alt() { return this.args.user.name !== null ? `${this.args.user.name} (${this.args.user.login})` : `(${this.args.user.login})`; } get title() { let user = this.args.user; switch (user.kind) { case 'user': return user.name; case 'team': return `${user.name} team`; default: return `${user.name} (${user.kind})`; } } get src() { return `${this.args.user.avatar}&s=${this.width * 2}`; } }
import { readOnly } from '@ember/object/computed'; import Component from '@glimmer/component'; export default class UserAvatar extends Component { get width() { if (this.args.size === 'medium') { return 85; } else if (this.args.size === 'medium-small') { return 32; } else { return 22; // small } } @readOnly('width') height; get alt() { return `${this.args.user.name} (${this.args.user.login})`; } get title() { let user = this.args.user; switch (user.kind) { case 'user': return user.name; case 'team': return `${user.name} team`; default: return `${user.name} (${user.kind})`; } } get src() { return `${this.args.user.avatar}&s=${this.width * 2}`; } }
Allow CLI to find devices based on model and type
'use strict'; const { EventEmitter } = require('events'); const { Browser, Devices } = require('../lib/discovery'); function asFilter(filter) { if(typeof filter === 'string') { return reg => reg.id === filter || reg.address === filter || reg.model === filter || reg.type === filter; } else if(typeof filter === 'function') { return filter; } else { return () => true; } } function asToplevelFilter(filter) { return reg => reg.type === 'gateway' || filter(reg); } module.exports = function(options) { const filter = asFilter(options.filter); let browser; if(options.instances) { browser = new Devices({ cacheTime: options.cacheTime || 300, filter: options.filter ? asToplevelFilter(filter) : null }); } else { browser = new Browser({ cachetime: options.cacheTime || 300 }); } const result = new EventEmitter(); browser.on('available', reg => { if(filter(reg)) { result.emit('available', reg); } }); browser.on('unavailable', reg => result.emit('unavailable', reg)); return result; };
'use strict'; const { EventEmitter } = require('events'); const { Browser, Devices } = require('../lib/discovery'); function asFilter(filter) { if(typeof filter === 'string') { return reg => reg.id === filter || reg.address === filter; } else if(typeof filter === 'function') { return filter; } else { return () => true; } } function asToplevelFilter(filter) { return reg => reg.type === 'gateway' || filter(reg); } module.exports = function(options) { const filter = asFilter(options.filter); let browser; if(options.instances) { browser = new Devices({ cacheTime: options.cacheTime || 300, filter: options.filter ? asToplevelFilter(filter) : null }); } else { browser = new Browser({ cachetime: options.cacheTime || 300 }); } const result = new EventEmitter(); browser.on('available', reg => { if(filter(reg)) { result.emit('available', reg); } }); browser.on('unavailable', reg => result.emit('unavailable', reg)); return result; };
Change unit tests for cache invalidation handler to include the constructor
package composition import ( "github.com/golang/mock/gomock" mockhttp "github.com/tarent/lib-compose/composition/mocks/net/http" "net/http" "testing" ) func Test_CacheInvalidationHandler_Invalidation(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() //given cacheMocK := NewMockCache(ctrl) cih := NewCacheInvalidationHandler(cacheMocK, nil) request, _ := http.NewRequest(http.MethodDelete, "internal/cache", nil) //when cacheMocK.EXPECT().Invalidate().Times(1) cih.ServeHTTP(nil, request) } func Test_CacheInvalidationHandler_Delegate_Is_Called(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() //given handlerMock := mockhttp.NewMockHandler(ctrl) cacheMocK := NewMockCache(ctrl) cih := NewCacheInvalidationHandler(cacheMocK, handlerMock) request, _ := http.NewRequest(http.MethodDelete, "internal/cache", nil) //when cacheMocK.EXPECT().Invalidate().AnyTimes() handlerMock.EXPECT().ServeHTTP(gomock.Any(), gomock.Any()).Times(1) cih.ServeHTTP(nil, request) }
package composition import ( "github.com/golang/mock/gomock" mockhttp "github.com/tarent/lib-compose/composition/mocks/net/http" "net/http" "testing" ) func Test_CacheInvalidationHandler_Invalidation(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() //given cacheMocK := NewMockCache(ctrl) cih := &CacheInvalidationHandler{cache: cacheMocK} request, _ := http.NewRequest(http.MethodDelete, "internal/cache", nil) //when cacheMocK.EXPECT().Invalidate().Times(1) cih.ServeHTTP(nil, request) } func Test_CacheInvalidationHandler_Delegate_Is_Called(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() //given handlerMock := mockhttp.NewMockHandler(ctrl) cacheMocK := NewMockCache(ctrl) cih := &CacheInvalidationHandler{cache: cacheMocK, next: handlerMock} request, _ := http.NewRequest(http.MethodDelete, "internal/cache", nil) //when cacheMocK.EXPECT().Invalidate().AnyTimes() handlerMock.EXPECT().ServeHTTP(gomock.Any(), gomock.Any()).Times(1) cih.ServeHTTP(nil, request) }
Fix char test to only run on test/none. Change-Id: I8f5ac5a6e7399ce2fdbe78d07ae24deaa1d7532d Reviewed-on: http://gerrit.sjc.cloudera.com:8080/4326 Tested-by: jenkins Reviewed-by: Alex Behm <fe1626037acfc2dc542d2aa723a6d14f2464a20c@cloudera.com>
#!/usr/bin/env python # Copyright (c) 2012 Cloudera, Inc. All rights reserved. # import logging import pytest from copy import copy from tests.common.test_vector import * from tests.common.impala_test_suite import * class TestStringQueries(ImpalaTestSuite): @classmethod def get_workload(cls): return 'functional-query' def setup_method(self, method): self.__cleanup_char_tables() self.__create_char_tables() def teardown_method(self, method): self.__cleanup_char_tables() def __cleanup_char_tables(self): self.client.execute('drop table if exists functional.test_char_tmp'); self.client.execute('drop table if exists functional.test_varchar_tmp'); def __create_char_tables(self): self.client.execute( 'create table if not exists functional.test_varchar_tmp (vc varchar(5))') self.client.execute( 'create table if not exists functional.test_char_tmp (c char(5))') @classmethod def add_test_dimensions(cls): super(TestStringQueries, cls).add_test_dimensions() cls.TestMatrix.add_dimension( create_exec_option_dimension(disable_codegen_options=[True])) cls.TestMatrix.add_constraint(lambda v:\ v.get_value('table_format').file_format in ['text'] and v.get_value('table_format').compression_codec in ['none']) def test_varchar(self, vector): self.run_test_case('QueryTest/chars', vector)
#!/usr/bin/env python # Copyright (c) 2012 Cloudera, Inc. All rights reserved. # import logging import pytest from copy import copy from tests.common.test_vector import * from tests.common.impala_test_suite import * class TestStringQueries(ImpalaTestSuite): @classmethod def get_workload(cls): return 'functional-query' def setup_method(self, method): self.__cleanup_char_tables() self.__create_char_tables() def teardown_method(self, method): self.__cleanup_char_tables() def __cleanup_char_tables(self): self.client.execute('drop table if exists functional.test_char_tmp'); self.client.execute('drop table if exists functional.test_varchar_tmp'); def __create_char_tables(self): self.client.execute( 'create table if not exists functional.test_varchar_tmp (vc varchar(5))') self.client.execute( 'create table if not exists functional.test_char_tmp (c char(5))') @classmethod def add_test_dimensions(cls): super(TestStringQueries, cls).add_test_dimensions() cls.TestMatrix.add_dimension( create_exec_option_dimension(disable_codegen_options=[True])) cls.TestMatrix.add_constraint(lambda v:\ v.get_value('table_format').file_format in ['text']) def test_varchar(self, vector): self.run_test_case('QueryTest/chars', vector)
Fix bug with article titles
UrlsApp.factory('webhoseFactory', ['$resource', function($resource) { self = {}; self.webhoseSuggestions = function(topicKeyword, newsSource) { var webhoseResource = $resource("https://webhose.io/search?token=b68bbb9d-dd4d-4179-95c1-d60a3cdbd303&format=json&q=" + topicKeyword + "%20site%3A"+ newsSource + ".co.uk"); return webhoseResource.get(); }; self.getUrlLinks = function(webhoseData) { return webhoseData.map(function(article) { return article.url; }); }; self.getArticleImages = function(webhoseData) { return webhoseData.map(function(article) { return article.thread.main_image; }); }; self.getArticleTitles = function(webhoseData) { return webhoseData.map(function(article) { return article.thread.title; }); }; return self; }]);
UrlsApp.factory('webhoseFactory', ['$resource', function($resource) { self = {}; self.webhoseSuggestions = function(topicKeyword, newsSource) { var webhoseResource = $resource("https://webhose.io/search?token=b68bbb9d-dd4d-4179-95c1-d60a3cdbd303&format=json&q=" + topicKeyword + "%20site%3A"+ newsSource + ".co.uk"); return webhoseResource.get(); }; self.getUrlLinks = function(webhoseData) { return webhoseData.map(function(article) { return article.url; }); }; self.getArticleImages = function(webhoseData) { return webhoseData.map(function(article) { return article.thread.main_image; }); }; self.getArticleTitles = function(webhoseData) { return webhoseData.map(function(article) { return article.title; }); }; return self; }]);
Move from github.com/mailgun/... to github.com/vulcand/... for dependencies.
package route import ( "fmt" "github.com/vulcand/predicate" ) // IsValid checks whether expression is valid func IsValid(expr string) bool { _, err := parse(expr, &match{}) return err == nil } func parse(expression string, result *match) (matcher, error) { p, err := predicate.NewParser(predicate.Def{ Functions: map[string]interface{}{ "Host": hostTrieMatcher, "HostRegexp": hostRegexpMatcher, "Path": pathTrieMatcher, "PathRegexp": pathRegexpMatcher, "Method": methodTrieMatcher, "MethodRegexp": methodRegexpMatcher, "Header": headerTrieMatcher, "HeaderRegexp": headerRegexpMatcher, }, Operators: predicate.Operators{ AND: newAndMatcher, }, }) if err != nil { return nil, err } out, err := p.Parse(expression) if err != nil { return nil, err } m, ok := out.(matcher) if !ok { return nil, fmt.Errorf("unknown result type: %T", out) } m.setMatch(result) return m, nil }
package route import ( "fmt" "github.com/mailgun/predicate" ) // IsValid checks whether expression is valid func IsValid(expr string) bool { _, err := parse(expr, &match{}) return err == nil } func parse(expression string, result *match) (matcher, error) { p, err := predicate.NewParser(predicate.Def{ Functions: map[string]interface{}{ "Host": hostTrieMatcher, "HostRegexp": hostRegexpMatcher, "Path": pathTrieMatcher, "PathRegexp": pathRegexpMatcher, "Method": methodTrieMatcher, "MethodRegexp": methodRegexpMatcher, "Header": headerTrieMatcher, "HeaderRegexp": headerRegexpMatcher, }, Operators: predicate.Operators{ AND: newAndMatcher, }, }) if err != nil { return nil, err } out, err := p.Parse(expression) if err != nil { return nil, err } m, ok := out.(matcher) if !ok { return nil, fmt.Errorf("unknown result type: %T", out) } m.setMatch(result) return m, nil }
Exit on EventInterrupt rather on hardcoded Ctrl+C
package main import "github.com/nsf/termbox-go" import "time" import "flag" func main() { loops := flag.Int("loops", 0, "number of times to loop (default: infinite)") delay := flag.Int("delay", 75, "frame delay in ms") orientation := flag.String("orientation", "regular", "regular or aussie") flag.Parse() err := termbox.Init() if err != nil { panic(err) } defer termbox.Close() event_queue := make(chan termbox.Event) go func() { for { event_queue <- termbox.PollEvent() } }() termbox.SetOutputMode(termbox.Output256) loop_index := 0 draw(*orientation) loop: for { select { case ev := <-event_queue: if (ev.Type == termbox.EventKey && ev.Key == termbox.KeyEsc) || ev.Type == termbox.EventInterrupt { break loop } default: loop_index++ if *loops > 0 && (loop_index/9) >= *loops { break loop } draw(*orientation) time.Sleep(time.Duration(*delay) * time.Millisecond) } } }
package main import "github.com/nsf/termbox-go" import "time" import "flag" func main() { loops := flag.Int("loops", 0, "number of times to loop (default: infinite)") delay := flag.Int("delay", 75, "frame delay in ms") orientation := flag.String("orientation", "regular", "regular or aussie") flag.Parse() err := termbox.Init() if err != nil { panic(err) } defer termbox.Close() event_queue := make(chan termbox.Event) go func() { for { event_queue <- termbox.PollEvent() } }() termbox.SetOutputMode(termbox.Output256) loop_index := 0 draw(*orientation) loop: for { select { case ev := <-event_queue: if ev.Type == termbox.EventKey && (ev.Key == termbox.KeyEsc || ev.Key == termbox.KeyCtrlC) { break loop } default: loop_index++ if *loops > 0 && (loop_index/9) >= *loops { break loop } draw(*orientation) time.Sleep(time.Duration(*delay) * time.Millisecond) } } }
Remove eslint config file from grunt task. No need for that.
"use strict"; module.exports = function (grunt) { grunt.initConfig({ eslint: { src: [ "Gruntfile.js", "index.js", "lib/**/*.js", "test/**/*-test.js", "examples/**/*.js" ] }, vows: { all: { src: "test/*.js", options: { reporter: "spec", error: false } } } }); grunt.loadNpmTasks("grunt-eslint"); grunt.loadNpmTasks("grunt-vows-runner"); grunt.registerTask("default", [ "eslint", "vows" ]); };
"use strict"; module.exports = function (grunt) { grunt.initConfig({ eslint: { options: { config: ".eslintrc" }, src: [ "Gruntfile.js", "index.js", "lib/**/*.js", "test/**/*-test.js", "examples/**/*.js" ] }, vows: { all: { src: "test/*.js", options: { reporter: "spec", error: false } } } }); grunt.loadNpmTasks("grunt-eslint"); grunt.loadNpmTasks("grunt-vows-runner"); grunt.registerTask("default", [ "eslint", "vows" ]); };
Make Android build script output to be Gradle compatible
// @flow const path = require('path'); const child_process = require('child_process'); const exec = (command, options) => child_process.execSync(command, { stdio: 'inherit', ...options, }); const hotelPath = path.join(__dirname, '..', 'app', 'hotels'); const buildPath = path.join(__dirname, '..', '.build'); const getBuildCommand = (platform, outputDest, assetDest) => { return `yarn react-native bundle --dev=false --verbose --platform=${platform} --entry-file=${hotelPath}/index.js --bundle-output=${outputDest}/hotels.${platform}.jsbundle --assets-dest ${assetDest}`; }; // Delete old build files. exec(`rm -rf ${buildPath}/ios && rm -rf ${buildPath}/android`); // Build JS bundles for iOS and Android and generate static assets. exec( `mkdir -pv ${buildPath}/ios && mkdir -pv ${buildPath}/android/assets && mkdir -pv ${buildPath}/android/res`, ); exec(getBuildCommand('ios', `${buildPath}/ios`, `${buildPath}/ios`)); exec( getBuildCommand( 'android', `${buildPath}/android/assets`, `${buildPath}/android/res`, ), ); // Copy additional static assets. exec('cp -Rv assets/fonts .build/ios/assets/fonts'); exec('cp -Rv assets/fonts .build/android/assets/fonts'); // Publish on NPM. exec('npm login'); exec('npm version patch', { cwd: buildPath, }); exec('npm publish --access=public', { cwd: buildPath, });
// @flow const path = require('path'); const child_process = require('child_process'); const exec = (command, options) => child_process.execSync(command, { stdio: 'inherit', ...options, }); const hotelPath = path.join(__dirname, '..', 'app', 'hotels'); const buildPath = path.join(__dirname, '..', '.build'); const getBuildCommand = platform => { return `yarn react-native bundle --dev=false --verbose --platform=${platform} --entry-file=${hotelPath}/index.js --bundle-output=${buildPath}/${platform}/hotels.${platform}.jsbundle --assets-dest ${buildPath}/${platform}`; }; // Build JS bundles for iOS and Android and generate static assets. exec(`mkdir -pv ${buildPath}/ios && mkdir -pv ${buildPath}/android`); exec(getBuildCommand('ios')); exec(getBuildCommand('android')); // Copy additional static assets. exec('cp -Rv assets/fonts .build/ios/assets/fonts'); exec('cp -Rv assets/fonts .build/android/fonts'); // Publish on NPM. exec('npm login'); exec('npm version patch', { cwd: buildPath, }); exec('npm publish --access=public', { cwd: buildPath, });
Update query param for mixin
""" Class Mixins. """ from django.db import IntegrityError from django.http import Http404 class MultipleIDMixin(object): """ Override get_queryset for multiple id support """ def get_queryset(self): """ Override :meth:``get_queryset`` """ if hasattr(self.request, 'query_params') and 'filter[id]' in self.request.query_params: query_param_ids = self.request.query_params.get('filter[id]') ids = [] if not query_param_ids else query_param_ids.split(',') try: self.queryset = self.queryset.filter(pk__in=ids) except (ValueError, IntegrityError): raise Http404 return self.queryset
""" Class Mixins. """ from django.db import IntegrityError from django.http import Http404 class MultipleIDMixin(object): """ Override get_queryset for multiple id support """ def get_queryset(self): """ Override :meth:``get_queryset`` """ if hasattr(self.request, 'query_params') and 'ids' in self.request.query_params: query_param_ids = self.request.query_params.get('ids') ids = [] if not query_param_ids else query_param_ids.split(',') try: self.queryset = self.queryset.filter(pk__in=ids) except (ValueError, IntegrityError): raise Http404 return self.queryset
Put pw reset expiration date in future
from datetime import datetime, timedelta from app import db, bcrypt from app.utils.misc import make_code def expiration_date(): return datetime.now() + timedelta(days=1) class User(db.Model): id = db.Column(db.Integer(), primary_key=True) email = db.Column(db.String(255), unique=True) password = db.Column(db.String(255)) active = db.Column(db.Boolean()) is_admin = db.Column(db.Boolean()) def __init__(self, email, password, is_admin=False): self.email = email self.active = True self.is_admin = is_admin self.set_password(password) def set_password(self, password): self.password = bcrypt.generate_password_hash(password) def deactivate(self): self.active = False class PasswordReset(db.Model): id = db.Column(db.Integer(), primary_key=True) user_id = db.Column(db.Integer(), db.ForeignKey('user.id')) code = db.Column(db.String(255), unique=True, default=make_code) date = db.Column(db.DateTime(), default=expiration_date) user = db.relationship(User) db.UniqueConstraint('user', 'code', name='uni_user_code') def __init__(self, user): self.user = user
from datetime import datetime from app import db, bcrypt from app.utils.misc import make_code class User(db.Model): id = db.Column(db.Integer(), primary_key=True) email = db.Column(db.String(255), unique=True) password = db.Column(db.String(255)) active = db.Column(db.Boolean()) is_admin = db.Column(db.Boolean()) def __init__(self, email, password, is_admin=False): self.email = email self.active = True self.is_admin = is_admin self.set_password(password) def set_password(self, password): self.password = bcrypt.generate_password_hash(password) def deactivate(self): self.active = False class PasswordReset(db.Model): id = db.Column(db.Integer(), primary_key=True) user_id = db.Column(db.Integer(), db.ForeignKey('user.id')) code = db.Column(db.String(255), unique=True, default=make_code) date = db.Column(db.DateTime(), default=datetime.now) user = db.relationship(User) db.UniqueConstraint('user', 'code', name='uni_user_code') def __init__(self, user): self.user = user
Correct case on module require
'use strict'; const passport = require('passport'); const userRepository = require('./userRepository'); const localStrategy = require('./LocalStrategy'); const bearerStrategy = require('./BearerStrategy'); const accessTokenStrategy = require('./AccessTokenStrategy'); function initPassport() { passport.serializeUser((user, done) => { done(null, user.username); }); passport.deserializeUser((id, done) => { userRepository.findUser(id, (err, user) => { done(err, user); }); }); passport.use('local', localStrategy); passport.use(bearerStrategy); passport.use('accessToken', accessTokenStrategy); } const auth = { initialize: function (app) { initPassport(); app.use(passport.initialize()); app.use(passport.session()); }, getAuthenticationHandler: function (authenticationRedirects) { return passport.authenticate('local', authenticationRedirects); }, getBearerHandler: function () { return passport.authenticate(['bearer', 'accessToken'], { session: false }); } }; module.exports = auth;
'use strict'; const passport = require('passport'); const userRepository = require('./userRepository'); const localStrategy = require('./LocalStrategy'); const bearerStrategy = require('./BearerStrategy'); const accessTokenStrategy = require('./accessTokenStrategy'); function initPassport() { passport.serializeUser((user, done) => { done(null, user.username); }); passport.deserializeUser((id, done) => { userRepository.findUser(id, (err, user) => { done(err, user); }); }); passport.use('local', localStrategy); passport.use(bearerStrategy); passport.use('accessToken', accessTokenStrategy); } const auth = { initialize: function (app) { initPassport(); app.use(passport.initialize()); app.use(passport.session()); }, getAuthenticationHandler: function (authenticationRedirects) { return passport.authenticate('local', authenticationRedirects); }, getBearerHandler: function () { return passport.authenticate(['bearer', 'accessToken'], { session: false }); } }; module.exports = auth;
Fix AwaitExpression all field default value
require("./core"); var types = require("../lib/types"); var def = types.Type.def; var or = types.Type.or; var builtin = types.builtInTypes; var isBoolean = builtin.boolean; var defaults = require("../lib/shared").defaults; def("Function") .field("async", isBoolean, defaults["false"]); def("SpreadProperty") .bases("Node") .build("argument") .field("argument", def("Expression")); def("ObjectExpression") .field("properties", [or(def("Property"), def("SpreadProperty"))]); def("SpreadPropertyPattern") .bases("Pattern") .build("argument") .field("argument", def("Pattern")); def("ObjectPattern") .field("properties", [or( def("PropertyPattern"), def("SpreadPropertyPattern") )]); def("AwaitExpression") .bases("Expression") .build("argument", "all") .field("argument", or(def("Expression"), null)) .field("all", isBoolean, defaults["false"]);
require("./core"); var types = require("../lib/types"); var def = types.Type.def; var or = types.Type.or; var builtin = types.builtInTypes; var isBoolean = builtin.boolean; var defaults = require("../lib/shared").defaults; def("Function") .field("async", isBoolean, defaults["false"]); def("SpreadProperty") .bases("Node") .build("argument") .field("argument", def("Expression")); def("ObjectExpression") .field("properties", [or(def("Property"), def("SpreadProperty"))]); def("SpreadPropertyPattern") .bases("Pattern") .build("argument") .field("argument", def("Pattern")); def("ObjectPattern") .field("properties", [or( def("PropertyPattern"), def("SpreadPropertyPattern") )]); def("AwaitExpression") .bases("Expression") .build("argument", "all") .field("argument", or(def("Expression"), null)) .field("all", isBoolean, false);
Make environ context helper test more accurate
""" Tests for our tests helpers 8-} """ import os import sys from helpers import ArgvContext, EnvironContext def test_argv_context(): """ Test if ArgvContext sets the right argvs and resets to the old correctly """ old = sys.argv new = ["Alice", "Bob", "Chris", "Daisy"] assert sys.argv == old with ArgvContext(*new): assert sys.argv == new, \ "sys.argv wasn't correctly changed by the contextmanager" assert sys.argv == old, "sys.argv wasn't correctly reset" def test_environ_context(): """ Test if EnvironContext sets the right environ values and resets to the old values correctly """ old = os.environ new = {'PATH': None, 'FOO': 'my foo value'} assert os.environ == old assert os.environ.get('PATH'), "Invalid test setup" assert not os.environ.get('FOO'), "Invalid test setup" with EnvironContext(**new): assert not os.environ.get('PATH'), \ "os.environ[PATH] wasn't removed by the contextmanager" assert os.environ['FOO'] == new['FOO'], \ "os.environ[FOO] wasn't set by the contextmanager" assert os.environ == old, "os.environ wasn't correctly reset"
""" Tests for our tests helpers 8-} """ import os import sys from helpers import ArgvContext, EnvironContext def test_argv_context(): """ Test if ArgvContext sets the right argvs and resets to the old correctly """ old = sys.argv new = ["Alice", "Bob", "Chris", "Daisy"] assert sys.argv == old with ArgvContext(*new): assert sys.argv == new, \ "sys.argv wasn't correctly changed by the contextmanager" assert sys.argv == old, "sys.argv wasn't correctly reset" def test_environ_context(): """ Test if EnvironContext sets the right environ values and resets to the old values correctly """ old = os.environ new = {'FOO': 'my foo value', 'PATH': None} assert os.environ == old assert not os.environ.get('FOO'), "Invalid test setup" assert not os.environ.get('BAR'), "Invalid test setup" with EnvironContext(**new): assert os.environ['FOO'] == new['FOO'], \ "os.environ[FOO] wasn't set by the contextmanager" assert not os.environ.get('PATH'), \ "os.environ[PATH] wasn't removed by the contextmanager" assert os.environ == old, "os.environ wasn't correctly reset"
Add legit-o-meter header to cat on start page
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import Button from '../Shared/Button'; import legitCatImage from '../../images/legit-cat.png'; class Start extends Component { render() { const bodyStyles = { marginBottom: '50px' } const headerStyles = { position: 'absolute', top: '120px', left: '60%' } const divStyles = { position: 'relative' } return ( <div className="text-center" style={divStyles}> <div style={bodyStyles}> <h1 style={headerStyles}>Legit-o-Meter</h1> <img src={legitCatImage} alt="Legit Cat Welcomes You" /> <h1>You'll evaluate 3 different articles and figure out which ones are legit.</h1> <p>We'll ask you questins to help you determine the answer.</p> </div> <Link to="/article/1"> <Button text="Let's Get Started" /> </Link> </div> ); } } export default Start;
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import Button from '../Shared/Button'; import legitCatImage from '../../images/legit-cat.png'; class Start extends Component { render() { const bodyStyles = { marginBottom: "50px" } return ( <div className="text-center"> <div style={bodyStyles}> <img src={legitCatImage} alt="Legit Cat Welcomes You" /> <h1>You'll evaluate 3 different articles and figure out which ones are legit.</h1> <p>We'll ask you questins to help you determine the answer.</p> </div> <Link to="/article/1"> <Button text="Let's Get Started" /> </Link> </div> ); } } export default Start;
Use super() and self within the Cipher and Caesar classes
import math import secrets from string import ascii_lowercase class Cipher(object): def __init__(self, key=None): if not key: key = self._random_key() if not key.isalpha() or not key.islower(): raise ValueError("Key must consist only of lowercase letters") self.key = key self._key = [ord(k)-97 for k in key] def encode(self, s): key = self._key * math.ceil(len(s)/len(self._key)) chars = [c for c in s.lower() if c in ascii_lowercase] return "".join(self._shift(c, k) for c, k in zip(chars, key)) def decode(self, s): key = self._key * math.ceil(len(s)/len(self._key)) chars = [c for c in s.lower() if c in ascii_lowercase] return "".join(self._shift(c, -k) for c, k in zip(chars, key)) @staticmethod def _shift(char, key): return chr(97 + ((ord(char) - 97 + key) % 26)) @staticmethod def _random_key(length=256): return "".join(secrets.choice(ascii_lowercase) for _ in range(length)) class Caesar(Cipher): def __init__(self): super().__init__("d")
import math import secrets from string import ascii_lowercase class Cipher(object): def __init__(self, key=None): if not key: key = Cipher._random_key() if not key.isalpha() or not key.islower(): raise ValueError("Key must consist only of lowercase letters") self.key = key self._key = [ord(k)-97 for k in key] def encode(self, s): key = self._key * math.ceil(len(s)/len(self._key)) chars = [c for c in s.lower() if c in ascii_lowercase] return "".join(Cipher._shift(c, k) for c, k in zip(chars, key)) def decode(self, s): key = self._key * math.ceil(len(s)/len(self._key)) chars = [c for c in s.lower() if c in ascii_lowercase] return "".join(Cipher._shift(c, -k) for c, k in zip(chars, key)) @staticmethod def _shift(char, key): return chr(97 + ((ord(char) - 97 + key) % 26)) @staticmethod def _random_key(length=256): return "".join(secrets.choice(ascii_lowercase) for _ in range(length)) class Caesar(Cipher): def __init__(self): Cipher.__init__(self, "d")
Add header id extension for github preferences
import re from bs4 import BeautifulSoup from django import template from django.template.defaultfilters import stringfilter from markdown import markdown as md from markdown.extensions.headerid import HeaderIdExtension register = template.Library() @stringfilter @register.filter(is_safe=True) def text2md(value): ''' convert markdown-like text to html. strip header <p> and footer </p> if p is True. ''' returns = md(value, ['markdown.extensions.extra', HeaderIdExtension(level=4)]) returns = BeautifulSoup(returns, 'html5lib').prettify(encoding="utf8") return returns.decode('utf8') @register.filter(is_safe=True) @stringfilter def line2md(value, p=True): returns = BeautifulSoup(value, 'html5lib').get_text() returns = re.sub("^([*+-]) ", r"\\\1 ", returns) returns = md(returns, ['markdown.extensions.extra']) if p: returns = returns[3:-4] return returns
import re from bs4 import BeautifulSoup from django import template from django.template.defaultfilters import stringfilter from markdown import markdown as md register = template.Library() @stringfilter @register.filter(is_safe=True) def text2md(value): ''' convert markdown-like text to html. strip header <p> and footer </p> if p is True. ''' returns = md(value, ['markdown.extensions.extra']) returns = BeautifulSoup(returns, 'html5lib').prettify(encoding="utf8") return returns.decode('utf8') @register.filter(is_safe=True) @stringfilter def line2md(value, p=True): returns = BeautifulSoup(value, 'html5lib').get_text() returns = re.sub("^([*+-]) ", r"\\\1 ", returns) returns = md(returns, ['markdown.extensions.extra']) if p: returns = returns[3:-4] return returns
Handle version string sent to stderr An unfortunate side effect of switching from print to output() is that all output() goes to stderr. We should probably carefully consider whether this is the right thing to do.
#!/usr/bin/python from subprocess import check_output as co from sys import exit # Actually run bin/mn rather than importing via python path version = 'Mininet ' + co( 'PYTHONPATH=. bin/mn --version 2>&1', shell=True ) version = version.strip() # Find all Mininet path references lines = co( "egrep -or 'Mininet [0-9\.\+]+\w*' *", shell=True ) error = False for line in lines.split( '\n' ): if line and 'Binary' not in line: fname, fversion = line.split( ':' ) if version != fversion: print( "%s: incorrect version '%s' (should be '%s')" % ( fname, fversion, version ) ) error = True if error: exit( 1 )
#!/usr/bin/python from subprocess import check_output as co from sys import exit # Actually run bin/mn rather than importing via python path version = 'Mininet ' + co( 'PYTHONPATH=. bin/mn --version', shell=True ) version = version.strip() # Find all Mininet path references lines = co( "egrep -or 'Mininet [0-9\.\+]+\w*' *", shell=True ) error = False for line in lines.split( '\n' ): if line and 'Binary' not in line: fname, fversion = line.split( ':' ) if version != fversion: print( "%s: incorrect version '%s' (should be '%s')" % ( fname, fversion, version ) ) error = True if error: exit( 1 )
Update from wherever 0.0.3 came from
var _dataModule = require('data-module'); var gutil = require('gulp-util'); var stream = require('through2').obj; var DataModuleError = gutil.PluginError.bind(null, 'gulp-data-module'); var dataModule = function dataModule (options) { 'use strict'; if (!options) options = {}; var parsing = options.parsing || JSON.parse; var dataModuleOptions = {}; if (typeof options.formatting == 'function') { dataModuleOptions.formatting = options.formatting; } return stream(function dataModuleStream (file, encoding, done) { var source; if (file.isBuffer()) { source = parsing(file.contents.toString()); file.contents = _dataModule ( source , dataModuleOptions ).toBuffer(); file.path = gutil.replaceExtension('.js'); } else if (file.isStream()) return done(new DataModuleError ( 'Streams not supported' )); this.push(file); return done(); }); }; dataModule.formatting = _dataModule.formatting; module.exports = dataModule;
var originalDataModule = require('data-module'); var gutil = require('gulp-util'); var through2 = require('through2'); var DataModuleError = gutil.PluginError.bind(null, 'gulp-data-module'); var dataModule = function dataModule (options) { 'use strict'; if (!options) options = {}; var parsing = options.parsing || JSON.parse; var dataModuleOptions = {}; if (typeof options.formatting == 'function') { dataModuleOptions.formatting = options.formatting; } return through2.obj(function dataModuleStream (file, encoding, done) { var source; if (file.isBuffer()) { source = parsing(file.contents.toString()); file.contents = originalDataModule ( source , dataModuleOptions ).toBuffer(); file.path = file.path.replace(/(?:\.[^\/\\\.]$|$)/, '.js'); } else if (file.isStream()) return done(new DataModuleError ( 'Streams not supported' )); this.push(file); return done(); }); }; dataModule.formatting = { diffy: dataModule.diffy }; module.exports = dataModule;
Set skipJavaLangImports flag to true
package pl.openrest.generator.commons.type; import java.io.File; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.TypeSpec; public class TypeFileWriter { private final File outputDirectory; private static final Logger LOGGER = LoggerFactory.getLogger(TypeFileWriter.class); public TypeFileWriter(File outputDirectory) { this.outputDirectory = outputDirectory; } public void write(TypeSpec typeSpec, String packageName) { JavaFile file = JavaFile.builder(packageName, typeSpec).skipJavaLangImports(true).build(); try { file.writeTo(outputDirectory); } catch (IOException e) { LOGGER.error(String.format("Error while writing %s", typeSpec.name), e); } } }
package pl.openrest.generator.commons.type; import java.io.File; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.TypeSpec; public class TypeFileWriter { private final File outputDirectory; private static final Logger LOGGER = LoggerFactory.getLogger(TypeFileWriter.class); public TypeFileWriter(File outputDirectory) { this.outputDirectory = outputDirectory; } public void write(TypeSpec typeSpec, String packageName) { JavaFile file = JavaFile.builder(packageName, typeSpec).build(); try { file.writeTo(outputDirectory); } catch (IOException e) { LOGGER.error(String.format("Error while writing %s", typeSpec.name), e); } } }
Update HTML to "rich" in description
<?php namespace SilverStripe\ContentWidget; use SilverStripe\Forms\FieldList; use SilverStripe\Forms\TextField; use SilverStripe\Forms\HTMLEditor\HTMLEditorField; use SilverStripe\Widgets\Model\Widget; /** * Content Widget */ class ContentWidget extends Widget { private static $db = [ "HTML" => "HTMLText", ]; private static $title = "Content"; private static $cmsTitle = "Content"; private static $description = "Custom rich content widget."; private static $table_name = 'ContentWidget'; /** * @return FieldList */ public function getCMSFields() { $fields = parent::getCMSFields(); $fields->push(TextField::create("Title")); $fields->push(HTMLEditorField::create("HTML", "Content")); return $fields; } }
<?php namespace SilverStripe\ContentWidget; use SilverStripe\Forms\FieldList; use SilverStripe\Forms\TextField; use SilverStripe\Forms\HTMLEditor\HTMLEditorField; use SilverStripe\Widgets\Model\Widget; /** * Content Widget */ class ContentWidget extends Widget { private static $db = [ "HTML" => "HTMLText", ]; private static $title = "Content"; private static $cmsTitle = "Content"; private static $description = "Custom HTML content widget."; private static $table_name = 'ContentWidget'; /** * @return FieldList */ public function getCMSFields() { $fields = parent::getCMSFields(); $fields->push(TextField::create("Title")); $fields->push(HTMLEditorField::create("HTML", "Content")); return $fields; } }
Fix device activation remove exception.
from moa.base import MoaBase class Device(MoaBase): ''' By default, the device does not support multi-threading. ''' _activated_set = None def __init__(self, **kwargs): super(Device, self).__init__(**kwargs) self._activated_set = set() def activate(self, identifier, **kwargs): active = self._activated_set result = len(active) == 0 active.add(identifier) return result def recover(self, **kwargs): pass def deactivate(self, identifier, clear=False, **kwargs): active = self._activated_set old_len = len(active) if clear: active.clear() else: try: active.remove(identifier) except KeyError: pass return bool(old_len and not len(active))
from moa.base import MoaBase class Device(MoaBase): ''' By default, the device does not support multi-threading. ''' _activated_set = None def __init__(self, **kwargs): super(Device, self).__init__(**kwargs) self._activated_set = set() def activate(self, identifier, **kwargs): active = self._activated_set result = len(active) == 0 active.add(identifier) return result def recover(self, **kwargs): pass def deactivate(self, identifier, clear=False, **kwargs): active = self._activated_set old_len = len(active) if clear: active.clear() else: try: active.remove(identifier) except ValueError: pass return bool(old_len and not len(active))
Fix ndimage complaining about shift being of NoneType
# Perform alignment to the estimated rotation axis # # Developed as part of the tomviz project (www.tomviz.com). def transform_scalars(dataset, SHIFT=None, rotation_angle=90.0): from tomviz import utils from scipy import ndimage import numpy as np data_py = utils.get_array(dataset) # Get data as numpy array. if data_py is None: #Check if data exists raise RuntimeError("No data array found!") if SHIFT is None: SHIFT = np.zeros(len(data_py.shape), dtype=np.int) data_py_return = np.empty_like(data_py) ndimage.interpolation.shift(data_py, SHIFT, order=0, output=data_py_return) rotation_axis = 2 # This operator always assumes the rotation axis is Z if rotation_angle == []: # If tilt angle not given, assign it to 90 degrees. rotation_angle = 90 axis1 = (rotation_axis + 1) % 3 axis2 = (rotation_axis + 2) % 3 axes = (axis1, axis2) shape = utils.rotate_shape(data_py_return, rotation_angle, axes=axes) data_py_return2 = np.empty(shape, data_py_return.dtype, order='F') ndimage.interpolation.rotate( data_py_return, rotation_angle, output=data_py_return2, axes=axes) utils.set_array(dataset, data_py_return2)
# Perform alignment to the estimated rotation axis # # Developed as part of the tomviz project (www.tomviz.com). def transform_scalars(dataset, SHIFT=None, rotation_angle=90.0): from tomviz import utils from scipy import ndimage import numpy as np data_py = utils.get_array(dataset) # Get data as numpy array. if data_py is None: #Check if data exists raise RuntimeError("No data array found!") data_py_return = np.empty_like(data_py) ndimage.interpolation.shift(data_py, SHIFT, order=0, output=data_py_return) rotation_axis = 2 # This operator always assumes the rotation axis is Z if rotation_angle == []: # If tilt angle not given, assign it to 90 degrees. rotation_angle = 90 axis1 = (rotation_axis + 1) % 3 axis2 = (rotation_axis + 2) % 3 axes = (axis1, axis2) shape = utils.rotate_shape(data_py_return, rotation_angle, axes=axes) data_py_return2 = np.empty(shape, data_py_return.dtype, order='F') ndimage.interpolation.rotate( data_py_return, rotation_angle, output=data_py_return2, axes=axes) utils.set_array(dataset, data_py_return2)
Exclude list of taxa as suggested by SPG. git-svn-id: d46fe582d22b46b457d3ac1c55a88da2fbe913a1@1719 baf6b65b-9124-4dc3-b1c0-01155b4af546
<?php /* connector for SPIRE estimated execution time: 10 mins Connector accesses the OWL (XML) files from remote server for most of the data and uses a spreadsheet for taxonomy info. */ include_once(dirname(__FILE__) . "/../../config/environment.php"); require_library('connectors/SpireAPI'); $GLOBALS['ENV_DEBUG'] = false; $timestart = time_elapsed(); $taxa = SpireAPI::get_all_taxa(); $xml = SchemaDocument::get_taxon_xml($taxa); $resource_path = CONTENT_RESOURCE_LOCAL_PATH . "219.xml"; $OUT = fopen($resource_path, "w"); fwrite($OUT, $xml); fclose($OUT); $elapsed_time_sec = time_elapsed() - $timestart; echo "\n"; echo "elapsed time = $elapsed_time_sec sec \n"; echo "elapsed time = " . $elapsed_time_sec/60 . " min \n"; echo "elapsed time = " . $elapsed_time_sec/60/60 . " hr \n"; exit("\n\n Done processing."); ?>
<?php /* connector for SPIRE estimated execution time: 10 mins Connector accesses the OWL (XML) files from remote server for most of the data and uses a spreadsheet for taxonomy info. */ include_once(dirname(__FILE__) . "/../../config/environment.php"); require_library('connectors/SpireAPI'); $GLOBALS['ENV_DEBUG'] = false; $timestart = time_elapsed(); $taxa = SpireAPI::get_all_taxa(); $xml = SchemaDocument::get_taxon_xml($taxa); $resource_path = CONTENT_RESOURCE_LOCAL_PATH . "219.xml"; $OUT = fopen($resource_path, "w"); fwrite($OUT, $xml); fclose($OUT); $elapsed_time_sec = time_elapsed() - $timestart; echo "\n"; echo "elapsed time = $elapsed_time_sec sec \n"; echo "elapsed time = " . $elapsed_time_sec/60 . " min \n"; echo "elapsed time = " . $elapsed_time_sec/60/60 . " hr \n"; exit("\n\n Done processing."); ?>
Revert "Stop FF/tabs stealing focus" This reverts commit 428a4e9dfc389b5fc30278b8bb736d23d4959d9d.
user_pref("browser.backspace_action", 2); user_pref("browser.ctrlTab.previews", true); user_pref("browser.fixup.alternate.enabled", false); user_pref("browser.newtab.url", "https://www.google.com"); user_pref("browser.sessionstore.warnOnQuit", true); user_pref("browser.showQuitWarning", true); user_pref("browser.tabs.tabClipWidth", 1); user_pref("browser.warnOnQuit", true); user_pref("datareporting.healthreport.service.enabled", false); user_pref("datareporting.healthreport.uploadEnabled", false); user_pref("devtools.webconsole.persistlog", true); user_pref("extensions.pocket.enabled", true); user_pref("general.useragent.locale", "en-GB"); user_pref("layout.spellcheckDefault", 2); user_pref("loop.enabled", false); user_pref("media.block-autoplay-until-in-foreground", true); user_pref("network.IDN_show_punycode", true); user_pref("plugins.click_to_play", true); user_pref("privacy.userContext.enabled", true); user_pref("privacy.userContext.ui.enabled", true); user_pref("security.webauth.u2f", true); user_pref("spellchecker.dictionary", "en-GB"); user_pref("toolkit.legacyUserProfileCustomizations.stylesheets", true); user_pref("toolkit.telemetry.enabled", false);
user_pref("browser.backspace_action", 2); user_pref("browser.ctrlTab.previews", true); user_pref("browser.fixup.alternate.enabled", false); user_pref("browser.newtab.url", "https://www.google.com"); user_pref("browser.sessionstore.warnOnQuit", true); user_pref("browser.showQuitWarning", true); user_pref("browser.tabs.loadDivertedInBackground", true); user_pref("browser.tabs.tabClipWidth", 1); user_pref("browser.warnOnQuit", true); user_pref("datareporting.healthreport.service.enabled", false); user_pref("datareporting.healthreport.uploadEnabled", false); user_pref("devtools.webconsole.persistlog", true); user_pref("extensions.pocket.enabled", true); user_pref("general.useragent.locale", "en-GB"); user_pref("layout.spellcheckDefault", 2); user_pref("loop.enabled", false); user_pref("media.block-autoplay-until-in-foreground", true); user_pref("network.IDN_show_punycode", true); user_pref("plugins.click_to_play", true); user_pref("privacy.userContext.enabled", true); user_pref("privacy.userContext.ui.enabled", true); user_pref("security.webauth.u2f", true); user_pref("spellchecker.dictionary", "en-GB"); user_pref("toolkit.legacyUserProfileCustomizations.stylesheets", true); user_pref("toolkit.telemetry.enabled", false);
Increase the goprofile trace limit to 5M. Signed-off-by: Aditya Dani <5d1852d43efe8f6e393448a3b4d1cd98a4cfd56f@portworx.com>
package dbg import ( "fmt" "io/ioutil" "os" "runtime" "runtime/pprof" "time" "github.com/Sirupsen/logrus" ) const ( path = "/var/cores/" ) // DumpGoMemoryTrace output memory profile to logs. func DumpGoMemoryTrace() { m := &runtime.MemStats{} runtime.ReadMemStats(m) res := fmt.Sprintf("%#v", m) logrus.Infof("==== Dumping Memory Profile ===") logrus.Infof(res) } // DumpGoProfile output goroutines to file. func DumpGoProfile() error { trace := make([]byte, 5120*1024) len := runtime.Stack(trace, true) return ioutil.WriteFile(path+time.Now().String()+".stack", trace[:len], 0644) } func DumpHeap() { f, err := os.Create(path + time.Now().String() + ".heap") if err != nil { logrus.Errorf("could not create memory profile: %v", err) return } defer f.Close() if err := pprof.WriteHeapProfile(f); err != nil { logrus.Errorf("could not write memory profile: %v", err) } }
package dbg import ( "fmt" "io/ioutil" "os" "runtime" "runtime/pprof" "time" "github.com/Sirupsen/logrus" ) const ( path = "/var/cores/" ) // DumpGoMemoryTrace output memory profile to logs. func DumpGoMemoryTrace() { m := &runtime.MemStats{} runtime.ReadMemStats(m) res := fmt.Sprintf("%#v", m) logrus.Infof("==== Dumping Memory Profile ===") logrus.Infof(res) } // DumpGoProfile output goroutines to file. func DumpGoProfile() error { trace := make([]byte, 1024*1024) len := runtime.Stack(trace, true) return ioutil.WriteFile(path+time.Now().String()+".stack", trace[:len], 0644) } func DumpHeap() { f, err := os.Create(path + time.Now().String() + ".heap") if err != nil { logrus.Errorf("could not create memory profile: %v", err) return } defer f.Close() if err := pprof.WriteHeapProfile(f); err != nil { logrus.Errorf("could not write memory profile: %v", err) } }
Fix the number of required arguments. Update the usage message.
package org.linuxguy.MarketBot.samples; import org.linuxguy.MarketBot.Comment; import org.linuxguy.MarketBot.GooglePlayWatcher; import org.linuxguy.MarketBot.Notifier; /** * Sample client implementation * <p/> * This class monitors an app in the Google Play Store and prints new * reviews to the console. */ public class GooglePlayLogger { public static void main(String[] args) throws InterruptedException { if (args.length < 3) { printUsage(); System.exit(-1); } String username = args[0]; String password = args[1]; String app_id = args[2]; GooglePlayWatcher playWatcher = new GooglePlayWatcher(username, password, app_id); playWatcher.addListener(new ConsoleNotifier()); playWatcher.start(); playWatcher.join(); } private static class ConsoleNotifier extends Notifier<Comment> { @Override public void onNewResult(Comment result) { System.out.println("Response : " + result); } } private static void printUsage() { System.out.println(String.format("Usage: <user> <password> <app package name>", GooglePlayLogger.class.getName())); } }
package org.linuxguy.MarketBot.samples; import org.linuxguy.MarketBot.Comment; import org.linuxguy.MarketBot.GooglePlayWatcher; import org.linuxguy.MarketBot.Notifier; /** * Sample client implementation * <p/> * This class monitors an app in the Google Play Store and prints new * reviews to the console. */ public class GooglePlayLogger { public static void main(String[] args) throws InterruptedException { if (args.length < 4) { printUsage(); System.exit(-1); } String username = args[0]; String password = args[1]; String app_id = args[2]; GooglePlayWatcher playWatcher = new GooglePlayWatcher(username, password, app_id); playWatcher.addListener(new ConsoleNotifier()); playWatcher.start(); playWatcher.join(); } private static class ConsoleNotifier extends Notifier<Comment> { @Override public void onNewResult(Comment result) { System.out.println("Response : " + result); } } private static void printUsage() { System.out.println(String.format("Usage: %s <user> <password> <app package name>", GooglePlayLogger.class.getName())); } }
Add new target blank for external link
<footer class="footer"> <div class="container-fluid"> <nav class="pull-left"> <ul> <li> <a href="<?=Core::$basepath;?>"> Home </a> </li> </ul> </nav> <div class="copyright pull-right"> &copy; <script>document.write(new Date().getFullYear())</script>, template made with<i class="fa fa-heart heart"></i> by <a href="http://www.creative-tim.com" target="_blank">Creative Tim</a> </div> </div> </footer>
<footer class="footer"> <div class="container-fluid"> <nav class="pull-left"> <ul> <li> <a href="<?=Core::$basepath;?>"> Home </a> </li> </ul> </nav> <div class="copyright pull-right"> &copy; <script>document.write(new Date().getFullYear())</script>, template made with<i class="fa fa-heart heart"></i> by <a href="http://www.creative-tim.com">Creative Tim</a> </div> </div> </footer>
Update groupBy test case description.
QUnit.test("groupBy() 0:2 1:3 0:4", function(assert) { var result = Canal.of([ 2, 3, 4 ]) // .groupBy(function(d) { return d % 2; }).collect(); assert.propEqual(result, [ [ "0", [ 2, 4 ] ], [ "1", [ 3 ] ] ]); }); QUnit.test("groupBy() 0:1", function(assert) { var result = Canal.of([ 1 ]) // .groupBy(function(d) { return d - 1; }, function(d) { return d + 1; }).collect(); assert.propEqual(result, [ [ "0", [ 2 ] ] ]); }); QUnit.test("groupBy() empty", function(assert) { var result = Canal.of([]) // .groupBy().collect(); assert.propEqual(result, []); });
QUnit.test("groupBy() 1:1 0:2 1:3", function(assert) { var result = Canal.of([ 2, 3, 4 ]) // .groupBy(function(d) { return d % 2; }).collect(); assert.propEqual(result, [ [ "0", [ 2, 4 ] ], [ "1", [ 3 ] ] ]); }); QUnit.test("groupBy() 0:1", function(assert) { var result = Canal.of([ 1 ]) // .groupBy(function(d) { return d - 1; }, function(d) { return d + 1; }).collect(); assert.propEqual(result, [ [ "0", [ 2 ] ] ]); }); QUnit.test("groupBy() empty", function(assert) { var result = Canal.of([]) // .groupBy().collect(); assert.propEqual(result, []); });
Switch lambda_utils to CalVer, bump the version
import os from setuptools import find_packages, setup def local_file(name): return os.path.relpath(os.path.join(os.path.dirname(__file__), name)) SOURCE = local_file('src') setup( name='wellcome_lambda_utils', packages=find_packages(SOURCE), package_dir={'': SOURCE}, version='2017.10.20', install_requires=[ 'attrs>=17.2.0', 'boto3', 'daiquiri>=1.3.0', 'python-dateutil', 'requests>=2.18.4', ], python_requires='>=3.6', description='Common lib for lambdas', author='Wellcome digital platform', author_email='wellcomedigitalplatform@wellcome.ac.uk', url='https://github.com/wellcometrust/platform', keywords=['lambda', 'utils'], classifiers=[], )
import os from setuptools import find_packages, setup def local_file(name): return os.path.relpath(os.path.join(os.path.dirname(__file__), name)) SOURCE = local_file('src') setup( name='wellcome_lambda_utils', packages=find_packages(SOURCE), package_dir={'': SOURCE}, version='1.0.6', install_requires=[ 'attrs>=17.2.0', 'boto3', 'daiquiri>=1.3.0', 'python-dateutil', 'requests>=2.18.4', ], python_requires='>=3.6', description='Common lib for lambdas', author='Wellcome digital platform', author_email='wellcomedigitalplatform@wellcome.ac.uk', url='https://github.com/wellcometrust/platform', keywords=['lambda', 'utils'], classifiers=[], )
Fix wrong Content-Type header in /file/min/
package controllers; import play.db.jpa.JPA; import play.db.jpa.Transactional; import play.mvc.Result; import java.io.IOException; import static play.mvc.Results.ok; public class File { @Transactional public Result get(Long id) { models.FileMeta fileMeta = JPA.em().find(models.FileMeta.class, id); java.io.File file = models.FileManager.getFile(fileMeta); return ok(file).as(fileMeta.getMimeType()); } @Transactional public Result getPreview(Long id) throws IOException { models.FileMeta fileMeta = JPA.em().find(models.FileMeta.class, id); java.io.File file = models.FileManager.getThumbnail(fileMeta); return ok(file); } }
package controllers; import play.db.jpa.JPA; import play.db.jpa.Transactional; import play.mvc.Result; import java.io.IOException; import static play.mvc.Results.ok; public class File { @Transactional public Result get(Long id) { models.FileMeta fileMeta = JPA.em().find(models.FileMeta.class, id); java.io.File file = models.FileManager.getFile(fileMeta); return ok(file).as(fileMeta.getMimeType()); } @Transactional public Result getPreview(Long id) throws IOException { models.FileMeta fileMeta = JPA.em().find(models.FileMeta.class, id); java.io.File file = models.FileManager.getThumbnail(fileMeta); return ok(file).as(fileMeta.getMimeType()); } }
Adjust unittesting config for CI
from os.path import abspath, dirname, join import json if __name__ == '__main__': file = abspath(join(dirname(__file__), '..', 'unittesting.json')) with open(file, 'w') as fp: config = { "deferred": True, "verbosity": 0, "capture_console": True, "failfast": True, "reload_package_on_testing": False, "start_coverage_after_reload": False, "show_reload_progress": False, "output": None, "generate_html_report": False } json.dump(config, fp, indent=4)
from os.path import abspath, dirname, join import json if __name__ == '__main__': file = abspath(join(dirname(__file__), '..', 'unittesting.json')) with open(file, 'w') as fp: config = { "deferred": True, "verbosity": 2, "capture_console": False, "failfast": False, "reload_package_on_testing": False, "start_coverage_after_reload": False, "show_reload_progress": False, "output": None, "generate_html_report": False } json.dump(config, fp, indent=4)
Remove form request type definition from form class (it's form by default anyways). Do not overwrite element submit method.
/* --- script: Form.js description: Act as a form to submit data license: Public domain (http://unlicense.org). requires: - LSD.Trait - LSD.Mixin.Request provides: - LSD.Trait.Form ... */ LSD.Trait.Form = new Class({ options: { pseudos: Array.fast('submittable') }, initialize: function() { this.addEvents({ nodeInserted: function(node) { if (node.pseudos['read-write'] || node.pseudos['form-associated']) node.form = this; } }); this.parent.apply(this, arguments); if (!this.getAttribute('action')) this.setAttribute('action', location.pathname); }, submit: function(event) { this.fireEvent('submit', arguments); if (event && event.type == 'submit') { event.preventDefault(); return this.callChain(); } else return this.send.apply(this, arguments); } });
/* --- script: Form.js description: Act as a form to submit data license: Public domain (http://unlicense.org). requires: - LSD.Trait - LSD.Mixin.Request provides: - LSD.Trait.Form ... */ LSD.Trait.Form = new Class({ options: { request: { type: 'form' }, pseudos: Array.fast('submittable') }, initialize: function() { this.addEvents({ nodeInserted: function(node) { if (node.pseudos['read-write'] || node.pseudos['form-associated']) node.form = this; }, build: function() { this.element.submit = this.submit.bind(this); } }); this.parent.apply(this, arguments); if (!this.getAttribute('action')) this.setAttribute('action', location.pathname); }, submit: function(event) { this.fireEvent('submit', arguments); if (event && event.type == 'submit') { event.preventDefault(); return this.callChain(); } else return this.send.apply(this, arguments); } });
Test exclude equality with sets
# -*- coding: utf-8 -*- """ Tests for the barebones example project """ import os import py.path from tarbell.app import EXCLUDES, TarbellSite PATH = os.path.realpath('examples/barebones') def test_get_site(): site = TarbellSite(PATH) assert os.path.realpath(site.path) == os.path.realpath(PATH) assert site.project.name == "barebones" def test_default_excludes(): "Ensure a basic set of excluded files" site = TarbellSite(PATH) assert set(site.project.EXCLUDES) == set(EXCLUDES) def test_generate_site(tmpdir): "Generate a static site matching what's in _site" site = TarbellSite(PATH) built = os.path.join(PATH, '_site') site.generate_static_site(str(tmpdir)) files = set(f.basename for f in tmpdir.listdir()) assert files == set(['data.json', 'index.html'])
# -*- coding: utf-8 -*- """ Tests for the barebones example project """ import os import py.path from tarbell.app import EXCLUDES, TarbellSite PATH = os.path.realpath('examples/barebones') def test_get_site(): site = TarbellSite(PATH) assert os.path.realpath(site.path) == os.path.realpath(PATH) assert site.project.name == "barebones" def test_default_excludes(): "Ensure a basic set of excluded files" site = TarbellSite(PATH) assert site.project.EXCLUDES == EXCLUDES def test_generate_site(tmpdir): "Generate a static site matching what's in _site" site = TarbellSite(PATH) built = os.path.join(PATH, '_site') site.generate_static_site(str(tmpdir)) files = set(f.basename for f in tmpdir.listdir()) assert files == set(['data.json', 'index.html'])
Use release channel of ember-data v1.13 is not supported for the next version of ember-data-fixture-adapter.
module.exports = { scenarios: [ { name: 'default', dependencies: { } }, { name: 'ember-release', dependencies: { 'ember': 'components/ember#release', 'ember-data': 'components/ember-data#release' }, resolutions: { 'ember': 'release', 'ember-data': 'release' } }, { name: 'ember-beta', dependencies: { 'ember': 'components/ember#beta', 'ember-data': 'components/ember-data#canary' }, resolutions: { 'ember': 'beta', 'ember-data': 'canary' } }, { name: 'ember-canary', dependencies: { 'ember': 'components/ember#canary', 'ember-data': 'components/ember-data#canary' }, resolutions: { 'ember': 'canary', 'ember-data': 'canary' } } ] };
module.exports = { scenarios: [ { name: 'default', dependencies: { } }, { name: 'ember-release', dependencies: { 'ember': 'components/ember#release', 'ember-data': 'components/ember-data#1.13.4' }, resolutions: { 'ember': 'release', 'ember-data': '1.13.4' } }, { name: 'ember-beta', dependencies: { 'ember': 'components/ember#beta', 'ember-data': 'components/ember-data#canary' }, resolutions: { 'ember': 'beta', 'ember-data': 'canary' } }, { name: 'ember-canary', dependencies: { 'ember': 'components/ember#canary', 'ember-data': 'components/ember-data#canary' }, resolutions: { 'ember': 'canary', 'ember-data': 'canary' } } ] };
Fix bug introduced by switching to minimist
'use strict' var co = require('co') var cli = require('./cli') var utils = require('./utils') var reporter = require('./reporter') var notifier = require('update-notifier') var pkg = require('../package') co(function * () { // check if using latest notifier({pkg: pkg}).notify() // get command options var opts = cli.options() var tasks = opts._ if (tasks.length == 0) tasks = [ 'default' ] if (opts.help) { cli.help() } else if (opts.version) { cli.version(pkg) } else { var fly = yield cli.spawn(opts.file) if (opts.list) { cli.list(fly.host, {bare: opts.list === 'bare'}) } else { return reporter.call(fly) .emit('fly_run', {path: fly.file}) .start(tasks) } } }).catch(function (e) { if (e.code === 'ENOENT') { utils.error('No Flyfile? See the Quickstart guide → git.io/fly-quick') } else if (e.code === 'UNKNOWN_OPTION') { utils.error('Unknown Flag: -' + e.key + '. Run fly -h to see available options.') } else { utils.trace(e) } }) // export Fly module.exports = require('./fly')
'use strict' var co = require('co') var cli = require('./cli') var utils = require('./utils') var reporter = require('./reporter') var notifier = require('update-notifier') var pkg = require('../package') co(function * () { // check if using latest notifier({pkg: pkg}).notify() // get command options var opts = cli.options() if (opts.help) { cli.help() } else if (opts.version) { cli.version(pkg) } else { var fly = yield cli.spawn(opts.file) if (opts.list) { cli.list(fly.host, {bare: opts.list === 'bare'}) } else { return reporter.call(fly) .emit('fly_run', {path: fly.file}) .start(opts.tasks) } } }).catch(function (e) { if (e.code === 'ENOENT') { utils.error('No Flyfile? See the Quickstart guide → git.io/fly-quick') } else if (e.code === 'UNKNOWN_OPTION') { utils.error('Unknown Flag: -' + e.key + '. Run fly -h to see available options.') } else { utils.trace(e) } }) // export Fly module.exports = require('./fly')
Add Nexus Siege game mode
/* * Copyright 2014 Taylor Caldwell * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rithms.riot.constant; public enum GameMode { ARAM("ARAM"), ASCENSION("Ascension"), CLASSIC("Classic"), FIRSTBLOOD("Snowdown Showdown"), KINGPORO("King Poro"), ODIN("Dominion/Crystal Scar"), ONEFORALL("One for All"), SIEGE("Nexus Siege"), TUTORIAL("Tutorial"); private String name; GameMode(String name) { this.name = name; } public String getName() { return name; } @Override public String toString() { return getName(); } }
/* * Copyright 2014 Taylor Caldwell * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rithms.riot.constant; public enum GameMode { ARAM("ARAM"), ASCENSION("Ascension"), CLASSIC("Classic"), FIRSTBLOOD("Snowdown Showdown"), KINGPORO("King Poro"), ODIN("Dominion/Crystal Scar"), ONEFORALL("One for All"), TUTORIAL("Tutorial"); private String name; GameMode(String name) { this.name = name; } public String getName() { return name; } @Override public String toString() { return getName(); } }
Sort punctuation hits so output is based on line and column, not the order rules are checked
#!/usr/bin/python3 import operator import wlint.common import wlint.punctuation class PunctuationStyle(wlint.common.Tool): def __init__(self, description): super().__init__(description) self.checks = wlint.punctuation.PunctuationRules().rules def setup(self, arguments): self.result = 0 def process(self, fileHandle): lineNumber = 0 hits = [] for text in fileHandle: lineNumber += 1 for message, fn in self.checks.items(): if fn(text, lambda pos: hits.append(lineNumber, pos, message)): self.result = 1 hits.sort() for (line, col, message) in hits: print("{}-{}:{} {}".format(fileHandle.name, line, pos, message)) punctuationStyle = PunctuationStyle("Check for common punctuation issues") punctuationStyle.execute() exit(punctuationStyle.result)
#!/usr/bin/python3 import re import wlint.common import wlint.punctuation class PunctuationStyle(wlint.common.Tool): def __init__(self, description): super().__init__(description) self.checks = wlint.punctuation.PunctuationRules().rules def setup(self, arguments): self.result = 0 def process(self, fileHandle): lineNumber = 0 for text in fileHandle: lineNumber += 1 for message, fn in self.checks.items(): if fn(text, lambda pos: print( "{}-{}:{} {}".format(fileHandle.name, lineNumber, pos, message))): self.result = 1 punctuationStyle = PunctuationStyle("Check for common punctuation issues") punctuationStyle.execute() exit(punctuationStyle.result)
Upgrade to 1.0.0 (switch to semantic versioning)
from setuptools import setup setup( name='playlistfromsong', packages=['playlistfromsong'], version='1.0.0', description='An offline music station generator', author='schollz', url='https://github.com/schollz/playlistfromsong', author_email='hypercube.platforms@gmail.com', download_url='https://github.com/schollz/playlistfromsong/archive/v1.0.0.tar.gz', keywords=['music', 'youtube', 'playlist'], classifiers=[], install_requires=[ "requests", "youtube_dl", 'appdirs', 'pyyaml', 'beautifulsoup4', ], setup_requires=['pytest-runner'], tests_require=[ 'pytest-flake8', 'pytest', 'pytest-cov' ], entry_points={'console_scripts': [ 'playlistfromsong = playlistfromsong.__main__:main', ], }, )
from setuptools import setup setup( name='playlistfromsong', packages=['playlistfromsong'], version='0.22', description='An offline music station generator', author='schollz', url='https://github.com/schollz/playlistfromsong', author_email='hypercube.platforms@gmail.com', download_url='https://github.com/schollz/playlistfromsong/archive/v0.22.tar.gz', keywords=['music', 'youtube', 'playlist'], classifiers=[], install_requires=[ "requests", "youtube_dl", 'appdirs', 'pyyaml', 'beautifulsoup4', ], setup_requires=['pytest-runner'], tests_require=[ 'pytest-flake8', 'pytest', 'pytest-cov' ], entry_points={'console_scripts': [ 'playlistfromsong = playlistfromsong.__main__:main', ], }, )
Add spaces to an if statement
package org.robockets.stronghold.robot.commands; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.networktables.NetworkTable; /** * */ public class MeasureLatency extends Command { NetworkTable table; double starttime; int i = 0; public MeasureLatency() { } protected void initialize() { table = NetworkTable.getTable("vision"); starttime = System.nanoTime(); } protected void execute() { if (table.getNumber("heartbeat", 0) == 1) { System.out.println("i," + (System.nanoTime() - starttime)); starttime = System.nanoTime(); table.putNumber("heartbeat", 0); } } protected boolean isFinished() { return false; } protected void end() { } protected void interrupted() { } }
package org.robockets.stronghold.robot.commands; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.networktables.NetworkTable; /** * */ public class MeasureLatency extends Command { NetworkTable table; double starttime; int i = 0; public MeasureLatency() { } protected void initialize() { table = NetworkTable.getTable("vision"); starttime = System.nanoTime(); } protected void execute() { if(table.getNumber("heartbeat", 0)==1){ System.out.println("i," + (System.nanoTime() - starttime)); starttime = System.nanoTime(); table.putNumber("heartbeat", 0); } } protected boolean isFinished() { return false; } protected void end() { } protected void interrupted() { } }
Use `map` instead of `reduce`
const fs = require("fs") const glob = require("glob") const path = require("path") const reactDocs = require("react-docgen") const {toCode} = require("./utils") module.exports = function () { const callback = this.async() const resource = this.request.split("!").pop() const directory = path.dirname(resource) glob(`${directory}/**/*[^.test].jsx`, (err, files) => { if (err) { return callback(err) } const docs = files.map((file) => { const contents = fs.readFileSync(file, {encoding: "utf8"}) const componentInfo = reactDocs.parse(contents) componentInfo.path = file componentInfo.module = `require('${file}')` return componentInfo }) return callback(null, `module.exports = ${toCode(docs)}`) }) }
const fs = require("fs") const glob = require("glob") const path = require("path") const reactDocs = require("react-docgen") const {toCode} = require("./utils") module.exports = function () { const callback = this.async() const resource = this.request.split("!").pop() const directory = path.dirname(resource) glob(`${directory}/**/*[^.test].jsx`, (err, files) => { if (err) { return callback(err) } const docs = files.reduce((acc, file) => { const contents = fs.readFileSync(file, {encoding: "utf8"}) const componentInfo = reactDocs.parse(contents) componentInfo.path = file componentInfo.module = `require('${file}')` acc.push(componentInfo) return acc }, []) return callback(null, `module.exports = ${toCode(docs)}`) }) }
Add test field password with required rule
<?php namespace Styde\Html\Tests; use Styde\Html\FormModel\Field; use Styde\Html\FormModel\FieldCollection; class FieldCollectionTest extends TestCase { /** @test */ function it_adds_a_field() { $fields = new FieldCollection(field()); $fields->add('first_name', 'text'); $this->assertInstanceOf(Field::class, $fields->first_name); } /** @test */ function it_renders_fields() { $fields = new FieldCollection(field()); $fields->add('name')->label('Full name'); $fields->add('role', 'select')->options(['admin' => 'Admin' , 'user' => 'User']); $this->assertTemplateMatches('field-collection/fields', $fields->render()); } /** @test */ function it_render_field_password_with_required_rule() { $fields = new FieldCollection(field()); $fields->password('password')->required(); $this->assertTemplateMatches('field-collection/fields', $fields->render()); } }
<?php namespace Styde\Html\Tests; use Styde\Html\FormModel\Field; use Styde\Html\FormModel\FieldCollection; class FieldCollectionTest extends TestCase { /** @test */ function it_adds_a_field() { $fields = new FieldCollection(field()); $fields->add('first_name', 'text'); $this->assertInstanceOf(Field::class, $fields->first_name); } /** @test */ function it_renders_fields() { $fields = new FieldCollection(field()); $fields->add('name')->label('Full name'); $fields->add('role', 'select')->options(['admin' => 'Admin' , 'user' => 'User']); $this->assertTemplateMatches('field-collection/fields', $fields->render()); } }
Add get_serializer_class to document model
from django.db import models from filingcabinet.models import ( AbstractDocument, AbstractDocumentCollection, ) class Document(AbstractDocument): original = models.ForeignKey( 'foirequest.FoiAttachment', null=True, blank=True, on_delete=models.SET_NULL, related_name='original_document' ) foirequest = models.ForeignKey( 'foirequest.FoiRequest', null=True, blank=True, on_delete=models.SET_NULL ) publicbody = models.ForeignKey( 'publicbody.PublicBody', null=True, blank=True, on_delete=models.SET_NULL ) def is_public(self): return self.public def get_serializer_class(self, detail=False): from .api_views import DocumentSerializer, DocumentDetailSerializer if detail: return DocumentDetailSerializer return DocumentSerializer class DocumentCollection(AbstractDocumentCollection): pass
from django.db import models from filingcabinet.models import ( AbstractDocument, AbstractDocumentCollection, ) class Document(AbstractDocument): original = models.ForeignKey( 'foirequest.FoiAttachment', null=True, blank=True, on_delete=models.SET_NULL, related_name='original_document' ) foirequest = models.ForeignKey( 'foirequest.FoiRequest', null=True, blank=True, on_delete=models.SET_NULL ) publicbody = models.ForeignKey( 'publicbody.PublicBody', null=True, blank=True, on_delete=models.SET_NULL ) def is_public(self): return self.public class DocumentCollection(AbstractDocumentCollection): pass
Add a argument and fix a error.
# coding: utf-8 import oslo_i18n def reset_i18n(domain="app", localedir=None, lazy=True): global _translators, _, _C, _P, _LI, _LW, _LE, _LC # Enable lazy translation if lazy: oslo_i18n.enable_lazy() _translators = oslo_i18n.TranslatorFactory(domain=domain, localedir=localedir) # The primary translation function using the well-known name "_" _ = _translators.primary # The contextual translation function using the name "_C" _C = _translators.contextual_form # The plural translation function using the name "_P" _P = _translators.plural_form # Translators for log levels. # # The abbreviated names are meant to reflect the usual use of a short # name like '_'. The "L" is for "log" and the other letter comes from # the level. _LI = _translators.log_info _LW = _translators.log_warning _LE = _translators.log_error _LC = _translators.log_critical _translators = _ = _C = _P = _LI = _LW = _LE = _LC = None reset_i18n()
# coding: utf-8 import oslo_i18n def reset_i18n(domain="app", localedir=None): global _translators, _, _C, _P, _LI, _LW, _LE, _LC # Enable lazy translation oslo_i18n.enable_lazy() _translators = oslo_i18n.TranslatorFactory(domain=domain, localedir=localedir) # The primary translation function using the well-known name "_" _ = _translators.primary # The contextual translation function using the name "_C" _C = _translators.contextual_form # The plural translation function using the name "_P" _P = _translators.plural_form # Translators for log levels. # # The abbreviated names are meant to reflect the usual use of a short # name like '_'. The "L" is for "log" and the other letter comes from # the level. _LI = _translators.log_info _LW = _translators.log_warning _LE = _translators.log_error _LC = _translators.log_critical _translators, _, _C, _P, _LI, _LW, _LE, _LC = None reset_i18n()
[LEETCODE] Add Two Numbers - go - check if the leftmost int exists
package _go /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { p := new(ListNode) dump := p l1_val, l2_val, c, sum := 0, 0, 0, 0 for l1 != nil || l2 != nil { if l1 != nil { l1_val = l1.Val l1 = l1.Next } if l2 != nil { l2_val = l2.Val l2 = l2.Next } sum = l1_val + l2_val + c p.Next = new(ListNode) p = p.Next p.Val, c = sum % 10, sum / 10 l1_val, l2_val = 0, 0 } if c == 1 { p.Next = &ListNode{1, nil} } return dump.Next } func max(x, y int) int { if x > y { return x } return y }
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { p := new(ListNode) dump := p l1_val, l2_val, c, sum := 0, 0, 0, 0 for l1 != nil || l2 != nil { if l1 != nil { l1_val = l1.Val l1 = l1.Next } if l2 != nil { l2_val = l2.Val l2 = l2.Next } sum = l1_val + l2_val + c p.Next = new(ListNode) p = p.Next p.Val, c = sum % 10, sum / 10 l1_val, l2_val = 0, 0 } return dump.Next }
Remove hack for sqpyte again Related: https://github.com/HPI-SWA-Lab/SQPyte/commit/1afdff01b989352e3d72ca7f2cc9c837471642c7
#! /usr/bin/env python import sys, os """ RSqueak Build Options (separated with `--` from RPython options) Example: .build/build.py -Ojit -- --64bit --64bit - Compile for 64bit platform --plugins database_plugin[,another_plugin] - Comma-separated list of optional plugins (e.g. DatabasePlugin) """ if __name__ == "__main__": if not any(arg.startswith("-") for arg in sys.argv): sys.argv.append("--batch") target = os.path.join(os.path.dirname(__file__), "..", "targetrsqueak.py") if '--' in sys.argv: sys.argv[sys.argv.index('--')] = target else: sys.argv.append(target) import environment from rpython.translator.goal.translate import main main()
#! /usr/bin/env python import sys, os """ RSqueak Build Options (separated with `--` from RPython options) Example: .build/build.py -Ojit -- --64bit --64bit - Compile for 64bit platform --plugins database_plugin[,another_plugin] - Comma-separated list of optional plugins (e.g. DatabasePlugin) """ if __name__ == "__main__": sys.argv[0] = 'rpython' # required for sqpyte hacks if not any(arg.startswith("-") for arg in sys.argv): sys.argv.append("--batch") target = os.path.join(os.path.dirname(__file__), "..", "targetrsqueak.py") if '--' in sys.argv: sys.argv[sys.argv.index('--')] = target else: sys.argv.append(target) import environment from rpython.translator.goal.translate import main main()
Fix bug of cleaning test files.
const exec = require('child_process').exec; const inspect = require('util').inspect; const fs = require('fs'); const path = require('path'); const del = require('del'); const mkdirp = require('mkdirp'); const command = 'node'; const inspectOpt = { depth: null }; const readOpt = { encoding: 'utf-8' }; var id = 0; function createTestFunction(templateFile, testDir) { del.sync(path.join(testDir, './test-**.js')); mkdirp(testDir); var templateJs = fs.readFileSync(templateFile, readOpt); return function(testcase, done) { var filepath = createTestFile(templateJs, testDir, testcase, id ++); exec(command + ' ' + filepath, function(err, stdout, stderr) { if (stderr !== '') { throw new Error(stderr); } if (err != null) { throw new Error(err); } done(); }); }; } function createTestFile(template, testDir, testcase, id) { var filePath = path.resolve(testDir, 'test-' + id + '.js'); var regExp = new RegExp('\\${testcase}', 'g'); var jsSrc = template.replace(regExp, inspect(testcase, inspectOpt)); fs.writeFileSync(filePath, jsSrc); return filePath; } module.exports = createTestFunction;
const exec = require('child_process').exec; const inspect = require('util').inspect; const fs = require('fs'); const path = require('path'); const del = require('del'); const mkdirp = require('mkdirp'); const command = 'node'; const inspectOpt = { depth: null }; const readOpt = { encoding: 'utf-8' }; var id = 0; function createTestFunction(templateFile, testDir) { del.sync(path.join(testDir + './test-**.js')); mkdirp(testDir); var templateJs = fs.readFileSync(templateFile, readOpt); return function(testcase, done) { var filepath = createTestFile(templateJs, testDir, testcase, id ++); exec(command + ' ' + filepath, function(err, stdout, stderr) { if (stderr !== '') { throw new Error(stderr); } if (err != null) { throw new Error(err); } done(); }); }; } function createTestFile(template, testDir, testcase, id) { var filePath = path.resolve(testDir, 'test-' + id + '.js'); var regExp = new RegExp('\\${testcase}', 'g'); var jsSrc = template.replace(regExp, inspect(testcase, inspectOpt)); fs.writeFileSync(filePath, jsSrc); return filePath; } module.exports = createTestFunction;
Set key type for resolver git-svn-id: 46308aa6df3a13aea5930e6665b35c8b83c3a711@276 9fbd0cf9-a10c-0410-82c1-be8c084f3200
/* * Copyright [2006] [University Corporation for Advanced Internet Development, Inc.] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opensaml.xml.encryption; import java.security.KeyException; import java.security.PublicKey; import org.opensaml.xml.security.KeyInfoResolver; /** * Resolves encrypted keys based on EncryptedData information or other external factors. */ public interface EncryptedKeyInfoResolver extends KeyInfoResolver<PublicKey> { /** * Returns an encrypted key based on a particular EncryptedData context. * * @param encryptedData the EncryptedData context in which to look for EncryptedKey * @return the resolved EncryptedKey element * @throws KeyException thrown if there is a problem resolving a key */ public EncryptedKey resolveKey(EncryptedData encryptedData) throws KeyException; }
/* * Copyright [2006] [University Corporation for Advanced Internet Development, Inc.] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opensaml.xml.encryption; import java.security.KeyException; import org.opensaml.xml.security.KeyInfoResolver; /** * Resolves encrypted keys based on EncryptedData information or other external factors. */ public interface EncryptedKeyInfoResolver extends KeyInfoResolver { /** * Returns an encrypted key based on a particular EncryptedData context. * * @param encryptedData the EncryptedData context in which to look for EncryptedKey * @return the resolved EncryptedKey element * @throws KeyException thrown if there is a problem resolving a key */ public EncryptedKey resolveKey(EncryptedData encryptedData) throws KeyException; }
Correct issue number in documentation
package test.issues.strava; import static org.junit.Assert.assertNull; import javastrava.api.v3.model.StravaSegmentEffort; import javastrava.api.v3.service.exception.NotFoundException; import javastrava.api.v3.service.impl.retrofit.Retrofit; import javastrava.api.v3.service.impl.retrofit.SegmentEffortServicesRetrofit; import org.junit.Test; import test.utils.TestUtils; /** * <p> * These tests should PASS if issue <a href="https://github.com/danshannon/javastravav3api/issues/27">javastrava-api #27</a> still exists * </p> * * @author Dan Shannon * @see <a href="https://github.com/danshannon/javastravav3api/issues/27">https://github.com/danshannon/javastravav3api/issues/27</a> * */ public class Issue27 { @Test public void testIssue() throws NotFoundException { SegmentEffortServicesRetrofit retrofit = Retrofit.retrofit(SegmentEffortServicesRetrofit.class, TestUtils.getValidToken()); StravaSegmentEffort effort = retrofit.getSegmentEffort(5591276015L); assertNull(effort.getAthlete().getResourceState()); } }
package test.issues.strava; import static org.junit.Assert.assertNull; import javastrava.api.v3.model.StravaSegmentEffort; import javastrava.api.v3.service.exception.NotFoundException; import javastrava.api.v3.service.impl.retrofit.Retrofit; import javastrava.api.v3.service.impl.retrofit.SegmentEffortServicesRetrofit; import org.junit.Test; import test.utils.TestUtils; /** * <p> * These tests should PASS if issue <a href="https://github.com/danshannon/javastravav3api/issues/32">javastrava-api #32</a> still exists * </p> * * @author Dan Shannon * @see <a href="https://github.com/danshannon/javastravav3api/issues/32">https://github.com/danshannon/javastravav3api/issues/32</a> * */ public class Issue27 { @Test public void testIssue() throws NotFoundException { SegmentEffortServicesRetrofit retrofit = Retrofit.retrofit(SegmentEffortServicesRetrofit.class, TestUtils.getValidToken()); StravaSegmentEffort effort = retrofit.getSegmentEffort(5591276015L); assertNull(effort.getAthlete().getResourceState()); } }
Add used storage account name in container info When calling e.g 'container list' you get all container names but you don't know from which storage account name was used One would need to look at the config file to check which storage account name was configured which could be avoided by just adding this information to the output
""" usage: azure-cli container list azure-cli container content <name> commands: list list available containers content list content of given container """ # project from cli_task import CliTask from storage_account import StorageAccount from data_collector import DataCollector from logger import Logger from exceptions import * from container import Container class ContainerTask(CliTask): def process(self): self.account = StorageAccount(self.account_name, self.config_file) self.container = Container(self.account) if self.command_args['list']: self.__list() elif self.command_args['content']: self.__content() else: raise AzureUnknownContainerCommand(self.command_args) def __list(self): result = DataCollector() result.add( 'containers:' + self.account.get_name(), self.container.list() ) Logger.info(result.get()) def __content(self): result = DataCollector() result.add( 'container_content:' + self.account.get_name(), self.container.content(self.command_args['<name>']) ) Logger.info(result.get())
""" usage: azure-cli container list azure-cli container content <name> commands: list list available containers content list content of given container """ # project from cli_task import CliTask from storage_account import StorageAccount from data_collector import DataCollector from logger import Logger from exceptions import * from container import Container class ContainerTask(CliTask): def process(self): account = StorageAccount(self.account_name, self.config_file) self.container = Container(account) if self.command_args['list']: self.__list() elif self.command_args['content']: self.__content() else: raise AzureUnknownContainerCommand(self.command_args) def __list(self): result = DataCollector() result.add('containers', self.container.list()) Logger.info(result.get()) def __content(self): result = DataCollector() result.add('container_content', self.container.content( self.command_args['<name>']) ) Logger.info(result.get())
Allow for callables in getIntProperty() Some tags can now implicitly be functions, as long as they are called through getIntProperty(). The function will take the current value as input, and will output the result of a calculation. This matters for Gahz'rilla and Blessed Champion where the attack up to the point of the buff is doubled. Thanks, Xinhuan
import logging from .enums import Zone class Entity(object): def __init__(self): self.tags = {} # Register the events self._registerEvents() def _registerEvents(self): self._eventListeners = {} for name in self.events: func = getattr(self, name, None) if func: self._eventListeners[name] = [func] def broadcast(self, event, *args): for entity in self.entities: for f in entity._eventListeners.get(event, []): if getattr(f, "zone", Zone.PLAY) == Zone.PLAY: f(*args) if event != "UPDATE": self.broadcast("UPDATE") def setTag(self, tag, value): logging.debug("%r::%r %r -> %r" % (self, tag, self.tags.get(tag, None), value)) self.tags[tag] = value def unsetTag(self, tag): del self.tags[tag] def getIntProperty(self, tag): ret = self.tags.get(tag, 0) for slot in self.slots: _ret = slot.getIntProperty(tag) if isinstance(_ret, int): ret += _ret else: ret = _ret(ret) return ret def getBoolProperty(self, tag): if self.tags.get(tag, False): return True for slot in self.slots: if slot.getBoolProperty(tag): return True return
import logging from .enums import Zone class Entity(object): def __init__(self): self.tags = {} # Register the events self._registerEvents() def _registerEvents(self): self._eventListeners = {} for name in self.events: func = getattr(self, name, None) if func: self._eventListeners[name] = [func] def broadcast(self, event, *args): for entity in self.entities: for f in entity._eventListeners.get(event, []): if getattr(f, "zone", Zone.PLAY) == Zone.PLAY: f(*args) if event != "UPDATE": self.broadcast("UPDATE") def setTag(self, tag, value): logging.debug("%r::%r %r -> %r" % (self, tag, self.tags.get(tag, None), value)) self.tags[tag] = value def unsetTag(self, tag): del self.tags[tag] def getIntProperty(self, tag): ret = self.tags.get(tag, 0) for slot in self.slots: ret += slot.getIntProperty(tag) return ret def getBoolProperty(self, tag): if self.tags.get(tag, False): return True for slot in self.slots: if slot.getBoolProperty(tag): return True return
Add javadoc to planned activity dao. git-svn-id: 4b387fe5ada7764508e2ca96c335714e4c1692c6@2431 0d517254-b314-0410-acde-c619094fa49f
package edu.northwestern.bioinformatics.studycalendar.dao; import edu.northwestern.bioinformatics.studycalendar.domain.PlannedActivity; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * @author Rhett Sutphin */ @Transactional (readOnly=true) public class PlannedActivityDao extends StudyCalendarMutableDomainObjectDao<PlannedActivity> { @Override public Class<PlannedActivity> domainClass() { return PlannedActivity.class; } /** * Deletes a planned activity * * @param event the planned activity to delete */ @Transactional(readOnly=false) public void delete(PlannedActivity event) { getHibernateTemplate().delete(event); } /** * Finds all planned activities for a activity id * * @param activityId the activity id to search with * @return a list of planned activities with the activity id passed in */ public List<PlannedActivity> getPlannedActivitiesForAcivity(Integer activityId) { return (List<PlannedActivity>) getHibernateTemplate().find("select pa from PlannedActivity as pa where pa.activity.id=?",activityId); } }
package edu.northwestern.bioinformatics.studycalendar.dao; import edu.northwestern.bioinformatics.studycalendar.domain.PlannedActivity; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * @author Rhett Sutphin */ @Transactional (readOnly=true) public class PlannedActivityDao extends StudyCalendarMutableDomainObjectDao<PlannedActivity> { @Override public Class<PlannedActivity> domainClass() { return PlannedActivity.class; } @Transactional(readOnly=false) public void delete(PlannedActivity event) { getHibernateTemplate().delete(event); } public List<PlannedActivity> getPlannedActivitiesForAcivity(Integer activityId) { return (List<PlannedActivity>) getHibernateTemplate().find("select pa from PlannedActivity as pa where pa.activity.id=?",activityId); } }
Move the proxy route handlers to onAfterAction so that the template gets rendered properly (instead of showing a brown/white blank page)
Router.route('/',{ template: 'nucleus' }); Router.route('/login-with-github', { template: 'nucleus', onAfterAction: function() { var subdomain = this.params.query.subdomain, serverLoginUrl = subdomain + '/nucleus-github-login' ; if (!subdomain) throw new Meteor.Error('"subdomain" query parameter required'); $.cookie('nucleus-github-auth-domain', subdomain); window.location.href = serverLoginUrl; } }); Router.route('/github-auth', { name: 'github-auth', template: 'nucleus', onAfterAction: function() { if (this.params.query.subdomain) { this.redirect('/login-with-github?subdomain='+this.params.query.subdomain); } var queryString = window.location.href.split('?')[1], subdomain = $.cookie('nucleus-github-auth-domain'), callbackUri = subdomain + '/nucleus-github-callback?' + queryString ; $.cookie('nucleus-github-auth-domain', null); //let's reset this cookie window.location.href = callbackUri; } });
Router.route('/',{ template: 'nucleus' }); Router.route('/login-with-github', { template: 'nucleus', action: function() { var subdomain = this.params.query.subdomain, serverLoginUrl = subdomain + '/nucleus-github-login' ; if (!subdomain) throw new Meteor.Error('"subdomain" query parameter required'); $.cookie('nucleus-github-auth-domain', subdomain); window.location.href = serverLoginUrl; } }); Router.route('/github-auth', { name: 'github-auth', template: 'nucleus', action: function() { if (this.params.query.subdomain) { this.redirect('/login-with-github?subdomain='+this.params.query.subdomain); } var queryString = window.location.href.split('?')[1], subdomain = $.cookie('nucleus-github-auth-domain'), callbackUri = subdomain + '/nucleus-github-callback?' + queryString ; $.cookie('nucleus-github-auth-domain', null); //let's reset this cookie window.location.href = callbackUri; } });
Add version 2.6.7 of py-setuptools
from spack import * class PySetuptools(Package): """Easily download, build, install, upgrade, and uninstall Python packages.""" homepage = "https://pypi.python.org/pypi/setuptools" url = "https://pypi.python.org/packages/source/s/setuptools/setuptools-11.3.tar.gz" version('11.3.1', '01f69212e019a2420c1693fb43593930') version('16.0', '0ace0b96233516fc5f7c857d086aa3ad') version('18.1', 'f72e87f34fbf07f299f6cb46256a0b06') version('19.2', '78353b1f80375ca5e088f4b4627ffe03') version('20.5', 'fadc1e1123ddbe31006e5e43e927362b') version('20.6.7', '45d6110f3ec14924e44c33411db64fe6') extends('python') def install(self, spec, prefix): python('setup.py', 'install', '--prefix=%s' % prefix)
from spack import * class PySetuptools(Package): """Easily download, build, install, upgrade, and uninstall Python packages.""" homepage = "https://pypi.python.org/pypi/setuptools" url = "https://pypi.python.org/packages/source/s/setuptools/setuptools-11.3.tar.gz" version('11.3.1', '01f69212e019a2420c1693fb43593930') version('16.0', '0ace0b96233516fc5f7c857d086aa3ad') version('18.1', 'f72e87f34fbf07f299f6cb46256a0b06') version('19.2', '78353b1f80375ca5e088f4b4627ffe03') version('20.5', 'fadc1e1123ddbe31006e5e43e927362b') extends('python') def install(self, spec, prefix): python('setup.py', 'install', '--prefix=%s' % prefix)
Improve code for annotation mock
package tools.devnull.trugger; import tools.devnull.trugger.reflection.Reflection; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.List; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * @author Marcelo Guimarães */ public class AnnotationMock { public static <T extends Annotation> T mockAnnotation(Class<T> annotationType) { T annotation = mock(annotationType); when(annotation.annotationType()).then(invocation -> annotationType); List<Method> methods = Reflection.reflect().methods() .filter(method -> method.getDefaultValue() != null) .in(annotationType); // maps the methods with default value methods.forEach(method -> when(Reflection.invoke(method).in(annotation).withoutArgs()) .thenReturn(method.getDefaultValue())); return annotation; } }
package tools.devnull.trugger; import org.mockito.stubbing.Answer; import tools.devnull.trugger.reflection.Reflection; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.List; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * @author Marcelo Guimarães */ public class AnnotationMock { private static final Answer returnType(Class annotationType) { return (i) -> annotationType; } public static <T extends Annotation> T mockAnnotation(Class<T> annotationType) { T annotation = mock(annotationType); when(annotation.annotationType()).then(returnType(annotationType)); List<Method> methods = Reflection.reflect().methods() .filter(method -> method.getDefaultValue() != null) .in(annotationType); // maps the methods with default value for (Method method : methods) { when(Reflection.invoke(method).in(annotation).withoutArgs()) .thenReturn(method.getDefaultValue()); } return annotation; } }
Update menu accelerators for cross platform compatibility. Simple update to be able to use the development menu accelerators on Windows and Linux and to remove the accelerator warnings on these platforms: [584:0617/135533:WARNING:accelerator_util.cc(185)] Invalid accelerator token: command [584:0617/135533:WARNING:accelerator_util.cc(185)] Invalid accelerator token: command [584:0617/135533:WARNING:accelerator_util.cc(185)] Invalid accelerator token: command
'use strict'; var app = require('app'); var Menu = require('menu'); var BrowserWindow = require('browser-window'); module.exports.setDevMenu = function () { var devMenu = Menu.buildFromTemplate([{ label: 'Development', submenu: [{ label: 'Reload', accelerator: 'CmdOrCtrl+R', click: function () { BrowserWindow.getFocusedWindow().reloadIgnoringCache(); } },{ label: 'Toggle DevTools', accelerator: 'Alt+CmdOrCtrl+I', click: function () { BrowserWindow.getFocusedWindow().toggleDevTools(); } },{ label: 'Quit', accelerator: 'CmdOrCtrl+Q', click: function () { app.quit(); } }] }]); Menu.setApplicationMenu(devMenu); };
'use strict'; var app = require('app'); var Menu = require('menu'); var BrowserWindow = require('browser-window'); module.exports.setDevMenu = function () { var devMenu = Menu.buildFromTemplate([{ label: 'Development', submenu: [{ label: 'Reload', accelerator: 'Command+R', click: function () { BrowserWindow.getFocusedWindow().reloadIgnoringCache(); } },{ label: 'Toggle DevTools', accelerator: 'Alt+Command+I', click: function () { BrowserWindow.getFocusedWindow().toggleDevTools(); } },{ label: 'Quit', accelerator: 'Command+Q', click: function () { app.quit(); } }] }]); Menu.setApplicationMenu(devMenu); };
Add 'build' gulp task and make the 'default' task clean, build and generate sw
var gulp = require('gulp'); var oghliner = require('oghliner'); var fse = require('fs-extra'); gulp.task('default', ['clean', 'build', 'offline']); gulp.task('build', function() { fse.mkdirSync('dist'); fse.copySync('js', 'dist/js'); fse.copySync('node_modules/localforage/dist/localforage.min.js', 'dist/js/localforage.min.js'); fse.copySync('index.html', 'dist/index.html'); fse.copySync('style.css', 'dist/style.css'); }); gulp.task('clean', function() { fse.removeSync('dist'); }); gulp.task('offline', function(callback) { return oghliner.offline({ rootDir: 'dist', fileGlobs: [ 'index.html', 'js/**/*.js', ], importScripts: ['js/sw-push.js'], }); }); gulp.task('deploy', function(callback) { return oghliner.deploy({ rootDir: 'dist', }); });
var gulp = require('gulp'); var oghliner = require('oghliner'); var fse = require('fs-extra'); gulp.task('default', function() { fse.removeSync('dist'); fse.mkdirSync('dist'); fse.copySync('js', 'dist/js'); fse.copySync('node_modules/localforage/dist/localforage.min.js', 'dist/js/localforage.min.js'); fse.copySync('index.html', 'dist/index.html'); fse.copySync('style.css', 'dist/style.css'); }); gulp.task('clean', function() { fse.removeSync('dist'); }); gulp.task('offline', function(callback) { return oghliner.offline({ rootDir: 'dist', fileGlobs: [ 'index.html', 'js/**/*.js', ], importScripts: ['js/sw-push.js'], }); }); gulp.task('deploy', function(callback) { return oghliner.deploy({ rootDir: 'dist', }); });
Fix assertion in JUnit test.
package com.tal.clienttext.junit; import static org.junit.Assert.*; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.IOException; import junit.framework.Assert; import com.tal.socketclient.SocketClient; public class ClientTest { private SocketClient client; @Before public void runBeforeEveryTest() { try { client = new SocketClient("localhost", 8080); } catch (IOException e) { fail("Exception on creating client: " + e.getMessage()); } } @After public void runAfterEveryTest() { client = null; } @Test(timeout = 10000) //10 second timeout as this is a socket operation public void testConnection() { for(int i=0; i<10; i++){ String reply = ""; try { reply = client.getData("GET_DATA"); } catch (IOException e) { fail("Exception when getting data from server: " + e.getMessage()); } //Check that the server returned what we expect Assert.assertEquals("DATA="+i, reply); } } }
package com.tal.clienttext.junit; import static org.junit.Assert.*; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.IOException; import com.tal.socketclient.SocketClient; public class ClientTest { private SocketClient client; @Before public void runBeforeEveryTest() { try { client = new SocketClient("localhost", 8080); } catch (IOException e) { fail("Exception on creating client: " + e.getMessage()); } } @After public void runAfterEveryTest() { client = null; } @Test(timeout = 10000) //10 second timeout as this is a socket operation public void testConnection() { for(int i=0; i<10; i++){ String reply = ""; try { reply = client.getData("GET_DATA"); } catch (IOException e) { fail("Exception when getting data from server: " + e.getMessage()); } //Check that the server returned what we expect assert(reply == "DATA="+i); } } }
Change title of meta transactions page in docs sidebar (cherry picked from commit 773c7265e8725c87a8220c2de111c7e252becc8b)
#!/usr/bin/env node const path = require('path'); const proc = require('child_process'); const startCase = require('lodash.startcase'); const baseDir = process.argv[2]; const files = proc.execFileSync( 'find', [baseDir, '-type', 'f'], { encoding: 'utf8' }, ).split('\n').filter(s => s !== ''); console.log('.API'); function getPageTitle (directory) { if (directory === 'metatx') { return 'Meta Transactions'; } else { return startCase(directory); } } const links = files.map((file) => { const doc = file.replace(baseDir, ''); const title = path.parse(file).name; return { xref: `* xref:${doc}[${getPageTitle(title)}]`, title, }; }); // Case-insensitive sort based on titles (so 'token/ERC20' gets sorted as 'erc20') const sortedLinks = links.sort(function (a, b) { return a.title.toLowerCase().localeCompare(b.title.toLowerCase(), undefined, { numeric: true }); }); for (const link of sortedLinks) { console.log(link.xref); }
#!/usr/bin/env node const path = require('path'); const proc = require('child_process'); const startCase = require('lodash.startcase'); const baseDir = process.argv[2]; const files = proc.execFileSync( 'find', [baseDir, '-type', 'f'], { encoding: 'utf8' }, ).split('\n').filter(s => s !== ''); console.log('.API'); const links = files.map((file) => { const doc = file.replace(baseDir, ''); const title = path.parse(file).name; return { xref: `* xref:${doc}[${startCase(title)}]`, title, }; }); // Case-insensitive sort based on titles (so 'token/ERC20' gets sorted as 'erc20') const sortedLinks = links.sort(function (a, b) { return a.title.toLowerCase().localeCompare(b.title.toLowerCase(), undefined, { numeric: true }); }); for (const link of sortedLinks) { console.log(link.xref); }
Set normalized directory path as parameter.
<?php namespace Orbt\Bundle\ResourceMirrorBundle\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\Config\FileLocator; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader; /** * This is the class that loads and manages your bundle configuration * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ class OrbtResourceMirrorExtension extends Extension { /** * {@inheritDoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); if (!is_dir($config['directory']) || !is_writable($config['directory'])) { throw new InvalidArgumentException('Resource mirror directory must be writable.'); } $container->setParameter('orbt_resource_mirror.base_url', $config['base_url']); $container->setParameter('orbt_resource_mirror.directory', realpath($config['directory'])); $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.xml'); } }
<?php namespace Orbt\Bundle\ResourceMirrorBundle\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\Config\FileLocator; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader; /** * This is the class that loads and manages your bundle configuration * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ class OrbtResourceMirrorExtension extends Extension { /** * {@inheritDoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); if (!is_dir($config['directory']) || !is_writable($config['directory'])) { throw new InvalidArgumentException('Resource mirror directory must be writable.'); } $container->setParameter('orbt_resource_mirror.base_url', $config['base_url']); $container->setParameter('orbt_resource_mirror.directory', $config['directory']); $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.xml'); } }
Allow round_id for submissions to be calculated dynamically
import logging from datetime import datetime import sqlalchemy as sql from sqlalchemy import Table, Column, Integer, String, DateTime, Text, ForeignKey from sqlalchemy import orm from sqlalchemy.ext.declarative import declarative_base import db Base = declarative_base() Base.metadata.bind = db.engine class Round(Base): __tablename__ = 'round' id = Column(Integer, primary_key=True) start_time = Column(DateTime, default=datetime.now) end_time = Column(DateTime, nullable=False) duration_secs = Column(Integer, nullable=False) class Perspective(Base): __tablename__ = 'perspective' id = Column(Integer, primary_key=True) gender = Column(String(6), nullable=False) text = Column(Text, nullable=False) created_at = Column(DateTime, default=datetime.now) submissions = orm.relationship('Submission', backref='perspective', lazy='dynamic') class Submission(Base): __tablename__ = 'submission' id = Column(Integer, primary_key=True) perspective_id = Column(Integer, ForeignKey('perspective.id'), nullable=False) text = Column(Text, nullable=False) likes = Column(Integer, default=0) Base.metadata.create_all() logging.info("Table information loaded")
import logging from datetime import datetime import sqlalchemy as sql from sqlalchemy import Table, Column, Integer, String, DateTime, Text, ForeignKey from sqlalchemy import orm from sqlalchemy.ext.declarative import declarative_base import db Base = declarative_base() Base.metadata.bind = db.engine class Round(Base): __tablename__ = 'round' id = Column(Integer, primary_key=True) start_time = Column(DateTime, default=datetime.now) end_time = Column(DateTime, nullable=False) duration_secs = Column(Integer, nullable=False) submissions = orm.relationship('Submission', backref='round', lazy='dynamic') class Perspective(Base): __tablename__ = 'perspective' id = Column(Integer, primary_key=True) gender = Column(String(6), nullable=False) text = Column(Text, nullable=False) created_at = Column(DateTime, default=datetime.now) submissions = orm.relationship('Submission', backref='perspective', lazy='dynamic') class Submission(Base): __tablename__ = 'submission' id = Column(Integer, primary_key=True) perspective_id = Column(Integer, ForeignKey('perspective.id'), nullable=False) round_id = Column(Integer, ForeignKey('round.id'), nullable=False) text = Column(Text, nullable=False) likes = Column(Integer, default=0) Base.metadata.create_all() logging.info("Table information loaded")
Update for error when plugin fusioninventory not present
<?php /* ---------------------------------------------------------------------- FusionInventory Copyright (C) 2010-2011 by the FusionInventory Development Team. http://www.fusioninventory.org/ http://forge.fusioninventory.org/ ---------------------------------------------------------------------- LICENSE This file is part of FusionInventory. FusionInventory is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or any later version. FusionInventory 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 General Public License for more details. You should have received a copy of the GNU General Public License along with FusionInventory. If not, see <http://www.gnu.org/licenses/>. ------------------------------------------------------------------------ Original Author of file: David DURIEUX Co-authors of file: Purpose of file: ---------------------------------------------------------------------- */ include_once ("hook.php"); // inc files if (file_exists(GLPI_ROOT."/plugins/fusioninventory/inc/communication.class.php")) { foreach (glob(GLPI_ROOT.'/plugins/fusinvsnmp/inc/*.php') as $file) { include_once($file); } } ?>
<?php /* ---------------------------------------------------------------------- FusionInventory Copyright (C) 2010-2011 by the FusionInventory Development Team. http://www.fusioninventory.org/ http://forge.fusioninventory.org/ ---------------------------------------------------------------------- LICENSE This file is part of FusionInventory. FusionInventory is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or any later version. FusionInventory 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 General Public License for more details. You should have received a copy of the GNU General Public License along with FusionInventory. If not, see <http://www.gnu.org/licenses/>. ------------------------------------------------------------------------ Original Author of file: David DURIEUX Co-authors of file: Purpose of file: ---------------------------------------------------------------------- */ include_once ("hook.php"); // inc files foreach (glob(GLPI_ROOT.'/plugins/fusinvsnmp/inc/*.php') as $file) { include_once($file); } ?>
Fix distribution and bump version.
__author__ = 'yalnazov' from setuptools import setup setup( name='paymill-wrapper', version='2.1.0', description='Python wrapper for PAYMILL API', author='Aleksandar Yalnazov', author_email='aleksandar.yalnazov@qaiware.com', url='https://github.com/paymill/paymill-python', license='MIT', packages=['paymill', 'paymill.models', 'paymill.services', 'paymill.utils'], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'License :: OSI Approved :: MIT License', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules', ], install_requires=['requests >= 2.1.0', 'paymill-jsonobject>=0.7.1beta'] )
__author__ = 'yalnazov' from setuptools import setup setup( name='paymill-wrapper', version='2.0.0', description='Python wrapper for PAYMILL API', author='Aleksandar Yalnazov', author_email='aleksandar.yalnazov@qaiware.com', url='https://github.com/paymill/paymill-python', license='MIT', packages=['paymill'], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'License :: OSI Approved :: MIT License', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules', ], install_requires=['requests >= 2.1.0', 'paymill-jsonobject>=0.7.1beta'] )
Change the insert to use updated_at as the reported_at date
""" Revision ID: 0311_populate_returned_letters Revises: 0310_returned_letters_table Create Date: 2019-12-09 12:13:49.432993 """ from alembic import op revision = '0311_populate_returned_letters' down_revision = '0310_returned_letters_table' def upgrade(): conn = op.get_bind() sql = """ select id, service_id, reference, updated_at from notification_history where notification_type = 'letter' and notification_status = 'returned-letter'""" insert_sql = """ insert into returned_letters(id, reported_at, service_id, notification_id, created_at, updated_at) values(uuid_in(md5(random()::text)::cstring), '{}', '{}', '{}', now(), null) """ results = conn.execute(sql) returned_letters = results.fetchall() for x in returned_letters: f = insert_sql.format(x.updated_at.date(), x.service_id, x.id) conn.execute(f) def downgrade(): pass
""" Revision ID: 0311_populate_returned_letters Revises: 0310_returned_letters_table Create Date: 2019-12-09 12:13:49.432993 """ from alembic import op from app.dao.returned_letters_dao import insert_or_update_returned_letters revision = '0311_populate_returned_letters' down_revision = '0310_returned_letters_table' def upgrade(): conn = op.get_bind() sql = """ select id, service_id, reference from notification_history where notification_type = 'letter' and notification_status = 'returned-letter'""" results = conn.execute(sql) returned_letters = results.fetchall() references = [x.reference for x in returned_letters] insert_or_update_returned_letters(references) def downgrade(): pass
Add semicolon to match code style rules
/** * Run a function on every insertion of an iframe on the current document * @param {object} currentDocument The document interface where to start * the Mutation Observer * @param {function} execFunction The function to run. The first function * argument will be the iframe node */ const onInsertedIframe = (currentDocument, execFunction) => { const observer = new window.MutationObserver(mutations => { mutations.forEach(mutation => { ;[...mutation.addedNodes] .filter(node => node.tagName === 'IFRAME') .forEach(node => { execFunction(node) }) }) }) const observerConfig = { childList: true, subtree: true, } const targetNode = currentDocument.body observer.observe(targetNode, observerConfig) } export default onInsertedIframe
/** * Run a function on every insertion of an iframe on the current document * @param {object} currentDocument The document interface where to start * the Mutation Observer * @param {function} execFunction The function to run. The first function * argument will be the iframe node */ const onInsertedIframe = (currentDocument, execFunction) => { const observer = new window.MutationObserver(mutations => { mutations.forEach(mutation => { [...mutation.addedNodes] .filter(node => node.tagName === 'IFRAME') .forEach(node => { execFunction(node) }) }) }) const observerConfig = { childList: true, subtree: true, } const targetNode = currentDocument.body observer.observe(targetNode, observerConfig) } export default onInsertedIframe
Use port for protocol when none is provided Fixes #245
var websocket = require('websocket-stream'); var URL = require('url'); function buildBuilder(client, opts) { var host = opts.hostname || 'localhost' , port = opts.port || 80 , url = opts.protocol + '://' + host + ':' + port , ws = websocket(url, { protocol: 'mqttv3.1' }); return ws; } function buildBuilderBrowser(mqttClient, opts) { var parsed = URL.parse(document.URL); if (!opts.protocol) { if (parsed.protocol === 'https:') { opts.protocol = 'wss'; } else { opts.protocol = 'ws'; } } if (!opts.host) { opts.host = parsed.hostname; } if (!opts.port) { if(opts.protocol === 'wss'){ opts.port = 443; } else if(opts.protocol === 'ws') { opts.port = 80; } else { opts.port = parsed.port; } } var host = opts.hostname || opts.host , port = opts.port , url = opts.protocol + '://' + host + ':' + opts.port return websocket(url); } if (process.title !== 'browser') { module.exports = buildBuilder; } else { module.exports = buildBuilderBrowser; }
var websocket = require('websocket-stream'); var URL = require('url'); function buildBuilder(client, opts) { var host = opts.hostname || 'localhost' , port = opts.port || 80 , url = opts.protocol + '://' + host + ':' + port , ws = websocket(url, { protocol: 'mqttv3.1' }); return ws; } function buildBuilderBrowser(mqttClient, opts) { var parsed = URL.parse(document.URL); if (!opts.protocol) { if (parsed.protocol === 'https:') { opts.protocol = 'wss'; } else { opts.protocol = 'ws'; } } if (!opts.host) { opts.host = parsed.hostname; } if (!opts.port) { opts.port = parsed.port; } var host = opts.hostname || opts.host , port = opts.port , url = opts.protocol + '://' + host + ':' + opts.port return websocket(url); } if (process.title !== 'browser') { module.exports = buildBuilder; } else { module.exports = buildBuilderBrowser; }
[fix] Return empty array when passed `undefined` or `null` in amazon.Client.prototype._toArray
/* * client.js: Base client from which all AWS clients inherit from * * (C) 2012 Nodejitsu Inc. * */ var utile = require('utile'), request = require('request'), base = require('../core/base'); var Client = exports.Client = function (options) { base.Client.call(this, options); // Allow overriding serversUrl in child classes this.provider = 'amazon'; this.version = (options || {}).version || '2012-04-01'; this.serversUrl = (options || {}).serversUrl || this.serversUrl || 'ec2.amazonaws.com'; if (!this.before) { this.before = []; } }; utile.inherits(Client, base.Client); Client.prototype._toArray = function toArray(obj) { if (typeof obj === 'undefined') { return []; } return Array.isArray(obj) ? obj : [obj]; }; Client.prototype.failCodes = { 400: 'Bad Request', 401: 'Unauthorized', 403: 'Resize not allowed', 404: 'Item not found', 409: 'Build in progress', 413: 'Over Limit', 415: 'Bad Media Type', 500: 'Fault', 503: 'Service Unavailable' }; Client.prototype.successCodes = { 200: 'OK', 201: 'Created', 202: 'Accepted', 203: 'Non-authoritative information', 204: 'No content' };
/* * client.js: Base client from which all AWS clients inherit from * * (C) 2012 Nodejitsu Inc. * */ var utile = require('utile'), request = require('request'), base = require('../core/base'); var Client = exports.Client = function (options) { base.Client.call(this, options); // Allow overriding serversUrl in child classes this.provider = 'amazon'; this.version = (options || {}).version || '2012-04-01'; this.serversUrl = (options || {}).serversUrl || this.serversUrl || 'ec2.amazonaws.com'; if (!this.before) { this.before = []; } }; utile.inherits(Client, base.Client); Client.prototype._toArray = function toArray(obj) { return Array.isArray(obj) ? obj : [obj]; }; Client.prototype.failCodes = { 400: 'Bad Request', 401: 'Unauthorized', 403: 'Resize not allowed', 404: 'Item not found', 409: 'Build in progress', 413: 'Over Limit', 415: 'Bad Media Type', 500: 'Fault', 503: 'Service Unavailable' }; Client.prototype.successCodes = { 200: 'OK', 201: 'Created', 202: 'Accepted', 203: 'Non-authoritative information', 204: 'No content' };
[COM_PUBLICATIONS] Add a new line to a file to conform with tht formatting styles
<?php use Hubzero\Content\Migration\Base; // No direct access defined('_HZEXEC_') or die(); /** * Migration script for adding offering_id to notes **/ class Migration20170815000001ComPublications extends Base { /** * Up **/ public function up() { if (!$this->db->tableHasField('#__publications', 'featured')) { $query = "ALTER TABLE `#__publications` ADD `featured` TINYINT(1) NOT NULL DEFAULT '0';"; $this->db->setQuery($query); $this->db->query(); } } /** * Down **/ public function down() { if ($this->db->tableHasField('#__publications', 'featured')) { $query = "ALTER TABLE `#__publications` DROP `featured`;"; $this->db->setQuery($query); $this->db->query(); } } }
<?php use Hubzero\Content\Migration\Base; // No direct access defined('_HZEXEC_') or die(); /** * Migration script for adding offering_id to notes **/ class Migration20170815000001ComPublications extends Base { /** * Up **/ public function up() { if (!$this->db->tableHasField('#__publications', 'featured')) { $query = "ALTER TABLE `#__publications` ADD `featured` TINYINT(1) NOT NULL DEFAULT '0';"; $this->db->setQuery($query); $this->db->query(); } } /** * Down **/ public function down() { if ($this->db->tableHasField('#__publications', 'featured')) { $query = "ALTER TABLE `#__publications` DROP `featured`;"; $this->db->setQuery($query); $this->db->query(); } } }
Fix long_description to read README.rst.
# -*- coding: utf-8 -*- from __future__ import unicode_literals from setuptools import setup, find_packages from os.path import dirname, join def main(): base_dir = dirname(__file__) setup( name='rotunicode', version='0.1.0', description='RotUnicode', long_description=open(join(base_dir, 'README.rst')).read(), author='Kunal Parmar', author_email='kunalparmar@gmail.com', url='https://pypi.python.org/pypi/rotunicode', license='Apache License 2.0', packages=find_packages(exclude=['test']), namespace_packages=[b'box'], test_suite='test', zip_safe=False, ) if __name__ == '__main__': main()
# -*- coding: utf-8 -*- from __future__ import unicode_literals from setuptools import setup, find_packages from os.path import dirname, join def main(): base_dir = dirname(__file__) setup( name='rotunicode', version='0.1.0', description='RotUnicode', long_description=open(join(base_dir, 'README.md')).read(), author='Kunal Parmar', author_email='kunalparmar@gmail.com', url='https://pypi.python.org/pypi/rotunicode', license='Apache License 2.0', packages=find_packages(exclude=['test']), namespace_packages=[b'box'], test_suite='test', zip_safe=False, ) if __name__ == '__main__': main()
Add shortcut and changes[SEARCH_KEY_NAME] checks
"use strict"; import { SEARCH_KEY_NAME, OLUTTAMO_SEARCH_SHORTCUT } from "./constants"; // Enable chromereload by uncommenting this line: import "./lib/livereload"; import createMenu from "./lib/contextMenus"; chrome.runtime.onInstalled.addListener(function (details) { createMenu(); }); chrome.commands.onCommand.addListener(shortcut => { if (shortcut === OLUTTAMO_SEARCH_SHORTCUT){ chrome.browserAction.setBadgeText({text: "<3"}); chrome.tabs.executeScript(null, { file: "./scripts/getSelection.js", runAt: "document_end", }); } }); chrome.storage.onChanged.addListener(function(changes, namespace) { if (changes[SEARCH_KEY_NAME]){ chrome.browserAction.setBadgeText({text: "<3"}); chrome.tabs.executeScript(null, { file: "./scripts/search.js", runAt: "document_end", }); } });
"use strict"; import { SEARCH_KEY_NAME } from "./constants"; // Enable chromereload by uncommenting this line: import "./lib/livereload"; import createMenu from "./lib/contextMenus"; chrome.runtime.onInstalled.addListener(function (details) { createMenu(); }); // TODO: executeScript only if shortcut is "search-beer" chrome.commands.onCommand.addListener(shortcut => { console.log("shortcut: ", shortcut); chrome.tabs.executeScript(null, { file: "./scripts/getSelection.js", runAt: "document_end", }); }); // TODO: executeScript only if changes include SEARCH_KEY_NAME chrome.storage.onChanged.addListener(function(changes, namespace) { console.log("changes: ", changes); chrome.storage.local.get(SEARCH_KEY_NAME, (items) => { console.log(`Value: ${items[SEARCH_KEY_NAME]}`); chrome.tabs.executeScript(null, { file: "./scripts/search.js", runAt: "document_end", }); }); });
Add non-hardcoded variable that leads to styleguide assets folder
'use strict' // var util = require('util') var console = require('better-console') // var renderNav = require('./compolib.renderNav') var filetreeToJSON = require('./compolib.filetreeToJSON') var components = require('./compolib.components') var ncp = require('ncp').ncp module.exports = function build (opts) { // copy assets to public folder ncp(opts.location.styleguide + '/assets', opts.location.dest + '/assets', function (err) { if (err) { return console.error(err) } }) // TODO make sure that there are no components in dest folder before creating new // could be the situation when .json files are missing/deleted, but dest component folder is still there opts.components = [] // before build, reset components opts.treeStructure['data'] = filetreeToJSON(opts, opts.location.src, true) // renderNav(opts) // create simple list of components // Saves data in opts.searchableItems components.generateSearch(opts) // render all components // - ( component.html & raw.component.html ) + navigation // - enrich components array with new data (style, info, data file locations) // Saves data in opts.components components.renderAll(opts) components.renderDashboard(opts) // console.log(util.inspect(opts.searchableItems, {showHidden: false, depth: null})) console.log('[CL] ' + opts.components.length + ' components rendered (' + opts.location.src + ')') }
'use strict' // var util = require('util') var console = require('better-console') // var renderNav = require('./compolib.renderNav') var filetreeToJSON = require('./compolib.filetreeToJSON') var components = require('./compolib.components') var ncp = require('ncp').ncp module.exports = function build (opts) { // copy assets to public folder ncp('node_modules/component-library-core/doc-template/assets', opts.location.dest + '/assets', function (err) { if (err) { return console.error(err) } }) // TODO make sure that there are no components in dest folder before creating new // could be the situation when .json files are missing/deleted, but dest component folder is still there opts.components = [] // before build, reset components opts.treeStructure['data'] = filetreeToJSON(opts, opts.location.src, true) // renderNav(opts) // create simple list of components // Saves data in opts.searchableItems components.generateSearch(opts) // render all components // - ( component.html & raw.component.html ) + navigation // - enrich components array with new data (style, info, data file locations) // Saves data in opts.components components.renderAll(opts) components.renderDashboard(opts) // console.log(util.inspect(opts.searchableItems, {showHidden: false, depth: null})) console.log('[CL] ' + opts.components.length + ' components rendered (' + opts.location.src + ')') }
Support python3 and PEP8 rules.
# -*- coding: utf-8 -*- # # dp for Tornado # YoungYong Park (youngyongpark@gmail.com) # 2015.03.09 # import os import sys import inspect import importlib path = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) sys.path.append(path) if __name__ == '__main__': if len(sys.argv) <= 1: exit(0) module = sys.argv[1] timeout = sys.argv[2] if len(sys.argv) >= 3 else None try: module = importlib.import_module(module) except ImportError as e: print('The specified scheduler module is invalid. (%s)' % module) exit(1) try: runner = getattr(module, 'Scheduler')(timeout) except AttributeError: print('The specified scheduler module is not implemented. (%s)' % module) exit(1) try: runner.run() except Exception as e: import traceback traceback.print_exc()
# -*- coding: utf-8 -*- # # dp for Tornado # YoungYong Park (youngyongpark@gmail.com) # 2015.03.09 # import os import sys import inspect import importlib path = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) sys.path.append(path) if __name__ == '__main__': if len(sys.argv) <= 1: exit(0) module = sys.argv[1] timeout = sys.argv[2] if len(sys.argv) >= 3 else None try: module = importlib.import_module(module) except ImportError as e: print 'The specified scheduler module is invalid. (%s)' % module exit(1) try: runner = getattr(module, 'Scheduler')(timeout) except AttributeError: print 'The specified scheduler module is not implemented. (%s)' % module exit(1) try: runner.run() except Exception as e: import traceback traceback.print_exc()
Fix the report option "reportLocation" Public interface of AccessSniff describes "reportLocation"; not "location".
// // Grunt AccessSniff Task // ------------------------ module.exports = function(grunt) { var accessSniff = require('access-sniff'); grunt.registerMultiTask('accessibility', 'Use HTML codesniffer to grade accessibility', function() { var done = this.async(); var options = this.options({}); accessSniff .default(options.urls || this.filesSrc, options) .then(function(report) { if (options.reportLocation) { accessSniff.report(report, { reportLocation: options.reportLocation, reportType: options.reportType }); } grunt.log.ok('Testing Complete'); done(); }) .catch(function(error) { grunt.fail.warn(error); }); }); };
// // Grunt AccessSniff Task // ------------------------ module.exports = function(grunt) { var accessSniff = require('access-sniff'); grunt.registerMultiTask('accessibility', 'Use HTML codesniffer to grade accessibility', function() { var done = this.async(); var options = this.options({}); accessSniff .default(options.urls || this.filesSrc, options) .then(function(report) { if (options.reportLocation) { accessSniff.report(report, { location: options.reportLocation, reportType: options.reportType }); } grunt.log.ok('Testing Complete'); done(); }) .catch(function(error) { grunt.fail.warn(error); }); }); };
Add newline at end of file
__all__ = ['CloneableMeta'] def attach_new_init_method(cls): """ Replace the existing cls.__init__() method with a new one which also initialises the _clones attribute to an empty list. """ orig_init = cls.__init__ def new_init(self, *args, **kwargs): orig_init(self, *args, **kwargs) self._clones = [] cls.__init__ = new_init class CloneableMeta(type): def __new__(metacls, cg_name, bases, clsdict): new_cls = super(CloneableMeta, metacls).__new__(metacls, cg_name, bases, clsdict) attach_new_init_method(new_cls) return new_cls
__all__ = ['CloneableMeta'] def attach_new_init_method(cls): """ Replace the existing cls.__init__() method with a new one which also initialises the _clones attribute to an empty list. """ orig_init = cls.__init__ def new_init(self, *args, **kwargs): orig_init(self, *args, **kwargs) self._clones = [] cls.__init__ = new_init class CloneableMeta(type): def __new__(metacls, cg_name, bases, clsdict): new_cls = super(CloneableMeta, metacls).__new__(metacls, cg_name, bases, clsdict) attach_new_init_method(new_cls) return new_cls
Handle errors from the calendar module
#!/usr/bin/env node const express = require('express'); const app = express(); app.set('port', (process.env.PORT || 5000)); app.get('/', function (req, res) { console.log("/"); res.sendFile(__dirname + '/static/index.html'); }); const calendar = require('./calendar.js'); app.get('/calendar', (req, res) => { calendar(req.query.team, ( calendarError, cal ) => { if( calendarError ){ throw calendarError; } if (req.query.team) { console.log(req.query.team); } else { console.log("no-filter"); }; res.setHeader('Content-disposition', 'attachment; filename=hockey-mchockeyface.ics'); res.set('Content-Type', 'text/calendar'); res.send(cal); }); }); app.listen(app.get('port'), function () { console.log('Hockey McHockeyFace ready to serve on port', app.get('port')) });
#!/usr/bin/env node const express = require('express'); const app = express(); app.set('port', (process.env.PORT || 5000)); app.get('/', function (req, res) { console.log("/"); res.sendFile(__dirname + '/static/index.html'); }); const calendar = require('./calendar.js'); app.get('/calendar', (req, res) => { calendar(req.query.team,(err,cal) => { if (req.query.team) { console.log(req.query.team); } else { console.log("no-filter"); }; res.setHeader('Content-disposition', 'attachment; filename=hockey-mchockeyface.ics'); res.set('Content-Type', 'text/calendar'); res.send(cal); }); }); app.listen(app.get('port'), function () { console.log('Hockey McHockeyFace ready to serve on port', app.get('port')) });
Remove empty defaults and deprecated settings
# # linter.py # Markdown Linter for SublimeLinter, a code checking framework # for Sublime Text 3 # # Written by Jon LaBelle # Copyright (c) 2018 Jon LaBelle # # License: MIT # """This module exports the Markdownlint plugin class.""" from SublimeLinter.lint import NodeLinter, util class Markdownlint(NodeLinter): """Provides an interface to markdownlint.""" syntax = ('markdown', 'markdown gfm', 'multimarkdown', 'markdown extended') cmd = 'markdownlint' npm_name = 'markdownlint-cli' version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 0.6.0' check_version = True regex = r'.+?[:]\s(?P<line>\d+)[:]\s(?P<error>MD\d+)?[/]?(?P<message>.+)' multiline = False line_col_base = (1, 1) # '-' == file must be saved to disk first before linting tempfile_suffix = '-' error_stream = util.STREAM_STDERR word_re = None comment_re = r'\s*/[/*]' config_file = ('--config', '.markdownlintrc', '~')
# # linter.py # Markdown Linter for SublimeLinter, a code checking framework # for Sublime Text 3 # # Written by Jon LaBelle # Copyright (c) 2018 Jon LaBelle # # License: MIT # """This module exports the Markdownlint plugin class.""" from SublimeLinter.lint import NodeLinter, util class Markdownlint(NodeLinter): """Provides an interface to markdownlint.""" syntax = ('markdown', 'markdown gfm', 'multimarkdown', 'markdown extended') cmd = 'markdownlint' npm_name = 'markdownlint-cli' version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 0.6.0' check_version = True regex = r'.+?[:]\s(?P<line>\d+)[:]\s(?P<error>MD\d+)?[/]?(?P<message>.+)' multiline = False line_col_base = (1, 1) # '-' == file must be saved to disk first before linting tempfile_suffix = '-' error_stream = util.STREAM_STDERR selectors = {} word_re = None defaults = {} inline_settings = None inline_overrides = None comment_re = r'\s*/[/*]' config_file = ('--config', '.markdownlintrc', '~')
frontend: Reset play head on music selection change.
import g from './globals'; let lastPlayed = ''; function toggle(soundtrack) { if (g.sound.isPlaying) { pause(); // eslint-disable-next-line no-negated-condition } else if (soundtrack !== lastPlayed) { if (lastPlayed !== '') { g.sound.stop(); } g.audioLoader.load(soundtrack, buffer => { g.sound.setBuffer(buffer); play(); }, xhr => { let loadPercentage = Math.round(xhr.loaded / xhr.total * 100); g.playBtnElem.innerHTML = `loading ${loadPercentage}%`; }, xhr => console.log(xhr) ); lastPlayed = soundtrack; } else { play(); } } function play() { g.sound.play(); g.playBtnElem.innerHTML = 'pause'; } function pause() { g.sound.pause(); g.playBtnElem.innerHTML = 'play'; } const audio = { toggle }; export default audio;
import g from './globals'; let lastPlayed = ''; function toggle(soundtrack) { if (g.sound.isPlaying) { pause(); // eslint-disable-next-line no-negated-condition } else if (soundtrack !== lastPlayed) { g.audioLoader.load(soundtrack, buffer => { g.sound.setBuffer(buffer); play(); }, xhr => { let loadPercentage = Math.round(xhr.loaded / xhr.total * 100); g.playBtnElem.innerHTML = `loading ${loadPercentage}%`; }, xhr => console.log(xhr) ); lastPlayed = soundtrack; } else { play(); } } function play() { g.sound.play(); g.playBtnElem.innerHTML = 'pause'; } function pause() { g.sound.pause(); g.playBtnElem.innerHTML = 'play'; } const audio = { toggle }; export default audio;
Add doc to package logger
// Package logger implements middleware loggeing. package logger import ( "net/http" "time" "github.com/Sirupsen/logrus" ) // responseWriter implements the http.ResponseWriter interface and // keeps track of the header status type responseWriter struct { Status int Writer http.ResponseWriter } func (rw *responseWriter) Header() http.Header { return rw.Writer.Header() } func (rw *responseWriter) Write(b []byte) (int, error) { return rw.Writer.Write(b) } func (rw *responseWriter) WriteHeader(s int) { rw.Status = s rw.Writer.WriteHeader(s) } // Request returns an http.Handler that can be used as middleware to log requests. func Request(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { start := time.Now() rw := responseWriter{Status: 200, Writer: w} defer func() { logrus.WithFields(map[string]interface{}{ "status": rw.Status, "latency": time.Since(start), "ip": r.RemoteAddr, "method": r.Method, "url": r.URL.String(), }).Info() }() next.ServeHTTP(&rw, r) }) }
package logger import ( "net/http" "time" "github.com/Sirupsen/logrus" ) // responseWriter implements the http.ResponseWriter interface and // keeps track of the header status type responseWriter struct { Status int Writer http.ResponseWriter } func (rw *responseWriter) Header() http.Header { return rw.Writer.Header() } func (rw *responseWriter) Write(b []byte) (int, error) { return rw.Writer.Write(b) } func (rw *responseWriter) WriteHeader(s int) { rw.Status = s rw.Writer.WriteHeader(s) } func Request(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { start := time.Now() rw := responseWriter{Status: 200, Writer: w} defer func() { logrus.WithFields(map[string]interface{}{ "status": rw.Status, "latency": time.Since(start), "ip": r.RemoteAddr, "method": r.Method, "url": r.URL.String(), }).Info() }() next.ServeHTTP(&rw, r) }) }
Send user back to workspace if they try to access non-existent board
import superagent from 'superagent/lib/client'; import page from 'page'; /** * Simple helper module to make HTTP requests. */ export default { get: request.bind(null, superagent.get), put: request.bind(null, superagent.put), del: request.bind(null, superagent.del), post: request.bind(null, superagent.post) } /** * Simple helper function to make HTTP requests. Note that you don't call this * directly but instead use one of the pre-bound methods above.a */ function request(to, options = {}) { return new Promise((resolve, reject) => { let request = to(options.url) .set('Accept', 'application/json') .set('Content-Type', 'application/json') .set('Authorization', `Bearer ${options.token}`); if(options.payload) { request = request.send(options.payload) } return request.end((err, res) => { if(err) { err.statusCode = err.status || res ? res.status : 0; console.log(err.statusCode); if (err.statusCode == 404) { // Insert custom 404 redirect here page.redirect('/workspace'); } else if (err.statusCode == 400) { page.redirect('/workspace'); } return reject(err); } return resolve({ body: res.body, headers: res.headers }); }); }); }
import superagent from 'superagent/lib/client'; /** * Simple helper module to make HTTP requests. */ export default { get: request.bind(null, superagent.get), put: request.bind(null, superagent.put), del: request.bind(null, superagent.del), post: request.bind(null, superagent.post) } /** * Simple helper function to make HTTP requests. Note that you don't call this * directly but instead use one of the pre-bound methods above. */ function request(to, options = {}) { return new Promise((resolve, reject) => { let request = to(options.url) .set('Accept', 'application/json') .set('Content-Type', 'application/json') .set('Authorization', `Bearer ${options.token}`); if(options.payload) { request = request.send(options.payload) } return request.end((err, res) => { if(err) { err.statusCode = err.status || res ? res.status : 0; return reject(err); } return resolve({ body: res.body, headers: res.headers }); }); }); }
Modify ajax-reveal to open modal from a link on modal
// 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, or any plugin's // vendor/assets/javascripts directory 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 // compiled file. JavaScript code in this file should be added after the last require_* statement. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require rails-ujs //= require turbolinks //= require jquery3 //= require jquery_ujs //= require foundation //= require_tree . $(document).on('turbolinks:load', function() { $(document).foundation(); $('body').on('click', '[data-open="ajax-reveal"]', function(e) { e.preventDefault(); $.ajax({ url: $(this).data('url'), success: function(result) { $(".reveal-content").html(result); }, error: function(result) { $(".reveal-content").html('Error loading content. Please close popup and retry.'); } }); }); });
// 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, or any plugin's // vendor/assets/javascripts directory 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 // compiled file. JavaScript code in this file should be added after the last require_* statement. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require rails-ujs //= require turbolinks //= require jquery3 //= require jquery_ujs //= require foundation //= require_tree . $(document).on('turbolinks:load', function() { $(document).foundation(); $('[data-open="ajax-reveal"]').on('click', function(e) { e.preventDefault(); $.ajax({ url: $(this).data('url'), success: function(result) { $(".reveal-content").html(result); }, error: function(result) { $(".reveal-content").html('Error loading content. Please close popup and retry.'); } }); }); });
Add a "FIXME" comment for the disabled test so it shows up as a note in Eclipse (this idea was suggested awhile ago by brozow).
package org.opennms.netmgt.vulnscand; import junit.framework.TestCase; import org.opennms.core.queue.FifoQueue; import org.opennms.core.queue.FifoQueueImpl; import org.opennms.netmgt.config.VulnscandConfigFactory; public class SchedulerTest extends TestCase { protected void setUp() throws Exception { System.setProperty("opennms.home", "src/test/test-configurations/vulnscand"); VulnscandConfigFactory.init(); super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } // FIXME public void FIXMEtestCreate() throws Exception { FifoQueue q = new FifoQueueImpl(); Scheduler scheduler = new Scheduler(q); Vulnscand vulnscand = null; vulnscand.initialize(); } }
package org.opennms.netmgt.vulnscand; import junit.framework.TestCase; import org.opennms.core.queue.FifoQueue; import org.opennms.core.queue.FifoQueueImpl; import org.opennms.netmgt.config.VulnscandConfigFactory; public class SchedulerTest extends TestCase { protected void setUp() throws Exception { System.setProperty("opennms.home", "src/test/test-configurations/vulnscand"); VulnscandConfigFactory.init(); super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } public void FIXMEtestCreate() throws Exception { FifoQueue q = new FifoQueueImpl(); Scheduler scheduler = new Scheduler(q); Vulnscand vulnscand = null; vulnscand.initialize(); } }
Fix for rendering empty views
<?php namespace pff; /** * Layout system with PHP templates * * A layout is a specific type of View: it represents a common layout with most * of its elements fixed and a few placeholders to render custom views. * * @author paolo.fagni<at>gmail.com */ class LayoutPHP extends \pff\ViewPHP { /** * @var \pff\AView[] */ private $_contentView; /** * Adds an Aview to the layout queue * * @param \pff\AView $view */ public function addContent(\pff\AView $view) { $this->_contentView[] = $view; } /** * Show the content in the layout * * Add "<?php $this->content()?>" in your layout template where you want to * display the AView object * * @param int $index */ public function content($index = 0) { if(isset($this->_contentView[$index])){ $this->_contentView[$index]->render(); } } }
<?php namespace pff; /** * Layout system with PHP templates * * A layout is a specific type of View: it represents a common layout with most * of its elements fixed and a few placeholders to render custom views. * * @author paolo.fagni<at>gmail.com */ class LayoutPHP extends \pff\ViewPHP { /** * @var \pff\AView[] */ private $_contentView; /** * Adds an Aview to the layout queue * * @param \pff\AView $view */ public function addContent(\pff\AView $view) { $this->_contentView[] = $view; } /** * Show the content in the layout * * Add "<?php $this->content()?>" in your layout template where you want to * display the AView object * * @param int $index */ public function content($index = 0) { $this->_contentView[$index]->render(); } }
Add mod+, as keyboard shortcut
define([ "src/tab", "src/manager", "less!src/stylesheets/main.less" ], function(Tab, Manager) { var commands = codebox.require("core/commands"); var dialogs = codebox.require("utils/dialogs"); var manager = new Manager(); commands.register({ id: "settings.open", title: "Settings: Open", shortcuts: [ "mod+," ], run: function(args, context) { return codebox.tabs.add(Tab, { model: manager }, { type: "settings", title: "Settings", uniqueId: "settings" }); } }); // Exports settings manager codebox.settings = manager; });
define([ "src/tab", "src/manager", "less!src/stylesheets/main.less" ], function(Tab, Manager) { var commands = codebox.require("core/commands"); var dialogs = codebox.require("utils/dialogs"); var manager = new Manager(); commands.register({ id: "settings.open", title: "Settings: Open", run: function(args, context) { return codebox.tabs.add(Tab, { model: manager }, { type: "settings", title: "Settings", uniqueId: "settings" }); } }); // Exports settings manager codebox.settings = manager; });
Use PNG for the avatar link
module.exports = { exec: function (msg, args) { userQuery(args || msg.author.id, msg, true).then(u => { bot.createMessage(msg.channel.id, { embed: { author: { name: `${u.nick ? u.nick : u.username} (${u.username}#${u.discriminator})'s avatar`, icon_url: bot.user.staticAvatarURL }, image: { url: u.avatarURL }, description: `[Image not loading?](${u.dynamicAvatarURL("png", 2048)})` } }); }).catch(console.error); }, isCmd: true, name: "getavatar", display: true, category: 1, description: "Get someone's avatar!" };
module.exports = { exec: function (msg, args) { userQuery(args || msg.author.id, msg, true).then(u => { bot.createMessage(msg.channel.id, { embed: { author: { name: `${u.nick ? u.nick : u.username} (${u.username}#${u.discriminator})'s avatar`, icon_url: bot.user.staticAvatarURL }, image: { url: u.avatarURL }, description: `[Image not loading?](${u.avatarURL})` } }); }).catch(console.error); }, isCmd: true, name: "getavatar", display: true, category: 1, description: "Get someone's avatar!" };