text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Select history_ledger columns directly, to prep for more fields
package db import ( "database/sql" sq "github.com/lann/squirrel" "time" ) var LedgerRecordSelect sq.SelectBuilder = sq.Select( "hl.id", "hl.sequence", "hl.importer_version", "hl.ledger_hash", "hl.previous_ledger_hash", "hl.transaction_count", "hl.operation_count", "hl.closed_at", "hl.created_at", "hl.updated_at", ).From("history_ledgers hl") type LedgerRecord struct { HistoryRecord Sequence int32 `db:"sequence"` ImporterVersion int32 `db:"importer_version"` LedgerHash string `db:"ledger_hash"` PreviousLedgerHash sql.NullString `db:"previous_ledger_hash"` TransactionCount int32 `db:"transaction_count"` OperationCount int32 `db:"operation_count"` ClosedAt time.Time `db:"closed_at"` CreatedAt time.Time `db:"created_at"` UpdatedAt time.Time `db:"updated_at"` }
package db import ( "database/sql" sq "github.com/lann/squirrel" "time" ) var LedgerRecordSelect sq.SelectBuilder = sq. Select("hl.*"). From("history_ledgers hl") type LedgerRecord struct { HistoryRecord Sequence int32 `db:"sequence"` ImporterVersion int32 `db:"importer_version"` LedgerHash string `db:"ledger_hash"` PreviousLedgerHash sql.NullString `db:"previous_ledger_hash"` TransactionCount int32 `db:"transaction_count"` OperationCount int32 `db:"operation_count"` ClosedAt time.Time `db:"closed_at"` CreatedAt time.Time `db:"created_at"` UpdatedAt time.Time `db:"updated_at"` }
Order page links by location
<div id='b-pagesettings-links' class="b-pagesettings"> <div> <h1>Primary Link</h1> <p> <?= $page->link() ?> </p> </div> <div> <h1>All links</h1> <ul class='boom-tree'> <? foreach($page->links->order_by('location', 'asc')->find_all() as $link): ?> <li data-link="<?= $link->location ?>" data-id="<?= $link->id ?>"> <?= $link->location ?> <?= Form::radio('is_primary', $link->location, (bool) $link->is_primary, array('class' => 'b-links-primary')) ?> <?= Form::checkbox("redirect_" . $link->id, 1, (bool) $link->redirect, array('class' => 'b-links-redirect')) ?> </li> <? endforeach; ?> </ul> </div> <div> <h1>Short Link</h1> <p> <?= URL::site($page->short_link()) ?> </p> </div> </div>
<div id='b-pagesettings-links' class="b-pagesettings"> <div> <h1>Primary Link</h1> <p> <?= $page->link() ?> </p> </div> <div> <h1>All links</h1> <ul class='boom-tree'> <? foreach($page->links->find_all() as $link): ?> <li data-link="<?= $link->location ?>" data-id="<?= $link->id ?>"> <?= $link->location ?> <?= Form::radio('is_primary', $link->location, (bool) $link->is_primary, array('class' => 'b-links-primary')) ?> <?= Form::checkbox("redirect_" . $link->id, 1, (bool) $link->redirect, array('class' => 'b-links-redirect')) ?> </li> <? endforeach; ?> </ul> </div> <div> <h1>Short Link</h1> <p> <?= URL::site($page->short_link()) ?> </p> </div> </div>
Add missing typehing on backend init
<?php namespace Backend; /* * This file is part of Fork CMS. * * For the full copyright and license information, please view the license * file that was distributed with this source code. */ use SpoonFilter; use Symfony\Component\HttpKernel\KernelInterface; /** * This class will initiate the backend-application */ class Init extends \Common\Core\Init { /** * @param KernelInterface $kernel */ public function __construct(KernelInterface $kernel) { $this->allowedTypes = array('Backend', 'BackendAjax', 'BackendCronjob', 'Console'); parent::__construct($kernel); } /** * {@inheritdoc} */ public function initialize(string $type) { parent::initialize($type); SpoonFilter::disableMagicQuotes(); } }
<?php namespace Backend; /* * This file is part of Fork CMS. * * For the full copyright and license information, please view the license * file that was distributed with this source code. */ use SpoonFilter; use Symfony\Component\HttpKernel\KernelInterface; /** * This class will initiate the backend-application */ class Init extends \Common\Core\Init { /** * @param KernelInterface $kernel */ public function __construct(KernelInterface $kernel) { $this->allowedTypes = array('Backend', 'BackendAjax', 'BackendCronjob', 'Console'); parent::__construct($kernel); } /** * {@inheritdoc} */ public function initialize($type) { parent::initialize($type); SpoonFilter::disableMagicQuotes(); } }
Move settings into "additional" section
<?php /** * * @author Pawel Rojek <pawel at pawelrojek.com> * @author Ian Reinhart Geiser <igeiser at devonit.com> * * This file is licensed under the Affero General Public License version 3 or later. * **/ namespace OCA\Drawio; use OCP\Settings\ISettings; use OCA\Drawio\AppInfo\Application; class AdminSettings implements ISettings { public function __construct() { } public function getForm() { $app = new Application(); $container = $app->getContainer(); $response = $container->query("\OCA\Drawio\Controller\SettingsController")->index(); return $response; } public function getSection() { return "additional"; } public function getPriority() { return 60; } }
<?php /** * * @author Pawel Rojek <pawel at pawelrojek.com> * @author Ian Reinhart Geiser <igeiser at devonit.com> * * This file is licensed under the Affero General Public License version 3 or later. * **/ namespace OCA\Drawio; use OCP\Settings\ISettings; use OCA\Drawio\AppInfo\Application; class AdminSettings implements ISettings { public function __construct() { } public function getForm() { $app = new Application(); $container = $app->getContainer(); $response = $container->query("\OCA\Drawio\Controller\SettingsController")->index(); return $response; } public function getSection() { return "server"; } public function getPriority() { return 60; } }
Send timestamp to the outside world
import time import socket import datetime from ipaddress import ip_address import zmq import yaml import quick2wire.i2c as i2c from database import Writer from database import Temperature, Base if __name__ == '__main__': context = zmq.Context() publisher = context.socket(zmq.PUB) database = context.socket(zmq.PUB) server = yaml.load(open('config.yaml'))['server'] host = server['host'] try: ip_address(host) except ValueError: host = socket.gethostbyname(host) publisher.bind('tcp://{}:{}'.format(host, server['port'])) database.bind('inproc://dbwrite') writer = Writer(context) writer.start() while True: with i2c.I2CMaster() as bus: data = bus.transaction(i2c.reading(8, 6)) now = datetime.datetime.utcnow() temp = data[0][-2:] temp = int.from_bytes(temp, byteorder='little', signed=True) / 100. print(now, temp) publisher.send_pyobj(('TEMP', now.timestamp(), temp)) database.send_pyobj(('TEMP', now, temp)) time.sleep(0.05)
import time import socket import datetime from ipaddress import ip_address import zmq import yaml import quick2wire.i2c as i2c from database import Writer from database import Temperature, Base if __name__ == '__main__': context = zmq.Context() publisher = context.socket(zmq.PUB) database = context.socket(zmq.PUB) server = yaml.load(open('config.yaml'))['server'] host = server['host'] try: ip_address(host) except ValueError: host = socket.gethostbyname(host) publisher.bind('tcp://{}:{}'.format(host, server['port'])) database.bind('inproc://dbwrite') writer = Writer(context) writer.start() while True: with i2c.I2CMaster() as bus: data = bus.transaction(i2c.reading(8, 6)) now = datetime.datetime.utcnow() temp = data[0][-2:] temp = int.from_bytes(temp, byteorder='little', signed=True) / 100. print(now, temp) publisher.send_pyobj(('TEMP', now, temp)) database.send_pyobj(('TEMP', now, temp)) time.sleep(0.05)
Format message, stack to match original Add new line at beginning of stack Pass the original stack to original Meteor._debug
var originalMeteorDebug = Meteor._debug; Meteor._debug = function(message, stack) { if(!window.zone) { // sometimes Meteor._debug is called with the stack concat to the message if(message && stack === undefined) { stack = getStackFromMessage(message); message = firstLine(message); } // stacktrace.js requires an Error object to create the normalized stack var err = new Error(message); err.stack = stack; var normalizedStack = getNormalizedStacktrace(err); var now = (new Date().getTime()); Kadira.errors.sendError({ appId : Kadira.options.appId, name : message, source : 'client', startTime : now, type : 'meteor._debug', info : getBrowserInfo(), stacks : JSON.stringify([{at: now, events: [], stack: normalizedStack}]), }); } originalMeteorDebug(message, stack); }; var stackRegex = /^\s+at\s.+$/gm; function getStackFromMessage (message) { // add empty string to add the empty line at start var stack = ['']; var match; while(match = stackRegex.exec(message)) { stack.push(match[0]); } return stack.join('\n'); } function firstLine (message) { return message.split('\n')[0]; }
var originalMeteorDebug = Meteor._debug; Meteor._debug = function(message, stack) { if(!window.zone) { // sometimes Meteor._debug is called with the stack concat to the message if(message && stack === undefined) { stack = getStackFromMessage(message); message = firstLine(message); } // stacktrace.js requires an Error object to create the normalized stack var err = new Error(message); err.stack = stack; var stack = getNormalizedStacktrace(err); var now = (new Date().getTime()); Kadira.errors.sendError({ appId : Kadira.options.appId, name : message, source : 'client', startTime : now, type : 'meteor._debug', info : getBrowserInfo(), stacks : JSON.stringify([{at: now, events: [], stack: stack}]), }); } originalMeteorDebug(message, stack); }; var stackRegex = /^\s+at\s.+$/gm; function getStackFromMessage (message) { var stack = []; var match; while(match = stackRegex.exec(message)) { stack.push(match[0]); } return stack.join('\n'); } function firstLine (message) { return message.split('\n')[0]; }
Update URL rules to match Molly 1.x
from flask import Blueprint from flask.ext.babel import lazy_gettext as _ from molly.apps.common.app import BaseApp from molly.apps.places.endpoints import PointOfInterestEndpoint from molly.apps.places.services import PointsOfInterest class App(BaseApp): module = 'http://mollyproject.org/apps/places' human_name = _('Places') def __init__(self, instance_name, config, providers, services): self.instance_name = instance_name poi_service = PointsOfInterest(instance_name, services['kv'].db[instance_name]) for provider in providers: provider.poi_service = poi_service self._register_provider_as_importer(provider, services) self._poi_endpoint = PointOfInterestEndpoint(instance_name, poi_service) self.blueprint = Blueprint(self.instance_name, __name__) self.blueprint.add_url_rule('/<slug>/', 'poi', self._poi_endpoint.get) self.links = []
from flask import Blueprint from flask.ext.babel import lazy_gettext as _ from molly.apps.common.app import BaseApp from molly.apps.places.endpoints import PointOfInterestEndpoint from molly.apps.places.services import PointsOfInterest class App(BaseApp): module = 'http://mollyproject.org/apps/places' human_name = _('Places') def __init__(self, instance_name, config, providers, services): self.instance_name = instance_name poi_service = PointsOfInterest(instance_name, services['kv'].db[instance_name]) for provider in providers: provider.poi_service = poi_service self._register_provider_as_importer(provider, services) self._poi_endpoint = PointOfInterestEndpoint(instance_name, poi_service) self.blueprint = Blueprint(self.instance_name, __name__) self.blueprint.add_url_rule('/<slug>', 'poi', self._poi_endpoint.get) self.links = []
Add test for checking whether insert method runs or not Tester class for the insert method that was implemented in the Records class. Whether or not the values were properly inserted has not been checked yet. This test was done only to check if it can be ran without exceptions happening.
package com.nigorojr.typebest; import java.sql.SQLException; import java.util.HashMap; public class Tester { public static void main(String[] args) { // This is to test the behavior of the Database class try { Records rec = new Records(); System.out.println("exist?\n" + rec.isTableExist()); HashMap<String, String> pair = new HashMap<String, String>(); pair.put("foo", "int"); pair.put("hoge", "varchar(50)"); if (!rec.isTableExist()) { rec.createTable(pair); } System.out.println("finished creating..."); HashMap<String, String> ins = new HashMap<String, String>(); ins.put("foo", "50"); ins.put("hoge", "'barbar'"); rec.insert(ins); } catch (SQLException e) { e.printStackTrace(); } } }
package com.nigorojr.typebest; import java.sql.SQLException; import java.util.HashMap; public class Tester { public static void main(String[] args) { // This is to test the behavior of the Database class try { Records rec = new Records(); System.out.println("exist?\n" + rec.isTableExist()); HashMap<String, String> pair = new HashMap<String, String>(); pair.put("foo", "int"); pair.put("hoge", "varchar(50)"); if (!rec.isTableExist()) { rec.createTable(pair); } } catch (SQLException e) { e.printStackTrace(); } } }
Use the pattern method to contrain the route parameter by a given regular expression.
<?php namespace App\Providers; use Illuminate\Routing\Router; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; class RouteServiceProvider extends ServiceProvider { /** * This namespace is applied to the controller routes in your routes file. * * In addition, it is set as the URL generator's root namespace. * * @var string */ protected $namespace = 'App\Http\Controllers'; /** * Define your route model bindings, pattern filters, etc. * * @param \Illuminate\Routing\Router $router * @return void */ public function boot(Router $router) { parent::boot($router); $router->pattern('id', '[0-9]+'); } /** * Define the routes for the application. * * @param \Illuminate\Routing\Router $router * @return void */ public function map(Router $router) { $router->group(['namespace' => $this->namespace], function($router) { require app_path('Http/routes.php'); }); } }
<?php namespace App\Providers; use Illuminate\Routing\Router; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; class RouteServiceProvider extends ServiceProvider { /** * This namespace is applied to the controller routes in your routes file. * * In addition, it is set as the URL generator's root namespace. * * @var string */ protected $namespace = 'App\Http\Controllers'; /** * Define your route model bindings, pattern filters, etc. * * @param \Illuminate\Routing\Router $router * @return void */ public function boot(Router $router) { parent::boot($router); // } /** * Define the routes for the application. * * @param \Illuminate\Routing\Router $router * @return void */ public function map(Router $router) { $router->group(['namespace' => $this->namespace], function($router) { require app_path('Http/routes.php'); }); } }
[fix] Set correct file path for coverage task
import gulp from 'gulp'; import jasmineNode from 'gulp-jasmine-node'; import babel from 'gulp-babel'; import injectModules from 'gulp-inject-modules'; import gulpBabelIstanbul from 'gulp-babel-istanbul'; import gulpCoveralls from 'gulp-coveralls'; // This task runs jasmine tests and outputs the result to the cli. gulp.task('run-tests', () => { gulp.src('server/tests/tests.js') .pipe(babel()) .pipe(injectModules()) .pipe(jasmineNode()); }); // Gulp coverage implicitly depends on run-tests. gulp.task('coverage', () => { gulp.src(['server/**/*.js']) .pipe(gulpBabelIstanbul()) .pipe(gulpBabelIstanbul.hookRequire()) .on('finish', () => { gulp.src('server/tests/tests.js') .pipe(babel()) .pipe(injectModules()) .pipe(jasmineNode()) .pipe(gulpBabelIstanbul.writeReports()) .pipe(gulpBabelIstanbul.enforceThresholds({ thresholds: { global: 50 } })) .on('end', () => { gulp.src('coverage/lcov.info') .pipe(gulpCoveralls()); }); }); });
import gulp from 'gulp'; import jasmineNode from 'gulp-jasmine-node'; import babel from 'gulp-babel'; import injectModules from 'gulp-inject-modules'; import gulpBabelIstanbul from 'gulp-babel-istanbul'; import gulpCoveralls from 'gulp-coveralls'; // This task runs jasmine tests and outputs the result to the cli. gulp.task('run-tests', () => { gulp.src('server/tests/tests.js') .pipe(babel()) .pipe(injectModules()) .pipe(jasmineNode()); }); // Gulp coverage implicitly depends on run-tests. gulp.task('coverage', () => { gulp.src(['src/*.js', 'routes/*.js']) .pipe(gulpBabelIstanbul()) .pipe(gulpBabelIstanbul.hookRequire()) .on('finish', () => { gulp.src('server/tests/tests.js') .pipe(babel()) .pipe(injectModules()) .pipe(jasmineNode()) .pipe(gulpBabelIstanbul.writeReports()) .pipe(gulpBabelIstanbul.enforceThresholds({ thresholds: { global: 30 } })) .on('end', () => { gulp.src('coverage/lcov.info') .pipe(gulpCoveralls()); }); }); });
Use index to scroll to desired target
import { PureComponent } from 'react'; import PropTypes from 'prop-types'; import { scrollIt } from 'utils/scroll'; class ScrollToHighlightIndex extends PureComponent { // eslint-disable-line react/prefer-stateless-function componentDidMount() { setTimeout(this.handleScroll, 150); } componentWillReceiveProps(nextProps) { if (nextProps.content.html !== this.props.content.html) { setTimeout(this.handleScroll, 150); } } handleScroll = () => { const { idx, targetElementsSelector } = this.props; const target = idx ? document.querySelectorAll(targetElementsSelector)[idx] : document.querySelectorAll(targetElementsSelector)[0]; if (target) { scrollIt(target, 300, 'smooth'); } }; render() { return null; } } ScrollToHighlightIndex.propTypes = { idx: PropTypes.string, targetElementsSelector: PropTypes.string, content: PropTypes.object }; export default ScrollToHighlightIndex;
import { PureComponent } from 'react'; import PropTypes from 'prop-types'; import { scrollIt } from 'utils/scroll'; class ScrollToHighlightIndex extends PureComponent { // eslint-disable-line react/prefer-stateless-function componentDidMount() { setTimeout(this.handleScroll, 150); } componentWillReceiveProps(nextProps) { if (nextProps.content.html !== this.props.content.html) { setTimeout(this.handleScroll, 150); } } handleScroll = () => { const { idx, targetElementsSelector } = this.props; const e = idx ? document.querySelectorAll(targetElementsSelector)[idx] : document.querySelectorAll(targetElementsSelector)[0]; if (e) { scrollIt(document.querySelector(targetElementsSelector), 300, 'smooth'); } }; render() { return null; } } ScrollToHighlightIndex.propTypes = { idx: PropTypes.string, targetElementsSelector: PropTypes.string, content: PropTypes.object }; export default ScrollToHighlightIndex;
Add logging to delivery receipt view
from __future__ import absolute_import import logging from corehq.apps.sms.views import IncomingBackendView from corehq.messaging.smsbackends.start_enterprise.models import ( StartEnterpriseBackend, StartEnterpriseDeliveryReceipt, ) from datetime import datetime from django.http import HttpResponse, HttpResponseBadRequest class StartEnterpriseDeliveryReceiptView(IncomingBackendView): urlname = 'start_enterprise_dlr' @property def backend_class(self): return StartEnterpriseBackend def get(self, request, api_key, *args, **kwargs): logging.info("Received Start Enterprise delivery receipt with items: %s" % request.GET.dict().keys()) message_id = request.GET.get('msgid') if not message_id: return HttpResponseBadRequest("Missing 'msgid'") message_id = message_id.strip() try: dlr = StartEnterpriseDeliveryReceipt.objects.get(message_id=message_id) except StartEnterpriseDeliveryReceipt.DoesNotExist: dlr = None if dlr: dlr.received_on = datetime.utcnow() dlr.info = request.GET.dict() dlr.save() # Based on the documentation, a response of "1" acknowledges receipt of the DLR return HttpResponse("1")
from __future__ import absolute_import from corehq.apps.sms.views import IncomingBackendView from corehq.messaging.smsbackends.start_enterprise.models import ( StartEnterpriseBackend, StartEnterpriseDeliveryReceipt, ) from datetime import datetime from django.http import HttpResponse, HttpResponseBadRequest class StartEnterpriseDeliveryReceiptView(IncomingBackendView): urlname = 'start_enterprise_dlr' @property def backend_class(self): return StartEnterpriseBackend def get(self, request, api_key, *args, **kwargs): message_id = request.GET.get('msgid') if not message_id: return HttpResponseBadRequest("Missing 'msgid'") message_id = message_id.strip() try: dlr = StartEnterpriseDeliveryReceipt.objects.get(message_id=message_id) except StartEnterpriseDeliveryReceipt.DoesNotExist: dlr = None if dlr: dlr.received_on = datetime.utcnow() dlr.info = request.GET.dict() dlr.save() # Based on the documentation, a response of "1" acknowledges receipt of the DLR return HttpResponse("1")
Change module path for cluster evaluation
# for local run, before pygraphc packaging import sys sys.path.insert(0, '../pygraphc/misc') from IPLoM import * sys.path.insert(0, '../pygraphc/evaluation') from ExternalEvaluation import * # set path ip_address = '161.166.232.17' standard_path = '/home/hudan/Git/labeled-authlog/dataset/' + ip_address standard_file = standard_path + 'auth.log.anon.labeled' analyzed_file = 'auth.log.anon' prediction_file = 'iplom-result-' + ip_address + '.txt' OutputPath = './results' para = Para(path=standard_path, logname=analyzed_file, save_path=OutputPath) # call IPLoM and get clusters myparser = IPLoM(para) time = myparser.main_process() clusters = myparser.get_clusters() original_logs = myparser.logs # set cluster label to get evaluation metrics ExternalEvaluation.set_cluster_label_id(None, clusters, original_logs, prediction_file) homogeneity_completeness_vmeasure = ExternalEvaluation.get_homogeneity_completeness_vmeasure(standard_file, prediction_file) print homogeneity_completeness_vmeasure print ('The running time of IPLoM is', time)
# for local run, before pygraphc packaging import sys sys.path.insert(0, '../pygraphc/misc') from IPLoM import * sys.path.insert(0, '../pygraphc/clustering') from ClusterUtility import * from ClusterEvaluation import * # set path ip_address = '161.166.232.17' standard_path = '/home/hudan/Git/labeled-authlog/dataset/' + ip_address standard_file = standard_path + 'auth.log.anon.labeled' analyzed_file = 'auth.log.anon' prediction_file = 'iplom-result-' + ip_address + '.txt' OutputPath = './results' para = Para(path=standard_path, logname=analyzed_file, save_path=OutputPath) # call IPLoM and get clusters myparser = IPLoM(para) time = myparser.main_process() clusters = myparser.get_clusters() original_logs = myparser.get_logs() # set cluster label to get evaluation metrics ClusterUtility.set_cluster_label_id(None, clusters, original_logs, prediction_file) homogeneity_completeness_vmeasure = ClusterEvaluation.get_homogeneity_completeness_vmeasure(standard_file, prediction_file) print homogeneity_completeness_vmeasure print ('The running time of IPLoM is', time)
Fix insanity-inducing argument omission mistake
from django.contrib.auth.backends import ModelBackend from django.contrib.auth.models import AnonymousUser class ObjectPermissionBackend(ModelBackend): def get_group_permissions(self, user_obj, obj=None): # probably won't be used return super(ObjectPermissionBackend, self ).get_group_permissions(user_obj, obj) def get_all_permissions(self, user_obj, obj=None): return super(ObjectPermissionBackend, self ).get_all_permissions(user_obj, obj) def has_perm(self, user_obj, perm, obj=None): if obj is None or not hasattr(obj, 'has_perm'): return super(ObjectPermissionBackend, self ).has_perm(user_obj, perm, obj) if not user_obj.is_active and not isinstance(user_obj, AnonymousUser): # Inactive users are denied immediately, except in the case of # AnonymousUsers. They are inactive but require further processing return False return obj.has_perm(user_obj, perm) def has_module_perms(self, user_obj, app_label): # probably won't be used return super(ObjectPermissionBackend, self ).has_module_perms(user_obj, app_label)
from django.contrib.auth.backends import ModelBackend from django.contrib.auth.models import AnonymousUser class ObjectPermissionBackend(ModelBackend): def get_group_permissions(self, user_obj, obj=None): # probably won't be used return super(ObjectPermissionBackend, self ).get_group_permissions(user_obj, obj) def get_all_permissions(self, user_obj, obj=None): return super(ObjectPermissionBackend, self ).get_all_permissions(user_obj, obj) def has_perm(self, user_obj, perm, obj=None): if obj is None or not hasattr(obj, 'has_perm'): return super(ObjectPermissionBackend, self ).has_perm(user_obj, obj) if not user_obj.is_active and not isinstance(user_obj, AnonymousUser): # Inactive users are denied immediately, except in the case of # AnonymousUsers. They are inactive but require further processing return False return obj.has_perm(user_obj, perm) def has_module_perms(self, user_obj, app_label): # probably won't be used return super(ObjectPermissionBackend, self ).has_module_perms(user_obj, app_label)
Add basic drawer layout to Android
/* * Copyright 2017-present, Hippothesis, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. * * @flow */ 'use strict'; import React, { Component } from 'react'; import { DrawerLayoutAndroid, Text, View } from 'react-native'; class NavigationBar extends Component { render() { var navigationView = ( <View style={{flex: 1, backgroundColor: '#fff'}}> <Text style={{margin: 10, fontSize: 15, textAlign: 'left'}}>I'm in the Drawer!</Text> </View> ); return ( <DrawerLayoutAndroid drawerWidth={300} drawerPosition={DrawerLayoutAndroid.positions.Left} renderNavigationView={() => navigationView}> <View style={{flex: 1, alignItems: 'center'}}> <Text style={{margin: 10, fontSize: 15, textAlign: 'right'}}>Hello</Text> <Text style={{margin: 10, fontSize: 15, textAlign: 'right'}}>Hello</Text> </View> </DrawerLayoutAndroid> ); } } export default NavigationBar;
/* * Copyright 2017-present, Hippothesis, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. * * @flow */ 'use strict'; import React, { Component } from 'react'; import { DrawerLayoutAndroid, Text, View } from 'react-native'; class NavigationBar extends Component { render() { var navigationView = ( <View style={{flex: 1, backgroundColor: '#fff'}}> <Text style={{margin: 10, fontSize: 15, textAlign: 'left'}}>I'm in the Drawer!</Text> </View> ); return ( <DrawerLayoutAndroid drawerWidth={300} drawerPosition={DrawerLayoutAndroid.positions.Left} renderNavigationView={() => navigationView}> <View style={{flex: 1, alignItems: 'center'}}> <Text style={{margin: 10, fontSize: 15, textAlign: 'right'}}>Hello</Text> <Text style={{margin: 10, fontSize: 15, textAlign: 'right'}}>Hello</Text> </View> </DrawerLayoutAndroid> ); } }
Add command-line arguments and main function
import json import csv import argparse def json_to_csv(json_file): with open(json_file, 'r') as jsonfile, open('output.csv', 'w', newline='') as csvfile: jsn = json.load(jsonfile) fieldnames = [] for name in jsn[0]: fieldnames += [name] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() for elem in jsn: writer.writerow(elem) def csv_to_json(csv_file): with open(csv_file, 'r') as csvfile, open('output.json', 'w') as jsonfile: reader = csv.DictReader(csvfile) jsn = [] for row in reader: jsn += [row] json.dump(jsn, jsonfile) def main(): parser = argparse.ArgumentParser() parser.add_argument('inputtype', help='The type of input', type=str, choices=['csv', 'json']) parser.add_argument('filename', help='Name of the input file', type=str) args = parser.parse_args() if (args.inputtype=='csv'): csv_to_json(args.filename) outputtype = 'json' elif (args.inputtype=='json'): json_to_csv(args.filename) outputtype = 'csv' print('[*] Output saved as output.{}'.format(outputtype)) if __name__=='__main__': main()
import json import csv def json_to_csv(json_file): with open(json_file, 'r') as jsonfile, open('output.csv', 'w', newline='') as csvfile: jsn = json.load(jsonfile) fieldnames = [] for name in jsn[0]: fieldnames += [name] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() for elem in jsn: writer.writerow(elem) def csv_to_json(csv_file): with open(csv_file, 'r') as csvfile, open('output.json', 'w') as jsonfile: reader = csv.DictReader(csvfile) jsn = [] for row in reader: jsn += [row] json.dump(jsn, jsonfile) filename = input('Enter filename of CSV file: ') csv_to_json(filename)
Add translation for 'Connectivity checks' section.
<?php $TRANSLATIONS = array( "If you don't know your password, please see below, section <a href=\"#user_servervars2\">Useful Informations For Connection With Login/Password</a>." => "Si vous ne connaissez pas votre mot de passe, voyez plus bas la section <a href=\"#user_servervars2\">Informations utiles pour la connexion via utilisateur/mot de passe</a>.", "Version of %s:" => "Version de %s :", "Change log" => "Change log", "GTU" => "CGU", "Confirm suppression of {userID} user ?" => "Confirmez vous la suppression de l'utilisateur {userID} ?", "User suppression" => "Suppression d'un utilisateur", "Help translate My CoRe" => "Aidez à traduire My CoRe", "Help translate ownCloud" => "Aidez à traduire ownCloud", "Connectivity Checks" => "Vérifications des connections", "No problems found" => "Aucun problème trouvé", "Please double check the <a href=\'%s\'>installation guides</a>." => "Merci de bien vérifier les <a href=\'%s\'>guides d'installation</a>." ); $PLURAL_FORMS = "nplurals=2; plural=(n > 1);";
<?php $TRANSLATIONS = array( "If you don't know your password, please see below, section <a href=\"#user_servervars2\">Useful Informations For Connection With Login/Password</a>." => "Si vous ne connaissez pas votre mot de passe, voyez plus bas la section <a href=\"#user_servervars2\">Informations utiles pour la connexion via utilisateur/mot de passe</a>.", "Version of %s:" => "Version de %s :", "Change log" => "Change log", "GTU" => "CGU", "Confirm suppression of {userID} user ?" => "Confirmez vous la suppression de l'utilisateur {userID} ?", "User suppression" => "Suppression d'un utilisateur", "Help translate My CoRe" => "Aidez à traduire My CoRe", "Help translate ownCloud" => "Aidez à traduire ownCloud", ); $PLURAL_FORMS = "nplurals=2; plural=(n > 1);";
Raise ValidationError properly in SignupForm
from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.core.validators import RegexValidator alphanumericu = RegexValidator( regex=r'^[0-9a-zA-Z_]*$', message='Only alphanumeric characters and underscore are allowed.') class SignupForm(UserCreationForm): username = forms.CharField(max_length=20, validators=[alphanumericu]) email = forms.EmailField(max_length=254, required=True) class Meta: model = User fields = ['email', 'username', ] def clean_email(self): error_message = 'An user with that email already exists' email = self.cleaned_data.get('email') if email and User.objects.filter(email=email).exists(): raise forms.ValidationError(error_message) return email
from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.core.validators import RegexValidator alphanumericu = RegexValidator( regex=r'^[0-9a-zA-Z_]*$', message='Only alphanumeric characters and underscore are allowed.') class SignupForm(UserCreationForm): username = forms.CharField(max_length=20, validators=[alphanumericu]) email = forms.EmailField(max_length=254, required=True) class Meta: model = User fields = ['email', 'username', ] def clean_email(self): error_message = 'An user with that email already exists' email = self.cleaned_data.get('email') if email and User.objects.filter(email=email).exists(): raise forms.ValidationError( self.error_messages[error_message], code='existing_email', ) return email
Use content instead of value for meta tags
<?php if ($content_type = Controller::$view->mime_type): ?> <?php if (!empty(Controller::$view->charset)) { $content_type .= ';charset=' . Controller::$view->charset; } ?> <meta http-equiv="Content-Type" content="<?php echo $content_type ?>"> <?php endif; ?> <?php if ($author = Backend::getConfig('application.author')): ?> <meta name="author" content="<?php echo $author ?>"> <?php endif; ?> <?php if (!empty($meta_description) || $meta_description = Backend::getConfig('application.description')): ?> <meta name="description" content="<?php echo $meta_description ?>"> <?php endif; ?> <meta name="generator" content="backend-php.net"> <?php if (!empty($keywords)): $keywords = is_array($keywords) ? implode(', ', $keywords) : $keywords; ?> <meta name="keywords" content="<?php echo $keywords ?>"> <?php endif; ?> <?php if (!empty($meta_values) && is_array($meta_values)): ?> <?php foreach($meta_values as $name => $value): ?> <meta property="<?php echo $name ?>" content="<?php echo $value ?>"/> <?php endforeach; ?> <?php endif; ?>
<?php if ($content_type = Controller::$view->mime_type): ?> <?php if (!empty(Controller::$view->charset)) { $content_type .= ';charset=' . Controller::$view->charset; } ?> <meta http-equiv="Content-Type" content="<?php echo $content_type ?>"> <?php endif; ?> <?php if ($author = Backend::getConfig('application.author')): ?> <meta name="author" content="<?php echo $author ?>"> <?php endif; ?> <?php if (!empty($meta_description) || $meta_description = Backend::getConfig('application.description')): ?> <meta name="description" content="<?php echo $meta_description ?>"> <?php endif; ?> <meta name="generator" content="backend-php.net"> <?php if (!empty($keywords)): $keywords = is_array($keywords) ? implode(', ', $keywords) : $keywords; ?> <meta name="keywords" content="<?php echo $keywords ?>"> <?php endif; ?> <?php if (!empty($meta_values) && is_array($meta_values)): ?> <?php foreach($meta_values as $name => $value): ?> <meta property="<?php echo $name ?>" value="<?php echo $value ?>"/> <?php endforeach; ?> <?php endif; ?>
Remove messages from Java VM
"""Handles all imports from jnius to prevent conflicts resulting from attempts to set JVM options while the VM is already running.""" import os import warnings import jnius_config if '-Xmx4g' not in jnius_config.get_options(): if not jnius_config.vm_running: jnius_config.add_options('-Xmx4g') else: warnings.warn("Couldn't set memory limit for Java VM because the VM " "is already running.") path_here = os.path.dirname(os.path.realpath(__file__)) cp = path_here + '/biopax/jars/paxtools.jar' cp_existing = os.environ.get('CLASSPATH') if cp_existing is not None: os.environ['CLASSPATH'] = cp + ':' + cp_existing else: os.environ['CLASSPATH'] = cp from jnius import autoclass, JavaException, cast
"""Handles all imports from jnius to prevent conflicts resulting from attempts to set JVM options while the VM is already running.""" import os import warnings import jnius_config if '-Xmx4g' not in jnius_config.get_options(): if not jnius_config.vm_running: jnius_config.add_options('-Xmx4g') else: warnings.warn("Couldn't set memory limit for Java VM because the VM " "is already running.") path_here = os.path.dirname(os.path.realpath(__file__)) cp = path_here + '/biopax/jars/paxtools.jar' cp_existing = os.environ.get('CLASSPATH') print 'before', os.environ.get('CLASSPATH') if cp_existing is not None: os.environ['CLASSPATH'] = cp + ':' + cp_existing else: os.environ['CLASSPATH'] = cp print 'after', os.environ.get('CLASSPATH') from jnius import autoclass, JavaException, cast
Create a random db for the tests each time.
import os from uuid import uuid4 from unittest import TestCase import webtest HERE = os.path.dirname(os.path.abspath(__file__)) class BaseWebTest(TestCase): """Base Web Test to test your cornice service. It setups the database before each test and delete it after. """ def setUp(self): self.db_name = os.environ['DB_NAME'] = 'daybed-tests-%s' % uuid4() self.app = webtest.TestApp("config:tests.ini", relative_to=HERE) self.db_server = self.app.app.registry.settings['db_server'] def tearDown(self): # Delete Test DB del self.db_server[self.db_name] def put_valid_definition(self): """Create a valid definition named "todo". """ # Put a valid definition self.app.put_json('/definitions/todo', self.valid_definition, headers=self.headers)
import os from unittest import TestCase import webtest HERE = os.path.dirname(os.path.abspath(__file__)) class BaseWebTest(TestCase): """Base Web Test to test your cornice service. It setups the database before each test and delete it after. """ def setUp(self): self.app = webtest.TestApp("config:tests.ini", relative_to=HERE) self.db_server = self.app.app.registry.settings['db_server'] def tearDown(self): # Delete Test DB del self.db_server[self.app.app.registry.settings['db_name']] def put_valid_definition(self): """Create a valid definition named "todo". """ # Put a valid definition self.app.put_json('/definitions/todo', self.valid_definition, headers=self.headers)
Change feedPaperPage handler to work with Express 4.x .
function feedPaperPage(req, res) { res.render('feedpaper.html', { categories: exports.cache.categoryList }, function (err, html) { res.send(html); } ); } function feedData(req, res) { exports.cache.getFeed(req.params.feedId, function (err, articles) { if (err) { res.status(500).send(err.message); } else { res.json(articles); } }); } function articleData(req, res) { var url = req.url.match(/http.+$/); exports.cache.getArticle(url, function (err, article) { if (err) { res.status(500).send(err.message); } else { res.json(article); } }); } exports.feedPaperPage = feedPaperPage; exports.feedData = feedData; exports.articleData = articleData;
function feedPaperPage(req, res) { res.render('feedpaper.html', { layout: 'layout', locals: { categories: exports.cache.categoryList } }); } function feedData(req, res) { exports.cache.getFeed(req.params.feedId, function (err, articles) { if (err) { res.status(500).send(err.message); } else { res.json(articles); } }); } function articleData(req, res) { var url = req.url.match(/http.+$/); exports.cache.getArticle(url, function (err, article) { if (err) { res.status(500).send(err.message); } else { res.json(article); } }); } exports.feedPaperPage = feedPaperPage; exports.feedData = feedData; exports.articleData = articleData;
Check in PublishServiceProviderLoginEvent() stub function.
package eventnotifier import ( "net/http" "sync" "github.com/Symantec/Dominator/lib/log" "github.com/Symantec/keymaster/proto/eventmon" ) type EventNotifier struct { logger log.DebugLogger mutex sync.Mutex // Protected by lock. transmitChannels map[chan<- eventmon.EventV0]chan<- eventmon.EventV0 } func New(logger log.DebugLogger) *EventNotifier { return newEventNotifier(logger) } func (n *EventNotifier) PublishAuthEvent(authType, username string) { n.publishAuthEvent(authType, username) } func (n *EventNotifier) PublishServiceProviderLoginEvent(url string) { } func (n *EventNotifier) PublishSSH(cert []byte) { n.publishCert(eventmon.EventTypeSSHCert, cert) } func (n *EventNotifier) PublishWebLoginEvent(username string) { n.publishWebLoginEvent(username) } func (n *EventNotifier) PublishX509(cert []byte) { n.publishCert(eventmon.EventTypeX509Cert, cert) } func (n *EventNotifier) ServeHTTP(w http.ResponseWriter, req *http.Request) { n.serveHTTP(w, req) }
package eventnotifier import ( "net/http" "sync" "github.com/Symantec/Dominator/lib/log" "github.com/Symantec/keymaster/proto/eventmon" ) type EventNotifier struct { logger log.DebugLogger mutex sync.Mutex // Protected by lock. transmitChannels map[chan<- eventmon.EventV0]chan<- eventmon.EventV0 } func New(logger log.DebugLogger) *EventNotifier { return newEventNotifier(logger) } func (n *EventNotifier) PublishAuthEvent(authType, username string) { n.publishAuthEvent(authType, username) } func (n *EventNotifier) PublishSSH(cert []byte) { n.publishCert(eventmon.EventTypeSSHCert, cert) } func (n *EventNotifier) PublishWebLoginEvent(username string) { n.publishWebLoginEvent(username) } func (n *EventNotifier) PublishX509(cert []byte) { n.publishCert(eventmon.EventTypeX509Cert, cert) } func (n *EventNotifier) ServeHTTP(w http.ResponseWriter, req *http.Request) { n.serveHTTP(w, req) }
Update to use unique_name for task update
# Download the helper library from https://www.twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' auth_token = 'your_auth_token' client = Client(account_sid, auth_token) phrases = [ 'hello', 'hi', 'Hello', 'Hi there' ] # Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list for phrase in phrases: sample = client.autopilot \ .assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \ .tasks('hello-world') \ .samples \ .create(language='en-us', tagged_text=phrase) print(sample.sid)
# Download the helper library from https://www.twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' auth_token = 'your_auth_token' client = Client(account_sid, auth_token) phrases = [ 'hello', 'hi', 'Hello', 'Hi there' ] # Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list # Replace 'UDXXX...' with the SID for the task you just created. for phrase in phrases: sample = client.autopilot \ .assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \ .tasks('UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \ .samples \ .create(language='en-us', tagged_text=phrase) print(sample.sid)
Fix issue when redux dev tool extension is not available
import {createStore, applyMiddleware, compose} from 'redux'; import { routerMiddleware } from 'react-router-redux'; import throttle from 'lodash/throttle'; import recipes from './data/recipes'; import { loadState, saveState } from './localStorage'; import rootReducer from './reducers'; const devtools = window.devToolsExtension || (() => f => f); export default function configureStore(history, initialState) { const middlewares = [ routerMiddleware(history), ]; const enhancers = [ applyMiddleware(...middlewares), devtools(), ]; const localState = loadState() || recipes; const store = createStore( rootReducer, initialState || localState, compose(...enhancers) ); store.subscribe(throttle(() => { const state = store.getState(); saveState({ recipes: state.recipes, likes: state.likes }); }, 1000)); if (module.hot && process.env.NODE_ENV !== 'production') { // Enable Webpack hot module replacement for reducers module.hot.accept('./reducers', () => { const nextReducer = require('./reducers'); // eslint-disable-line global-require store.replaceReducer(nextReducer); }); } return store; }
import {createStore, applyMiddleware, compose} from 'redux'; import { routerMiddleware } from 'react-router-redux'; import throttle from 'lodash/throttle'; import recipes from './data/recipes'; import { loadState, saveState } from './localStorage'; import rootReducer from './reducers'; const devtools = window.devToolsExtension || (f => f); export default function configureStore(history, initialState) { const middlewares = [ routerMiddleware(history), ]; const enhancers = [ applyMiddleware(...middlewares), devtools(), ]; const localState = loadState() || recipes; const store = createStore( rootReducer, initialState || localState, compose(...enhancers) ); store.subscribe(throttle(() => { const state = store.getState(); saveState({ recipes: state.recipes, likes: state.likes }); }, 1000)); if (module.hot && process.env.NODE_ENV !== 'production') { // Enable Webpack hot module replacement for reducers module.hot.accept('./reducers', () => { const nextReducer = require('./reducers'); // eslint-disable-line global-require store.replaceReducer(nextReducer); }); } return store; }
Add `event.preventDefault()` call in UJS action handlers.
/** * Assigns handlers/listeners for `[data-action]` links. * * Actions associated with a link will be invoked via Wire with the jQuery * event object as an argument. **/ 'use strict'; /*global NodecaLoader, N, window*/ var $ = window.jQuery; $(function () { ['click', 'submit', 'input'].forEach(function (action) { var eventName = action + '.nodeca.data-api' , attribute = '[data-on-' + action + ']'; $('body').on(eventName, attribute, function (event) { var apiPath = $(this).data('on-' + action); NodecaLoader.loadAssets(apiPath.split('.').shift(), function () { if (N.wire.has(apiPath)) { N.wire.emit(apiPath, event); } else { N.logger.error('Unknown client Wire handler: %s', apiPath); } }); event.preventDefault(); return false; }); }); });
/** * Assigns handlers/listeners for `[data-action]` links. * * Actions associated with a link will be invoked via Wire with the jQuery * event object as an argument. **/ 'use strict'; /*global NodecaLoader, N, window*/ var $ = window.jQuery; $(function () { ['click', 'submit', 'input'].forEach(function (action) { var eventName = action + '.nodeca.data-api' , attribute = '[data-on-' + action + ']'; $('body').on(eventName, attribute, function (event) { var apiPath = $(this).data('on-' + action); NodecaLoader.loadAssets(apiPath.split('.').shift(), function () { if (N.wire.has(apiPath)) { N.wire.emit(apiPath, event); } else { N.logger.error('Unknown client Wire handler: %s', apiPath); } }); return false; }); }); });
Disable vanilla armours is turned off by default
package teamOD.armourReborn.common.core.handler; import java.io.File; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.config.Property; public final class ConfigHandler { public static Configuration config ; public static boolean generateOre = true ; public static boolean disableVanillaArmours = false ; public static void init (File configFile) { config = new Configuration (configFile) ; config.load() ; load() ; config.save() ; } public static void load () { String desc ; desc = "Set this to false to disable the world generation of this mod's added ores." + "\n" ; desc += "Make sure your pack has an alternative way to obtain the following ores if disabled:" + "\n" ; desc += "Copper Ore, Aluminum Ore" ; generateOre = loadPropBool ("enable.worldGen", desc, generateOre) ; desc = "If set to true, all vanilla armours will not provide any protection to the user" ; disableVanillaArmours = loadPropBool ("disable.vanillaArmour", desc, disableVanillaArmours) ; } private static boolean loadPropBool(String propName, String desc, boolean default_) { Property prop = config.get(Configuration.CATEGORY_GENERAL, propName, default_); prop.setComment(desc); return prop.getBoolean(default_); } }
package teamOD.armourReborn.common.core.handler; import java.io.File; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.config.Property; public final class ConfigHandler { public static Configuration config ; public static boolean generateOre = true ; public static boolean disableVanillaArmours = true ; public static void init (File configFile) { config = new Configuration (configFile) ; config.load() ; load() ; config.save() ; } public static void load () { String desc ; desc = "Set this to false to disable the world generation of this mod's added ores." + "\n" ; desc += "Make sure your pack has an alternative way to obtain the following ores if disabled:" + "\n" ; desc += "Copper Ore, Aluminum Ore" ; generateOre = loadPropBool ("enable.worldGen", desc, generateOre) ; desc = "If set to true, all vanilla armours will not provide any protection to the user" ; disableVanillaArmours = loadPropBool ("disable.vanillaArmour", desc, disableVanillaArmours) ; } private static boolean loadPropBool(String propName, String desc, boolean default_) { Property prop = config.get(Configuration.CATEGORY_GENERAL, propName, default_); prop.setComment(desc); return prop.getBoolean(default_); } }
Add usage and help commands
/* Miscellaneous commands */ Settings.addPermissions(['pick', 'randomanswer', 'usage', 'help']); exports.commands = { choose: 'pick', pick: function (arg, by, room, cmd) { var choices = arg.split(","); choices = choices.filter(function (i) {return (toId(i) !== '');}); if (choices.length < 2) return this.pmReply(this.trad('err')); var choice = choices[Math.floor(Math.random() * choices.length)]; if (!this.can('pick') || this.roomType === 'pm') { this.pmReply(Tools.stripCommands(choice)); } else { this.reply(Tools.stripCommands(choice)); } }, '8ball': 'randomanswer', helix: 'randomanswer', randomanswer: function (arg, user, room) { if (room === user) return false; var text = ''; var rand = ~~(20 * Math.random()); var answers = this.trad('answers'); text += (answers[rand] || answers[0]); this.restrictReply(text, 'randomanswer'); }, usagestats: 'usage', usage: function (arg, user, room) { this.restrictReply('http://www.smogon.com/stats/', 'usage'); }, guide: 'help', botguide: 'help', help: function (arg, user, room) { this.restrictReply('https://github.com/Ecuacion/Pokemon-Showdown-Node-Bot/blob/master/commands/README.md', 'help'); } };
/* Miscellaneous commands */ Settings.addPermissions(['pick', 'randomanswer']); exports.commands = { choose: 'pick', pick: function (arg, by, room, cmd) { var choices = arg.split(","); choices = choices.filter(function (i) {return (toId(i) !== '');}); if (choices.length < 2) return this.pmReply(this.trad('err')); var choice = choices[Math.floor(Math.random() * choices.length)]; if (!this.can('pick') || this.roomType === 'pm') { this.pmReply(Tools.stripCommands(choice)); } else { this.reply(Tools.stripCommands(choice)); } }, '8ball': 'randomanswer', helix: 'randomanswer', randomanswer: function (arg, user, room) { if (room === user) return false; var text = ''; var rand = ~~(20 * Math.random()); var answers = this.trad('answers'); text += (answers[rand] || answers[0]); this.restrictReply(text, 'randomanswer'); } };
Bring back String u function
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Sylius\Component\Core\Formatter; use Behat\Transliterator\Transliterator; use function Symfony\Component\String\u; final class StringInflector { public static function codeToName(string $value): string { return ucfirst(str_replace('_', ' ', $value)); } public static function nameToCode(string $value): string { return str_replace([' ', '-', '\''], '_', $value); } public static function nameToSlug(string $value): string { return str_replace(['_'], '-', self::nameToLowercaseCode(Transliterator::transliterate($value))); } public static function nameToLowercaseCode(string $value): string { return strtolower(self::nameToCode($value)); } public static function nameToUppercaseCode(string $value): string { return strtoupper(self::nameToCode($value)); } public static function nameToCamelCase(string $value): string { return (string) u($value)->camel(); } private function __construct() { } }
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Sylius\Component\Core\Formatter; use Behat\Transliterator\Transliterator; final class StringInflector { public static function codeToName(string $value): string { return ucfirst(str_replace('_', ' ', $value)); } public static function nameToCode(string $value): string { return str_replace([' ', '-', '\''], '_', $value); } public static function nameToSlug(string $value): string { return str_replace(['_'], '-', self::nameToLowercaseCode(Transliterator::transliterate($value))); } public static function nameToLowercaseCode(string $value): string { return strtolower(self::nameToCode($value)); } public static function nameToUppercaseCode(string $value): string { return strtoupper(self::nameToCode($value)); } public static function nameToCamelCase(string $value): string { return lcfirst(str_replace(' ', '', ucwords(preg_replace('/[^a-zA-Z0-9\x7f-\xff]++/', ' ', $value)))); } private function __construct() { } }
Fix mock Qt objects again
has_qt = True try: from matplotlib.backends.qt_compat import QtGui, QtCore, QtWidgets except ImportError: try: from matplotlib.backends.qt4_compat import QtGui, QtCore QtWidgets = QtGui except ImportError: # Mock objects class QtGui_cls(object): QMainWindow = object QDialog = object QWidget = object class QtCore_cls(object): class Qt(object): TopDockWidgetArea = None BottomDockWidgetArea = None LeftDockWidgetArea = None RightDockWidgetArea = None def Signal(self, *args, **kwargs): pass QtGui = QtWidgets = QtGui_cls() QtCore = QtCore_cls() has_qt = False Qt = QtCore.Qt Signal = QtCore.Signal
has_qt = True try: from matplotlib.backends.qt_compat import QtGui, QtCore, QtWidgets except ImportError: try: from matplotlib.backends.qt4_compat import QtGui, QtCore QtWidgets = QtGui except ImportError: # Mock objects class QtGui(object): QMainWindow = object QDialog = object QWidget = object class QtCore_cls(object): class Qt(object): TopDockWidgetArea = None BottomDockWidgetArea = None LeftDockWidgetArea = None RightDockWidgetArea = None def Signal(self, *args, **kwargs): pass QWidget = object QtCore = QtWidgets = QtCore_cls() has_qt = False Qt = QtCore.Qt Signal = QtCore.Signal
Reduce the size of log_name so it fits within mysql's limit.
from database import db from conversions import datetime_from_str class LogEntry(db.Model): id = db.Column(db.Integer, primary_key=True) timestamp = db.Column(db.DateTime, index=True) server = db.Column(db.String(100), index=True) log_name = db.Column(db.String(760), index=True) message = db.Column(db.Text(), nullable=True) def __init__(self, timestamp, server, log_name, message): self.timestamp = datetime_from_str(timestamp) self.server = server self.log_name = log_name self.message = message def to_dict(self): return { 'timestamp': self.timestamp, 'server': self.server, 'log_name': self.log_name, 'message': self.message, }
from database import db from conversions import datetime_from_str class LogEntry(db.Model): id = db.Column(db.Integer, primary_key=True) timestamp = db.Column(db.DateTime, index=True) server = db.Column(db.String(100), index=True) log_name = db.Column(db.String(1000), index=True) message = db.Column(db.Text(), nullable=True) def __init__(self, timestamp, server, log_name, message): self.timestamp = datetime_from_str(timestamp) self.server = server self.log_name = log_name self.message = message def to_dict(self): return { 'timestamp': self.timestamp, 'server': self.server, 'log_name': self.log_name, 'message': self.message, }
Update the PyPI version to 0.2.15.
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except: return '' setup( name='todoist-python', version='0.2.15', packages=['todoist', 'todoist.managers'], author='Doist Team', author_email='info@todoist.com', license='BSD', description='todoist-python - The official Todoist Python API library', long_description = read('README.md'), install_requires=[ 'requests', ], # see here for complete list of classifiers # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=( 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', ), )
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except: return '' setup( name='todoist-python', version='0.2.14', packages=['todoist', 'todoist.managers'], author='Doist Team', author_email='info@todoist.com', license='BSD', description='todoist-python - The official Todoist Python API library', long_description = read('README.md'), install_requires=[ 'requests', ], # see here for complete list of classifiers # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=( 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', ), )
Add a test for the __call__ method of the APIRequest class.
"""Test the api_requests module.""" from pytest import mark from gobble.api_requests import APIRequest SIMPLE = ('foo.bar', dict(), ['https://foo.bar']) LOCAL = ('0.0.0.0', dict(port=5000, schema='http'), ['http://0.0.0.0:5000']) LONG = ( 'foo.bar', dict( path=['spam', 'eggs'], query={'foo': 'bar', 'spam': 'eggs'} ), [ 'https://foo.bar/spam/eggs?spam=eggs&foo=bar', 'https://foo.bar/spam/eggs?foo=bar&spam=eggs' ] ) TEST_CASES = [SIMPLE, LONG, LOCAL] # noinspection PyShadowingNames @mark.parametrize('host, parameters, urls', TEST_CASES) def test_url(host, parameters, urls): assert APIRequest(host, **parameters).url in urls def test_call(): request = APIRequest('google.com') assert request().status_code == 200
"""Test the api_requests module.""" from pytest import mark from gobble.api_requests import APIRequest SIMPLE = ('foo.bar', dict(), ['https://foo.bar']) LOCAL = ('0.0.0.0', dict(port=5000, schema='http'), ['http://0.0.0.0:5000']) LONG = ( 'foo.bar', dict( path=['spam', 'eggs'], query={'foo': 'bar', 'spam': 'eggs'} ), [ 'https://foo.bar/spam/eggs?spam=eggs&foo=bar', 'https://foo.bar/spam/eggs?foo=bar&spam=eggs' ] ) TEST_CASES = [SIMPLE, LONG, LOCAL] # noinspection PyShadowingNames @mark.parametrize('host, parameters, urls', TEST_CASES) def test_url(host, parameters, urls): assert APIRequest(host, **parameters).url in urls
Fix wrong phone validation rule
<?php /* * NOTICE OF LICENSE * * Part of the Rinvex Fort Package. * * This source file is subject to The MIT License (MIT) * that is bundled with this package in the LICENSE file. * * Package: Rinvex Fort Package * License: The MIT License (MIT) * Link: https://rinvex.com */ namespace Rinvex\Fort\Http\Requests\Frontend; class PhoneVerificationSendRequest extends PhoneVerificationRequest { /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return $this->isMethod('post') ? [ 'phone' => 'required|numeric|exists:'.config('rinvex.fort.tables.users').',phone', 'method' => 'required', ] : []; } }
<?php /* * NOTICE OF LICENSE * * Part of the Rinvex Fort Package. * * This source file is subject to The MIT License (MIT) * that is bundled with this package in the LICENSE file. * * Package: Rinvex Fort Package * License: The MIT License (MIT) * Link: https://rinvex.com */ namespace Rinvex\Fort\Http\Requests\Frontend; use Illuminate\Support\Facades\Auth; class PhoneVerificationSendRequest extends PhoneVerificationRequest { /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $user = Auth::guard()->user() ?: Auth::guard()->attemptUser(); return $this->isMethod('post') ? [ 'phone' => 'required|numeric|exists:'.config('rinvex.fort.tables.users').',phone,id,'.$user->id.',phone_verified,1', 'method' => 'required', ] : []; } }
Add pushHamburgerIcon and remove .scroll-icon
$(document).ready(function() { $(window).scroll(function() { if ($(this).scrollTop() > 1) { /* add header animation */ $('header').addClass('scroll-nav scroll-animation'); /* add hamburger icon trigger adjustment */ $('.hamburgerTrigger').addClass('pushHamburgerIcon'); } else { /* remove header animation */ $('header').removeClass('scroll-nav').addClass('scroll-animation'); /* remove hamburger icon trigger adjustment */ $('.hamburgerTrigger').removeClass('pushHamburgerIcon').addClass('scroll-animation'); } }); });
$(document).ready(function() { $(window).scroll(function() { if ($(this).scrollTop() > 1) { /* add header animation */ $('header').addClass('scroll-nav scroll-animation'); /* add hamburger icon animation */ $('.hamburger-icon').addClass('scroll-icon'); } else { /* remove header animation */ $('header').removeClass('scroll-nav').addClass('scroll-animation'); /* remove hamburger icon animation */ $('.hamburger-icon').removeClass('scroll-icon').addClass('scroll-animation'); } }); });
Create the OptionsClientFactory without the Name
<?php /* * This file is part of the wp-magnify/magnify-elasticsearch package. * * (c) Christopher Davis <http://christopherdavis.me> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Magnify\Elasticsearch as ES; /** * Hooked into the `magnify_loaded` to initialize the driver. * * @param $magnify the magnify application class. * @return void */ function magnify_elasticsearch_load(Magnify $magnify) { foreach (magnify_elasticsearch_drivers() as $d) { $magnify["elasticsearch.{$d}.factory"] = function ($magnify) use ($d) { return new ES\OptionsClientFactory($magnify['logger'], $d); }; $magnify["elasticsearch.{$d}"] = function ($magnify) use ($d) { return new ES\ElasticsearchDriver( $magnify["elasticsearch.{$d}.factory"], $d ); }; $magnify->registerDriver($magnify["elasticsearch.{$d}"]); } } function magnify_elasticsearch_drivers() { return magnify_filter('elasticsearch_drivers', ['default']); }
<?php /* * This file is part of the wp-magnify/magnify-elasticsearch package. * * (c) Christopher Davis <http://christopherdavis.me> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Magnify\Elasticsearch as ES; /** * Hooked into the `magnify_loaded` to initialize the driver. * * @param $magnify the magnify application class. * @return void */ function magnify_elasticsearch_load(Magnify $magnify) { foreach (magnify_elasticsearch_drivers() as $d) { $magnify["elasticsearch.{$d}.factory"] = function ($magnify) use ($d) { return new ES\OptionsClientFactory($magnify['logger'], sprintf( 'magnify_elasticsearch_%s', $d )); }; $magnify["elasticsearch.{$d}"] = function ($magnify) use ($d) { return new ES\ElasticsearchDriver( $magnify["elasticsearch.{$d}.factory"], $d ); }; $magnify->registerDriver($magnify["elasticsearch.{$d}"]); } } function magnify_elasticsearch_drivers() { return magnify_filter('elasticsearch_drivers', ['default']); }
Add special handling for NotImplementedError If the function called by run_command() raises a NotImplementedError, don't print the full stacktrace. Do a mild amount of custom formatting, then exit with status 1 (failure).
from __future__ import print_function import sys from globus_cli.parser.shared_parser import GlobusCLISharedParser from globus_cli.parser.command_tree import build_command_tree def _gen_parser(): """ Produces a top-level argument parser built out of all of the various subparsers for different services. """ # create the top parser and give it subparsers top_level_parser = GlobusCLISharedParser() subparsers = top_level_parser.add_subparsers( title='Commands', parser_class=GlobusCLISharedParser, metavar='') build_command_tree(subparsers) # return the created parser in all of its glory return top_level_parser def _load_args(): """ Load commandline arguments, and do any necessary post-processing. """ parser = _gen_parser() args = parser.parse_args() return args def run_command(): """ Whatever arguments were loaded, they set a function to be invoked on the arguments themselves -- somewhat circular, but a nifty way of passing the args to a function that this module doesn't even know about """ args = _load_args() try: args.func(args) except NotImplementedError as e: print('NotImplementedError: {}'.format(e.message), file=sys.stderr) sys.exit(1)
from globus_cli.parser.shared_parser import GlobusCLISharedParser from globus_cli.parser.command_tree import build_command_tree def _gen_parser(): """ Produces a top-level argument parser built out of all of the various subparsers for different services. """ # create the top parser and give it subparsers top_level_parser = GlobusCLISharedParser() subparsers = top_level_parser.add_subparsers( title='Commands', parser_class=GlobusCLISharedParser, metavar='') build_command_tree(subparsers) # return the created parser in all of its glory return top_level_parser def _load_args(): """ Load commandline arguments, and do any necessary post-processing. """ parser = _gen_parser() args = parser.parse_args() return args def run_command(): """ Whatever arguments were loaded, they set a function to be invoked on the arguments themselves -- somewhat circular, but a nifty way of passing the args to a function that this module doesn't even know about """ args = _load_args() args.func(args)
Use Zoltan's type of fix
<?php /** * Decoded bencode string, representing an ordered set of bytes. * * @package PHPTracker * @subpackage Bencode */ class PHPTracker_Bencode_Value_String extends PHPTracker_Bencode_Value_Abstract { /** * Intializing the object with its parsed value. * * @throws PHPTracker_Bencode_Error_InvalidType In the value is not a string. * @param string $value */ public function __construct( $value ) { if ( !is_string( $value ) ) { throw new PHPTracker_Bencode_Error_InvalidType( "Invalid string value: " . var_export( $value, true ) ); } $this->value = $value; } /** * Convert the object back to a bencoded string when used as string. */ public function __toString() { return strlen( $this->value ) . ":" . $this->value; } /** * Represent the value of the object as PHP scalar. */ public function represent() { return $this->value; } }
<?php /** * Decoded bencode string, representing an ordered set of bytes. * * @package PHPTracker * @subpackage Bencode */ class PHPTracker_Bencode_Value_String extends PHPTracker_Bencode_Value_Abstract { /** * Intializing the object with its parsed value. * * @throws PHPTracker_Bencode_Error_InvalidType In the value is not a string. * @param string $value */ public function __construct( $value ) { if ( !is_string( $value ) ) { $type = gettype($value); throw new PHPTracker_Bencode_Error_InvalidType( "Invalid string value: $type" ); } $this->value = $value; } /** * Convert the object back to a bencoded string when used as string. */ public function __toString() { return strlen( $this->value ) . ":" . $this->value; } /** * Represent the value of the object as PHP scalar. */ public function represent() { return $this->value; } }
Fix bustage for script calls
import argparse import os import json import sys def parse_args(argv): parser = argparse.ArgumentParser("Test") parser.add_argument("--port", "-p", type=int, default=8080, help="Specify the port recordpeeker runs on") parser.add_argument("--verbosity", "-v", default=0, type=int, choices=[0,1,2,3], help="Spews more info. 1: prints the path of each request. 2: prints the content of unknown requests. 3: Also print the content of known requests.") return parser.parse_args(argv[1:]) def launch(): script = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'mitmdump_input.py') # This is just here so that --help returns the arguments args = parse_args(sys.argv) if sys.argv[1:]: arglist = " ".join(sys.argv[1:]) scriptargs = '-s "{0}" "{1}"'.format(script, arglist) else: scriptargs = '-s "{0}"'.format(script) sys.argv = [sys.argv[0], scriptargs, '-q'] from libmproxy.main import mitmdump mitmdump() if __name__ == '__main__': launch()
import argparse import os import json import sys def parse_args(argv): parser = argparse.ArgumentParser("Test") parser.add_argument("--port", "-p", type=int, default=8080, help="Specify the port recordpeeker runs on") parser.add_argument("--verbosity", "-v", default=0, type=int, choices=[0,1,2,3], help="Spews more info. 1: prints the path of each request. 2: prints the content of unknown requests. 3: Also print the content of known requests.") return parser.parse_args(argv[1:]) def launch(): script = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'mitmdump_input.py') # This is just here so that --help returns the arguments args = parse_args(sys.argv) arglist = " ".join(sys.argv[1:]) sys.argv = [sys.argv[0], '-s "{0}" "{1}"'.format(script, arglist), '-q'] from libmproxy.main import mitmdump mitmdump() if __name__ == '__main__': launch()
Make the image path work even if it's in a subfolder
<?php include( '../config.php' ); $url = 'http://www.myepisodes.com/rss.php?feed=mylist&uid=mirrorer&pwdmd5=' . $myEpisodes; $data = file_get_contents( $url ); $shows = new SimpleXMLElement( $data ); $items = array(); foreach( $shows->channel->item as $show ): preg_match( '#\[(.+?)\]\[(.+?)\]\[(.+?)\]\[(.+?)\]#mis', $show->title, $matches ); $dateString = date( 'Y-m-d', strtotime( $matches[ 4 ] ) ); if( !isset( $items[ $dateString ] ) ): $items[ $dateString ] = array(); endif; $item = array(); $item[ 'image' ] = $_SERVER[ 'REQUEST_URI' ] . 'images/?query=' . preg_replace( '#\s+#mis', '-', strtolower( trim( $matches[ 1 ] ) ) ); $items[ $dateString ][] = $item; endforeach; header( 'Access-Control-Allow-Origin: *' ); header( 'Content-Type: application/json' ); echo json_encode( $items );
<?php include( '../config.php' ); $url = 'http://www.myepisodes.com/rss.php?feed=mylist&uid=mirrorer&pwdmd5=' . $myEpisodes; $data = file_get_contents( $url ); $shows = new SimpleXMLElement( $data ); $items = array(); foreach( $shows->channel->item as $show ): preg_match( '#\[(.+?)\]\[(.+?)\]\[(.+?)\]\[(.+?)\]#mis', $show->title, $matches ); $dateString = date( 'Y-m-d', strtotime( $matches[ 4 ] ) ); if( !isset( $items[ $dateString ] ) ): $items[ $dateString ] = array(); endif; $item = array(); $item[ 'image' ] = '/images/?query=' . preg_replace( '#\s+#mis', '-', strtolower( trim( $matches[ 1 ] ) ) ); $items[ $dateString ][] = $item; endforeach; header( 'Access-Control-Allow-Origin: *' ); header( 'Content-Type: application/json' ); echo json_encode( $items );
Revert "adding JSON to the list of extensions that should be compressed" This reverts commit 71aeb2fb86f80caf25d565e79260e3441ebd343a.
'use strict'; var es = require('event-stream'), path = require('path'), zlib = require('zlib'); var compressibles = [ '.js', '.css', '.html' ]; function isCompressibleFile( file ) { var ext = path.extname( file.path ).toLowerCase(); return ( compressibles.indexOf( ext ) > -1 ); } module.exports = function() { return es.map( function( file, cb ) { if( !isCompressibleFile( file ) ) { cb( null, file ); return; } zlib.gzip( file.contents, function( err, result ) { if( err ) { cb( err, null ); return; } file.path += '.gz'; file.contents = result; cb( null, file ); } ); } ); }; module.exports._isCompressibleFile = isCompressibleFile;
'use strict'; var es = require('event-stream'), path = require('path'), zlib = require('zlib'); var compressibles = [ '.js', '.json', '.css', '.html' ]; function isCompressibleFile( file ) { var ext = path.extname( file.path ).toLowerCase(); return ( compressibles.indexOf( ext ) > -1 ); } module.exports = function() { return es.map( function( file, cb ) { if( !isCompressibleFile( file ) ) { cb( null, file ); return; } zlib.gzip( file.contents, function( err, result ) { if( err ) { cb( err, null ); return; } file.path += '.gz'; file.contents = result; cb( null, file ); } ); } ); }; module.exports._isCompressibleFile = isCompressibleFile;
Use goutis tracer over plain statsd connection
package thrift import ( "log" "os" "time" "github.com/upfluence/goutils/tracing" "github.com/upfluence/goutils/tracing/noop" "github.com/upfluence/goutils/tracing/statsd" ) var ( Metrics *Metric = NewMetric(os.Getenv("STATSD_URL")) ) type Metric struct { tracer tracing.Tracer } func NewMetric(statsdURL string) *Metric { if statsdURL != "" { if t, err := statsd.NewTracer(statsdURL, ""); err != nil { log.Println("statsd dial: %s", err.Error()) } else { return &Metric{t} } } return &Metric{&noop.Tracer{}} } func (m *Metric) Incr(metricName string) { m.tracer.Count(metricName, 1) } func (m *Metric) Timing(metricName string, duration time.Duration) { m.tracer.Timing(metricName, duration) }
package thrift import ( "github.com/cyberdelia/statsd" "log" "os" ) var ( Metrics *Metric = NewMetric(os.Getenv("STATSD_URL")) ) type Metric struct { client *statsd.Client } func NewMetric(statsdURL string) *Metric { var client *statsd.Client var err error if statsdURL != "" { client, err = statsd.Dial(statsdURL) if err != nil { log.Println(err.Error()) return nil } } return &Metric{client} } func (m *Metric) Incr(metricName string) { if m.client != nil { m.client.Increment(metricName, 1, 1) } } func (m *Metric) Timing(metricName string, duration int64) { if m.client != nil { m.client.Timing(metricName, int(duration/1000000), 1) } }
Remove + character from generated URLs
# -*- coding: utf-8 -*- import re _strip_re = re.compile(ur'[\'"`‘’“”′″‴]+') _punctuation_re = re.compile(ur'[\t +!#$%&()*\-/<=>?@\[\\\]^_{|}:;,.…‒–—―]+') def makename(text, delim=u'-', maxlength=50, filter=None): u""" Generate a Unicode name slug. >>> makename('This is a title') u'this-is-a-title' >>> makename('Invalid URL/slug here') u'invalid-url-slug-here' >>> makename('this.that') u'this-that' >>> makename("How 'bout this?") u'how-bout-this' >>> makename(u"How’s that?") u'hows-that' >>> makename(u'K & D') u'k-d' >>> makename('billion+ pageviews') u'billion-pageviews' """ return unicode(delim.join([_strip_re.sub('', x) for x in _punctuation_re.split(text.lower()) if x != '']))
# -*- coding: utf-8 -*- import re _strip_re = re.compile(ur'[\'"`‘’“”′″‴]+') _punctuation_re = re.compile(ur'[\t !#$%&()*\-/<=>?@\[\\\]^_{|}:;,.…‒–—―]+') def makename(text, delim=u'-', maxlength=50, filter=None): u""" Generate a Unicode name slug. >>> makename('This is a title') u'this-is-a-title' >>> makename('Invalid URL/slug here') u'invalid-url-slug-here' >>> makename('this.that') u'this-that' >>> makename("How 'bout this?") u'how-bout-this' >>> makename(u"How’s that?") u'hows-that' >>> makename(u'K & D') u'k-d' """ return unicode(delim.join([_strip_re.sub('', x) for x in _punctuation_re.split(text.lower()) if x != '']))
Allow currentUser.username, etc. from within templates (rather than currentUser.user.username)
package com.peterphi.std.guice.web.rest.templating.thymeleaf; import com.google.inject.Provider; import com.peterphi.std.guice.common.auth.iface.CurrentUser; import org.joda.time.DateTime; import java.time.Instant; import java.util.Date; public class ThymeleafCurrentUserUtils { private final Provider<CurrentUser> provider; public ThymeleafCurrentUserUtils(final Provider<CurrentUser> provider) { this.provider = provider; } public boolean hasRole(String role) { return getUser().hasRole(role); } public String getAuthType() { return getUser().getAuthType(); } public CurrentUser getUser() { return provider.get(); } public String getName() { return getUser().getName(); } public String getUsername() { return getUser().getUsername(); } public DateTime getExpires() { return getUser().getExpires(); } public boolean isAnonymous() { return getUser().isAnonymous(); } public String format(DateTime date) { return getUser().format(date); } public String format(Date date) { return getUser().format(date); } public String format(Instant date) { return getUser().format(date); } public String format(Long date) { if (date == null) return format((DateTime) null); else return format(new DateTime(date)); } }
package com.peterphi.std.guice.web.rest.templating.thymeleaf; import com.google.inject.Provider; import com.peterphi.std.guice.common.auth.iface.CurrentUser; import org.joda.time.DateTime; import java.time.Instant; import java.util.Date; public class ThymeleafCurrentUserUtils { private final Provider<CurrentUser> provider; public ThymeleafCurrentUserUtils(final Provider<CurrentUser> provider) { this.provider = provider; } public boolean hasRole(String role) { return getUser().hasRole(role); } public String getAuthType() { return getUser().getAuthType(); } public CurrentUser getUser() { return provider.get(); } public boolean isAnonymous() { return getUser().isAnonymous(); } public String format(DateTime date) { return getUser().format(date); } public String format(Date date) { return getUser().format(date); } public String format(Instant date) { return getUser().format(date); } public String format(Long date) { if (date == null) return format((DateTime) null); else return format(new DateTime(date)); } }
[Chore] Remove unneccessary paren in flag review statement
const reviews = (state=[], action) => { switch (action.type) { case 'ADD_REVIEW': return [ ...state, { id: action.id, reviewer: action.reviewer, text: action.text, rating: action.rating, flag: false } ] case 'DELETE_REVIEW': return state.filter(review => review.id !== action.id); case 'FLAG_REVIEW': return state.map(review => review.id === action.id ? Object.assign({}, review, { flag: action.flag}): review) case 'RATE_REVIEW': return state.map(review => review.id === action.id ? [...review, {rating: action.rating}]: review) default: return state; } } export default reviews;
const reviews = (state=[], action) => { switch (action.type) { case 'ADD_REVIEW': return [ ...state, { id: action.id, reviewer: action.reviewer, text: action.text, rating: action.rating, flag: false } ] case 'DELETE_REVIEW': return state.filter(review => review.id !== action.id); case 'FLAG_REVIEW': return state.map((review, index) => review.id === action.id ? Object.assign({}, review, { flag: !action.flag}): review) case 'RATE_REVIEW': return state.map((review, index) => review.id === action.id ? [...review, {rating: action.rating}]: review) default: return state; } } export default reviews;
Switch argument order to remove placeholders
'use strict'; var bind = require('lodash.bind'); var ResponseHandler = require('./response-handler'); function ResultList(retriever, options) { if (!retriever) { throw new Error('Expected Retriever as an argument'); } options || (options = {}); this._retriever = retriever; this._onFailure = options.onFailure; this._onSuccess = options.onSuccess; this._page = options.page || 1; } ResultList.prototype.next = function() { this._retriever.query({page: this._page}); this._page += 1; return this._get(this._page - 1); }; ResultList.prototype._get = function(page) { return this._retriever .get() .then(bind(this._handleSuccess, this, page)) .fail(bind(this._handleFailure, this, page)); }; ResultList.prototype._handleSuccess = function(page, res) { var resHandler = new ResponseHandler(res, page, this._onSuccess); return resHandler.success(); }; ResultList.prototype._handleFailure = function(page, res) { var resHandler = new ResponseHandler(res, page, this._onFailure); return resHandler.failure(); }; module.exports = ResultList;
'use strict'; var bind = require('lodash.bind'); var ResponseHandler = require('./response-handler'); bind.placeholder = '_'; function ResultList(retriever, options) { if (!retriever) { throw new Error('Expected Retriever as an argument'); } options || (options = {}); this._retriever = retriever; this._onFailure = options.onFailure; this._onSuccess = options.onSuccess; this._page = options.page || 1; } ResultList.prototype.next = function() { this._retriever.query({page: this._page}); this._page += 1; return this._get(this._page - 1); }; ResultList.prototype._get = function(page) { return this._retriever .get() .then(bind(this._handleSuccess, this, '_', page)) .fail(bind(this._handleFailure, this, '_', page)); }; ResultList.prototype._handleSuccess = function(res, page) { var resHandler = new ResponseHandler(res, page, this._onSuccess); return resHandler.success(); }; ResultList.prototype._handleFailure = function(res, page) { var resHandler = new ResponseHandler(res, page, this._onFailure); return resHandler.failure(); }; module.exports = ResultList;
Add second delete url where users will send request to confirm they want to bulk delete.
from django.conf.urls import url from api.nodes import views urlpatterns = [ # Examples: # url(r'^$', 'api.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^$', views.NodeList.as_view(), name='node-list'), url(r'^bulk_delete/(?P<confirmation_token>\w+)/$', views.NodeBulkDelete.as_view(), name='node-bulk-delete'), url(r'^(?P<node_id>\w+)/$', views.NodeDetail.as_view(), name='node-detail'), url(r'^(?P<node_id>\w+)/contributors/$', views.NodeContributorsList.as_view(), name='node-contributors'), url(r'^(?P<node_id>\w+)/registrations/$', views.NodeRegistrationsList.as_view(), name='node-registrations'), url(r'^(?P<node_id>\w+)/children/$', views.NodeChildrenList.as_view(), name='node-children'), url(r'^(?P<node_id>\w+)/node_links/$', views.NodeLinksList.as_view(), name='node-pointers'), url(r'^(?P<node_id>\w+)/files/$', views.NodeFilesList.as_view(), name='node-files'), url(r'^(?P<node_id>\w+)/node_links/(?P<node_link_id>\w+)', views.NodeLinksDetail.as_view(), name='node-pointer-detail'), ]
from django.conf.urls import url from api.nodes import views urlpatterns = [ # Examples: # url(r'^$', 'api.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^$', views.NodeList.as_view(), name='node-list'), url(r'^(?P<node_id>\w+)/$', views.NodeDetail.as_view(), name='node-detail'), url(r'^(?P<node_id>\w+)/contributors/$', views.NodeContributorsList.as_view(), name='node-contributors'), url(r'^(?P<node_id>\w+)/registrations/$', views.NodeRegistrationsList.as_view(), name='node-registrations'), url(r'^(?P<node_id>\w+)/children/$', views.NodeChildrenList.as_view(), name='node-children'), url(r'^(?P<node_id>\w+)/node_links/$', views.NodeLinksList.as_view(), name='node-pointers'), url(r'^(?P<node_id>\w+)/files/$', views.NodeFilesList.as_view(), name='node-files'), url(r'^(?P<node_id>\w+)/node_links/(?P<node_link_id>\w+)', views.NodeLinksDetail.as_view(), name='node-pointer-detail'), ]
Revert "Revert "Fixed ElasticSearchInfoTest after upgrading to 7.3.1"" This reverts commit 1eb00d8243299fc14a045fef02b71c86f3595f0b.
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.elasticsearch; import org.apache.camel.builder.RouteBuilder; import org.elasticsearch.client.core.MainResponse; import org.junit.Test; public class ElasticsearchInfoTest extends ElasticsearchBaseTest { @Test public void testInfo() throws Exception { MainResponse infoResult = template.requestBody("direct:info", "test", MainResponse.class); assertNotNull(infoResult.getClusterName()); assertNotNull(infoResult.getNodeName()); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() { from("direct:info").to("elasticsearch-rest://elasticsearch?operation=Info&hostAddresses=localhost:" + ES_BASE_HTTP_PORT); } }; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.elasticsearch; import org.apache.camel.builder.RouteBuilder; import org.elasticsearch.action.main.MainResponse; import org.junit.Test; public class ElasticsearchInfoTest extends ElasticsearchBaseTest { @Test public void testInfo() throws Exception { MainResponse infoResult = template.requestBody("direct:info", "test", MainResponse.class); assertNotNull(infoResult.getClusterName()); assertNotNull(infoResult.getNodeName()); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() { from("direct:info").to("elasticsearch-rest://elasticsearch?operation=Info&hostAddresses=localhost:" + ES_BASE_HTTP_PORT); } }; } }
Update slash command to not intefere with native search
var express = require('express'); var Global = require('../global'); var search = require('../commands/search'); var router = express.Router(); router.post('/*', function(req, res) { var response = ''; var arg = req.query.text; //validate token if(req.query.token === Global.authToken) { switch(req.query.command) { case '/searchin': response = search(arg, res); break; default: res.status('500'); res.json({ text: 'Unknown command' }); } } else { res.status('403'); res.json({ text: 'Invalid token' }); } }); module.exports = router;
var express = require('express'); var Global = require('../global'); var search = require('../commands/search'); var router = express.Router(); router.post('/*', function(req, res) { var response = ''; var arg = req.query.text; //validate token if(req.query.token === Global.authToken) { switch(req.query.command) { case '/search': response = search(arg, res); break; default: res.status('500'); res.json({ text: 'Unknown command' }); } } else { res.status('403'); res.json({ text: 'Invalid token' }); } }); module.exports = router;
Replace invalid string format '{}' by '{0}' for Python 2.6 compatibility.
# -*- coding: utf-8 -*- import functools import warnings def deprecated(func): """ This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emmitted when the function is used. """ @functools.wraps(func) def new_func(*args, **kwargs): warnings.simplefilter('always', DeprecationWarning) warnings.warn( "Call to deprecated function {0}.".format(func.__name__), category=DeprecationWarning, stacklevel=2 ) warnings.simplefilter('default', DeprecationWarning) return func(*args, **kwargs) return new_func
# -*- coding: utf-8 -*- import functools import warnings def deprecated(func): """ This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emmitted when the function is used. """ @functools.wraps(func) def new_func(*args, **kwargs): warnings.simplefilter('always', DeprecationWarning) warnings.warn( "Call to deprecated function {}.".format(func.__name__), category=DeprecationWarning, stacklevel=2 ) warnings.simplefilter('default', DeprecationWarning) return func(*args, **kwargs) return new_func
Replace tenant name by tenant title in page headers
<header class="main-header fh-fixedHeader"> <!-- Logo --> <a href="#" class="logo" data-toggle="push-menu" role="button"> <!-- mini logo for sidebar mini 50x50 pixels --> <span class="logo-mini"><i class="fa fa-home"></i></span> <!-- logo for regular state and mobile devices --> <span class="logo-lg"><b>{{ $currentTenant->title }}</b></span> </a> <!-- Header Navbar: style can be found in header.less --> <nav class="navbar navbar-static-top"> <div class="navbar-custom-menu pull-left"> <ul class="nav navbar-nav"> <li><a href="{{ route('managerarea.home') }}"><i class="fa fa-home"></i> {{ trans('cortex/foundation::common.home') }}</a></li> </ul> </div> <div class="navbar-custom-menu"> {!! Menu::render('managerarea.header') !!} </div> </nav> </header>
<header class="main-header fh-fixedHeader"> <!-- Logo --> <a href="#" class="logo" data-toggle="push-menu" role="button"> <!-- mini logo for sidebar mini 50x50 pixels --> <span class="logo-mini"><i class="fa fa-home"></i></span> <!-- logo for regular state and mobile devices --> <span class="logo-lg"><b>{{ $currentTenant->name }}</b></span> </a> <!-- Header Navbar: style can be found in header.less --> <nav class="navbar navbar-static-top"> <div class="navbar-custom-menu pull-left"> <ul class="nav navbar-nav"> <li><a href="{{ route('managerarea.home') }}"><i class="fa fa-home"></i> {{ trans('cortex/foundation::common.home') }}</a></li> </ul> </div> <div class="navbar-custom-menu"> {!! Menu::render('managerarea.header') !!} </div> </nav> </header>
Fix spaces in path breaking for scss filter
<?php App::uses('AssetFilter', 'AssetCompress.Lib'); /** * Pre-processing filter that adds support for SCSS files. * * Requires ruby and sass rubygem to be installed * * @see http://sass-lang.com/ */ class ScssFilter extends AssetFilter { protected $_settings = array( 'ext' => '.scss', 'sass' => '/usr/bin/sass', 'path' => '/usr/bin', ); /** * Runs SCSS compiler against any files that match the configured extension. * * @param string $filename The name of the input file. * @param string $input The content of the file. * @return string */ public function input($filename, $input) { if (substr($filename, strlen($this->_settings['ext']) * -1) !== $this->_settings['ext']) { return $input; } $filename = preg_replace('/ /', '\\ ', $filename); $bin = $this->_settings['sass'] . ' ' . $filename; $return = $this->_runCmd($bin, '', array('PATH' => $this->_settings['path'])); return $return; } }
<?php App::uses('AssetFilter', 'AssetCompress.Lib'); /** * Pre-processing filter that adds support for SCSS files. * * Requires ruby and sass rubygem to be installed * * @see http://sass-lang.com/ */ class ScssFilter extends AssetFilter { protected $_settings = array( 'ext' => '.scss', 'sass' => '/usr/bin/sass', 'path' => '/usr/bin', ); /** * Runs SCSS compiler against any files that match the configured extension. * * @param string $filename The name of the input file. * @param string $input The content of the file. * @return string */ public function input($filename, $input) { if (substr($filename, strlen($this->_settings['ext']) * -1) !== $this->_settings['ext']) { return $input; } $bin = $this->_settings['sass'] . ' ' . $filename; $return = $this->_runCmd($bin, '', array('PATH' => $this->_settings['path'])); return $return; } }
Fix renamer, lcov check was not accessing the proper object
var Reporter = require('../reporter'); var lcovRecord = function(data) { var str = '', lineHandled = 0, lineFound = 0, fileName = data.fileName; if (this.options.cliOptions && this.options.cliOptions.lcovOptions && this.options.cliOptions.lcovOptions.renamer){ fileName = this.options.cliOptions.lcovOptions.renamer(fileName); } str += 'SF:' + fileName + '\n'; data.lines.forEach(function(value, num) { if (value !== null) { str += 'DA:' + num + ',' + value + '\n'; lineFound += 1; if (value > 0) { lineHandled += 1; } } }); str += 'LF:' + lineFound + '\n'; str += 'LH:' + lineHandled + '\n'; str += 'end_of_record'; return str; }; /** * LCOVReporter outputs lcov formatted coverage data * from the test run * * @class LCOVReporter * @param {Object} options hash of options interpreted by reporter */ module.exports = Reporter.extend({ name: 'lcov', defaultOutput: 'lcov.dat', transform: function(coverageData) { var data = coverageData.fileData.map(lcovRecord, this); return data.join('\n'); } });
var Reporter = require('../reporter'); var lcovRecord = function(data) { var str = "", lineHandled = 0, lineFound = 0, fileName = data.fileName; if(this.options.lcovOptions && this.options.lcovOptions.renamer){ fileName = this.options.lcovOptions.renamer(fileName); } str += 'SF:' + fileName + '\n'; data.lines.forEach(function(value, num) { if (value !== null) { str += 'DA:' + num + ',' + value + '\n'; lineFound += 1; if (value > 0) { lineHandled += 1; } } }); str += 'LF:' + lineFound + '\n'; str += 'LH:' + lineHandled + '\n'; str += 'end_of_record'; return str; }; /** * LCOVReporter outputs lcov formatted coverage data * from the test run * * @class LCOVReporter * @param {Object} options hash of options interpreted by reporter */ module.exports = Reporter.extend({ name: 'lcov', defaultOutput: 'lcov.dat', transform: function(coverageData) { var data = coverageData.fileData.map(lcovRecord, this); return data.join('\n'); } });
Use finish event listening instead of overriding res.end()
var assert = require('assert'); var extend = require('obj-extend'); var Lynx = require('lynx'); module.exports = function expressStatsdInit (options) { options = extend({ requestKey: 'statsdKey', host: '127.0.0.1', port: 8125 }, options); assert(options.requestKey, 'express-statsd expects a requestKey'); var client = options.client || new Lynx(options.host, options.port, options); return function expressStatsd (req, res, next) { var startTime = new Date().getTime(); // Function called on response finish that sends stats to statsd function sendStats() { var key = req[options.requestKey]; key = key ? key + '.' : ''; // Status Code var statusCode = res.statusCode || 'unknown_status'; client.increment(key + 'status_code.' + statusCode); // Response Time var duration = new Date().getTime() - startTime; client.timing(key + 'response_time', duration); cleanup(); } // Function to clean up the listeners we've added function cleanup() { res.removeListener('finish', sendStats); res.removeListener('error', cleanup); res.removeListener('close', cleanup); } // Add response listeners res.once('finish', sendStats); res.once('error', cleanup); res.once('close', cleanup); next(); }; };
var assert = require('assert'); var extend = require('obj-extend'); var Lynx = require('lynx'); module.exports = function expressStatsdInit (options) { options = extend({ requestKey: 'statsdKey', host: '127.0.0.1', port: 8125 }, options); assert(options.requestKey, 'express-statsd expects a requestKey'); var client = options.client || new Lynx(options.host, options.port, options); return function expressStatsd (req, res, next) { var startTime = new Date().getTime(); var end = res.end; res.end = function () { var returnValue = end.apply(this, arguments); var key = req[options.requestKey]; key = key ? key + '.' : ''; // Status Code var statusCode = res.statusCode || 'unknown_status'; client.increment(key + 'status_code.' + statusCode); // Response Time var duration = new Date().getTime() - startTime; client.timing(key + 'response_time', duration); return returnValue; }; next(); }; };
Refactor fixture to provide meaningful ids
import socket import pytest import portend def socket_infos(): """ Generate addr infos for connections to localhost """ host = '' port = portend.find_available_local_port() return socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM) def id_for_info(info): af, = info[:1] return str(af) def build_listening_infos(): params = list(socket_infos()) ids = list(map(id_for_info, params)) return locals() @pytest.fixture(**build_listening_infos()) def listening_addr(request): af, socktype, proto, canonname, sa = request.param sock = socket.socket(af, socktype, proto) sock.bind(sa) sock.listen(5) try: yield sa finally: sock.close() class TestCheckPort: def test_check_port_listening(self, listening_addr): with pytest.raises(IOError): portend._check_port(*listening_addr[:2])
import socket import pytest import portend def socket_infos(): """ Generate addr infos for connections to localhost """ host = '' port = portend.find_available_local_port() infos = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM) for info in infos: yield host, port, info @pytest.fixture(params=list(socket_infos())) def listening_addr(request): host, port, info = request.param af, socktype, proto, canonname, sa = info sock = socket.socket(af, socktype, proto) sock.bind(sa) sock.listen(5) try: yield sa finally: sock.close() class TestCheckPort: def test_check_port_listening(self, listening_addr): with pytest.raises(IOError): portend._check_port(*listening_addr[:2])
Fix output of HTML from support Cachet link
<footer class="footer"> @if(Setting::get('show_support')) <p>{!! trans('cachet.powered_by', ['app' => Setting::get('app_name')]) !!}</p> @endif <p><a href="/rss"><i class="ion-social-rss"></i> {{ trans('cachet.rss-feed') }}</a>&nbsp;-&nbsp;<a href="/atom"><i class="ion-social-rss"></i> {{ trans('cachet.atom-feed') }}</a></p> <p> <a href="{{ route('dashboard') }}">{{ trans('dashboard.dashboard') }}</a> @if($loggedUser) &ndash; <a href="{{ route('logout') }}">{{ trans('dashboard.logout') }}</a> @endif </p> </footer> @include("partials.analytics")
<footer class="footer"> @if(Setting::get('show_support')) <p>{{ trans('cachet.powered_by', ['app' => Setting::get('app_name')]) }}</p> @endif <p><a href="/rss"><i class="ion-social-rss"></i> {{ trans('cachet.rss-feed') }}</a>&nbsp;-&nbsp;<a href="/atom"><i class="ion-social-rss"></i> {{ trans('cachet.atom-feed') }}</a></p> <p> <a href="{{ route('dashboard') }}">{{ trans('dashboard.dashboard') }}</a> @if($loggedUser) &ndash; <a href="{{ route('logout') }}">{{ trans('dashboard.logout') }}</a> @endif </p> </footer> @include("partials.analytics")
Fix port issue for heroku deploy ;
var express = require('express'); var app = express(); var http = require('http').Server(app); var io = require('socket.io')(http); var size = 16; var drumState = new Array(size*size); for (var i = 0; i < size*size; i++) drumState[i] = false; app.use(express.static('dist')); app.set('port', (process.env.PORT || 3000)); app.get('/', function(req, res){ res.sendFile(__dirname + '/dist/index.html'); }); io.on('connection', function(socket){ console.log('connected'); socket.on('getDrumState', function(){ console.log('in getDrumState'); socket.emit('setDrumState', drumState); }); socket.on('toggle', function(pos){ if (pos >= 0 && pos < size*size) { drumState[pos] = !drumState[pos]; console.log('broadcasting new drum state'); var s = 'Active drums: '; drumState.forEach(function(cur, i){ if (cur) s += ' ' + i; }); console.log(s); io.sockets.emit('setDrumState', drumState); } }); socket.on('chat', function(msg){ console.log(msg); io.sockets.emit('chat', msg); }); }); http.listen(app.get('port'), function(){ console.log('App running on *:' + app.get('port')); });
var express = require('express'); var app = express(); var http = require('http').Server(app); var io = require('socket.io')(http); var size = 16; var drumState = new Array(size*size); for (var i = 0; i < size*size; i++) drumState[i] = false; app.use(express.static('dist')); app.get('/', function(req, res){ res.sendFile(__dirname + '/dist/index.html'); }); io.on('connection', function(socket){ console.log('connected'); socket.on('getDrumState', function(){ console.log('in getDrumState'); socket.emit('setDrumState', drumState); }); socket.on('toggle', function(pos){ if (pos >= 0 && pos < size*size) { drumState[pos] = !drumState[pos]; console.log('broadcasting new drum state'); var s = 'Active drums: '; drumState.forEach(function(cur, i){ if (cur) s += ' ' + i; }); console.log(s); io.sockets.emit('setDrumState', drumState); } }); socket.on('chat', function(msg){ console.log(msg); io.sockets.emit('chat', msg); }); }); http.listen(3000, function(){ console.log('listening on *:3000'); });
Fix channel type rendering in setup panel
import React from 'react' import PropTypes from 'prop-types' import capitalize from 'lodash/capitalize' import {ListItem, CHECKED, UNCHECKED} from '@opentrons/components' InstrumentListItem.propTypes = { isRunning: PropTypes.bool.isRequired, name: PropTypes.string, axis: PropTypes.string, volume: PropTypes.number, channels: PropTypes.number, probed: PropTypes.bool, clearLabwareReviewed: PropTypes.func } export default function InstrumentListItem (props) { const {isRunning, name, axis, volume, channels, probed, clearLabwareReviewed} = props const isDisabled = name == null const url = isRunning ? '#' : `/setup-instruments/${axis}` // TODO (ka 2018-1-17): Move this up to container mergeProps in upcoming update setup panel ticket const confirmed = probed const iconName = confirmed ? CHECKED : UNCHECKED const pipetteType = channels === 8 ? 'multi' : 'single' const description = !isDisabled ? `${capitalize(pipetteType)}-channel` : 'N/A' const units = !isDisabled ? 'ul' : null return ( <ListItem isDisabled={isDisabled || isRunning} url={url} onClick={!isRunning && clearLabwareReviewed} confirmed={confirmed} iconName={iconName} > <span>{capitalize(axis)}</span> <span>{description}</span> <span>{volume} {units}</span> </ListItem> ) }
import React from 'react' import PropTypes from 'prop-types' import capitalize from 'lodash/capitalize' import {ListItem, CHECKED, UNCHECKED} from '@opentrons/components' InstrumentListItem.propTypes = { isRunning: PropTypes.bool.isRequired, name: PropTypes.string, axis: PropTypes.string, volume: PropTypes.number, channels: PropTypes.number, probed: PropTypes.bool, clearLabwareReviewed: PropTypes.func } export default function InstrumentListItem (props) { const {isRunning, name, axis, volume, channels, probed, clearLabwareReviewed} = props const isDisabled = name == null const url = isRunning ? '#' : `/setup-instruments/${axis}` const confirmed = probed const iconName = confirmed ? CHECKED : UNCHECKED const description = !isDisabled ? `${capitalize(channels)}-channel` : 'N/A' const units = !isDisabled ? 'ul' : null return ( <ListItem isDisabled={isDisabled || isRunning} url={url} onClick={!isRunning && clearLabwareReviewed} confirmed={confirmed} iconName={iconName} > <span>{axis}</span> <span>{description}</span> <span>{volume} {units}</span> </ListItem> ) }
Add a constant that determines the response when no results are found
from IPython.display import Image import requests API_ENDPOINT = 'http://api.giphy.com/v1/gifs/random' # This is the Giphy API's public beta key, see https://github.com/Giphy/GiphyAPI API_KEY = 'dc6zaTOxFJmzC' RANDOM_ON_NO_MATCH = False def get_params(tag): params = {'api_key': API_KEY} if tag is not None: params['tag'] = tag return params def giphy(tag): params = get_params(tag) r = requests.get(API_ENDPOINT, params=params) json = r.json() data = json['data'] if data and 'image_url' in data: return Image(url=data['image_url']) elif RANDOM_ON_NO_MATCH: return giphy(None) else: return 'Giphy could not match {}'.format(tag), def load_ipython_extension(ipython): ipython.register_magic_function(giphy, 'line')
from IPython.display import Image import requests API_ENDPOINT = 'http://api.giphy.com/v1/gifs/random' # This is the Giphy API's public beta key, see https://github.com/Giphy/GiphyAPI API_KEY = 'dc6zaTOxFJmzC' def giphy(tag): params = { 'api_key': API_KEY, 'tag': tag } r = requests.get(API_ENDPOINT, params=params) json = r.json() data = json['data'] if data and 'image_url' in data: return Image(url=data['image_url']) else: return 'Giphy could not match {}'.format(tag) def load_ipython_extension(ipython): ipython.register_magic_function(giphy, 'line')
Change the version number to 0.2.0
#!/usr/bin/env python from setuptools import setup setup(name='programmabletuple', version='0.2.0', description='Python metaclass for making named tuples with programmability', long_description=open('README.rst').read(), author='Tschijnmo TSCHAU', author_email='tschijnmotschau@gmail.com', url='https://github.com/tschijnmo/programmabletuple', license='MIT', packages=['programmabletuple', ], classifiers=[ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
#!/usr/bin/env python from setuptools import setup setup(name='programmabletuple', version='0.1', description='Python metaclass for making named tuples with programmability', long_description=open('README.rst').read(), author='Tschijnmo TSCHAU', author_email='tschijnmotschau@gmail.com', url='https://github.com/tschijnmo/programmabletuple', license='MIT', packages=['programmabletuple', ], classifiers=[ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
Use history spreadsheet to get votes per party for the last vote. @martinstabe can you please populate the relevant column in said spreadsheet: => /db/source/parties-history.csv
'use strict'; const fs = require('fs'); const path = require('path'); const _ = require('lodash'); const PoliticalParties = require('uk-political-parties'); const knownParties = _.values(PoliticalParties.data); const dsv = require('dsv'); const csv = dsv(','); const model = require('../model'); module.exports = { addCollection: addCollection, makeDataFromSources: makeDataFromSources, load: load }; function load(db) { return addCollection(db, makeDataFromSources()); } function createModel(p) { return model.factory.Party(p); } function historicalElectionResults(filename) { var history = csv.parse(fs.readFileSync(path.resolve(__dirname, '../source/parties-history.csv')).toString()); var index = _.indexBy(history, 'id'); return function(party) { var party_history = index[party.id]; party.elections.last = model.factory.PartyNationalResult({ seats: party_history ? party_history.last_seats : 0, votes: party_history ? party_history.last_votes : 0, }); return party; }; } function makeDataFromSources() { var parties = knownParties.map(createModel) .map(historicalElectionResults()); return parties; } function addCollection(database, data) { return database.addCollection('parties', ['id', 'short', 'full', 'pa']).insert(data); }
'use strict'; const fs = require('fs'); const path = require('path'); const _ = require('lodash'); const PoliticalParties = require('uk-political-parties'); const knownParties = _.values(PoliticalParties.data); const dsv = require('dsv'); const csv = dsv(','); const model = require('../model'); module.exports = { addCollection: addCollection, makeDataFromSources: makeDataFromSources, load: load }; function load(db) { return addCollection(db, makeDataFromSources()); } function createModel(p) { return model.factory.Party(p); } function historicalElectionResults(filename) { var history = csv.parse(fs.readFileSync(path.resolve(__dirname, '../source/parties-history.csv')).toString()); var index = _.indexBy(history, 'id'); return function(party) { var party_history = index[party.id]; party.elections.last = model.factory.PartyNationalResult({ seats: party_history ? party_history.last_seats : 0 }); return party; }; } function makeDataFromSources() { var parties = knownParties.map(createModel) .map(historicalElectionResults()); return parties; } function addCollection(database, data) { return database.addCollection('parties', ['id', 'short', 'full', 'pa']).insert(data); }
Update pelcian conf to reflect theme change
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals AUTHOR = 'Mike' SITENAME = 'Conversations with Mike the Turtle' SITEURL = '' RELATIVE_URLS = True PATH = 'content' TIMEZONE = 'America/New_York' DEFAULT_LANG = 'en' # Feed generation is usually not desired when developing FEED_ALL_ATOM = None CATEGORY_FEED_ATOM = None TRANSLATION_FEED_ATOM = None AUTHOR_FEED_ATOM = None AUTHOR_FEED_RSS = None # Blogroll LINKS = () # Social widget SOCIAL = () STATIC_PATHS = ['images'] THEME = 'themes/blue_idea' THEME_STATIC_DIR = 'blue_idea/static' DEFAULT_PAGINATION = 100 # Uncomment following line if you want document-relative URLs when developing #RELATIVE_URLS = True
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals AUTHOR = 'Mike' SITENAME = 'Conversations with Mike the Turtle' SITEURL = '' RELATIVE_URLS = True PATH = 'content' TIMEZONE = 'America/New_York' DEFAULT_LANG = 'en' # Feed generation is usually not desired when developing FEED_ALL_ATOM = None CATEGORY_FEED_ATOM = None TRANSLATION_FEED_ATOM = None AUTHOR_FEED_ATOM = None AUTHOR_FEED_RSS = None # Blogroll LINKS = () # Social widget SOCIAL = () STATIC_PATHS = ['images'] THEME = 'themes/blueidea' THEME_STATIC_DIR = 'blueidea/static' DEFAULT_PAGINATION = 100 # Uncomment following line if you want document-relative URLs when developing #RELATIVE_URLS = True
Return a list of identifiers instead of almost all info
from flask import Flask, abort, jsonify from flask_caching import Cache from flask_cors import CORS import main app = Flask(__name__) cache = Cache(app, config={'CACHE_TYPE': 'simple'}) cors = CORS(app, resources={r"/*": {"origins": "*"}}) @app.route('/api/') @cache.cached(timeout=3600) def list_entities(): return jsonify({'entities': ['restaurant']}) @app.route('/api/restaurant/') @cache.cached(timeout=3600) def list_restaurants(): return jsonify({'restaurants': [entry['identifier'] for entry in main.list_restaurants()]}) @app.route('/api/restaurant/<name>/') @cache.cached(timeout=3600) def get_restaurant(name): data = main.get_restaurant(name) if not data: abort(status=404) data['menu'] = [{'dish': entry} for entry in data['menu']] return jsonify({'restaurant': data})
from flask import Flask, abort, jsonify from flask_caching import Cache from flask_cors import CORS import main app = Flask(__name__) cache = Cache(app, config={'CACHE_TYPE': 'simple'}) cors = CORS(app, resources={r"/*": {"origins": "*"}}) @app.route('/api/') @cache.cached(timeout=3600) def nbis_list_entities(): return jsonify({'entities': ['restaurant']}) @app.route('/api/restaurant/') @cache.cached(timeout=3600) def nbis_api_list_restaurants(): return jsonify({'restaurants': main.list_restaurants()}) @app.route('/api/restaurant/<name>/') @cache.cached(timeout=3600) def nbis_api_get_restaurant(name): data = main.get_restaurant(name) if not data: abort(status=404) data['menu'] = [{'dish': entry} for entry in data['menu']] return jsonify({'restaurant': data})
Add comment to debug line
'use strict' let routes = function(server, app) { server.route({ method: 'POST', path: '/alexa', config: { handler: function(request, response) { let retVal = app.handleRequest(request) console.warn("RET VAL", retVal) // TODO - Remove once you actually make use of the response response({ version: "0.1.0", sessionAttributes: {}, response: { outputSpeech: { type: "PlainText", text: "Done" } } }) } } }) } module.exports = routes
'use strict' let routes = function(server, app) { server.route({ method: 'POST', path: '/alexa', config: { handler: function(request, response) { let retVal = app.handleRequest(request) console.warn("RET VAL", retVal) response({ version: "0.1.0", sessionAttributes: {}, response: { outputSpeech: { type: "PlainText", text: "Done" } } }) } } }) } module.exports = routes
Check if admin is logged in AuthControllers
<?php namespace PSFS\base\types; use PSFS\base\Security; /** * Class AuthController * @package PSFS\base\types */ trait SecureTrait { /** * @Inyectable * @var \PSFS\base\Security Seguridad del controlador */ protected $security; /** * Constructor por defecto */ public function __construct() { $this->security = Security::getInstance(); } /** * Método que verifica si está autenticado el usuario * @return boolean */ public function isLogged() { return (null !== $this->security->getUser() || $this->isAdmin()); } /** * Método que devuelve si un usuario es administrador de la plataforma * @return boolean */ public function isAdmin() { return $this->security->canAccessRestrictedAdmin(); } /** * Método que define si un usuario puede realizar una acción concreta * @param $action * TODO * @return bool */ public function canDo($action) { return true; } }
<?php namespace PSFS\base\types; use PSFS\base\Security; /** * Class AuthController * @package PSFS\base\types */ trait SecureTrait { /** * @Inyectable * @var \PSFS\base\Security Seguridad del controlador */ protected $security; /** * Constructor por defecto */ public function __construct() { $this->security = Security::getInstance(); } /** * Método que verifica si está autenticado el usuario * @return boolean */ public function isLogged() { return (null !== $this->security->getUser()); } /** * Método que devuelve si un usuario es administrador de la plataforma * @return boolean */ public function isAdmin() { return $this->security->canAccessRestrictedAdmin(); } /** * Método que define si un usuario puede realizar una acción concreta * @param $action * TODO * @return bool */ public function canDo($action) { return true; } }
Fix deprecation warning on unlink()
'use strict'; var fs = require('fs'); var pictureTube = require('picture-tube'); var webshot = require('webshot'); function hitThat (url, options) { var name = Date.now() + '_that.png'; var o = options || {}; if (o.width === void 0) { o.width = 1024; } if (o.height === void 0) { o.height = 768; } if (o.cols === void 0) { o.cols = 80; } if (o.dest === void 0) { o.dest = process.stdout; } var tube = pictureTube({ cols: o.cols }); tube.pipe(o.dest); webshot(url, { windowSize: { width: o.width, height: o.height } }, ready); function ready (err, reader) { if (err) { throw err; } var file = fs.createWriteStream(name, { encoding: 'binary' }); reader.on('data', read); reader.on('end', write); function read (data) { file.write(data.toString('binary'), 'binary'); } function write () { fs.createReadStream(name).pipe(tube).on('end', remove); } function remove () { fs.unlinkSync(name); } } } module.exports = hitThat;
'use strict'; var fs = require('fs'); var pictureTube = require('picture-tube'); var webshot = require('webshot'); function hitThat (url, options) { var name = Date.now() + '_that.png'; var o = options || {}; if (o.width === void 0) { o.width = 1024; } if (o.height === void 0) { o.height = 768; } if (o.cols === void 0) { o.cols = 80; } if (o.dest === void 0) { o.dest = process.stdout; } var tube = pictureTube({ cols: o.cols }); tube.pipe(o.dest); webshot(url, { windowSize: { width: o.width, height: o.height } }, ready); function ready (err, reader) { if (err) { throw err; } var file = fs.createWriteStream(name, { encoding: 'binary' }); reader.on('data', read); reader.on('end', write); function read (data) { file.write(data.toString('binary'), 'binary'); } function write () { fs.createReadStream(name).pipe(tube).on('end', remove); } function remove () { fs.unlink(name); } } } module.exports = hitThat;
Make (undocumented) library interface backwards-compatible, since some clients seem to be relying on it
/* Copyrights for code authored by Yahoo! Inc. is licensed under the following terms: MIT License Copyright (c) 2011 Yahoo! Inc. All Rights Reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ module.exports = { Yui3TestRunner: require('./lib/yui3-test-runner'), YuiTestRunner: require('./lib/yuitest-runner'), coverage: require('./lib/coverage/yui'), cli: require('./lib/cli') };
/* Copyrights for code authored by Yahoo! Inc. is licensed under the following terms: MIT License Copyright (c) 2011 Yahoo! Inc. All Rights Reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ module.exports = { Yui3TestRunner: require('./lib/yui3-test-runner'), YuiTestRunner: require('./lib/yuitest-runner'), coverage: require('./lib/coverage'), cli: require('./lib/cli') };
Add http error 415 Unsupported Media Type
// Copyright 2012 Mark Cavage, Inc. All rights reserved. var jsonParser = require('./json_body_parser'); var formParser = require('./form_body_parser'); var multipartParser = require('./multipart_parser'); var errors = require('../errors'); var UnsupportedMediaTypeError = errors.UnsupportedMediaTypeError; function bodyParser(options) { var parseForm = formParser(options); var parseJson = jsonParser(options); var parseMultipart = multipartParser(options); return function parseBody(req, res, next) { if (req.contentLength === 0 && !req.chunked) return next(); if (req.contentType === 'application/json') { return parseJson(req, res, next); } else if (req.contentType === 'application/x-www-form-urlencoded') { return parseForm(req, res, next); } else if (req.contentType === 'multipart/form-data') { return parseMultipart(req, res, next); } else { return next(new UnsupportedMediaTypeError('Unsupported Content-Type: ' + req.contentType)); } return next(); }; } module.exports = bodyParser;
// Copyright 2012 Mark Cavage, Inc. All rights reserved. var jsonParser = require('./json_body_parser'); var formParser = require('./form_body_parser'); var multipartParser = require('./multipart_parser'); function bodyParser(options) { var parseForm = formParser(options); var parseJson = jsonParser(options); var parseMultipart = multipartParser(options); return function parseBody(req, res, next) { if (req.contentLength === 0 && !req.chunked) return next(); if (req.contentType === 'application/json') { return parseJson(req, res, next); } else if (req.contentType === 'application/x-www-form-urlencoded') { return parseForm(req, res, next); } else if (req.contentType === 'multipart/form-data') { return parseMultipart(req, res, next); } return next(); }; } module.exports = bodyParser;
Add explaination to selection of retrying status codes
package io.tus.java.client; import java.io.IOException; import java.net.HttpURLConnection; /** * This exception is thrown if the server sends a request with an unexpected status code or * missing/invalid headers. */ public class ProtocolException extends Exception { private HttpURLConnection connection; public ProtocolException(String message) { super(message); } public ProtocolException(String message, HttpURLConnection connection) { super(message); this.connection = connection; } public HttpURLConnection getCausingConnection() { return connection; } public boolean shouldRetry() { if(connection == null) { return false; } try { int responseCode = connection.getResponseCode(); // 5XX and 423 Resource Locked status codes should be retried. return (responseCode >= 500 && responseCode < 600) || responseCode == 423; } catch(IOException e) { return false; } } }
package io.tus.java.client; import java.io.IOException; import java.net.HttpURLConnection; /** * This exception is thrown if the server sends a request with an unexpected status code or * missing/invalid headers. */ public class ProtocolException extends Exception { private HttpURLConnection connection; public ProtocolException(String message) { super(message); } public ProtocolException(String message, HttpURLConnection connection) { super(message); this.connection = connection; } public HttpURLConnection getCausingConnection() { return connection; } public boolean shouldRetry() { if(connection == null) { return false; } try { int responseCode = connection.getResponseCode(); return responseCode >= 500 && responseCode < 600 || responseCode == 423; } catch(IOException e) { return false; } } }
Setup: Fix data_files to install man and license documents
#! /usr/bin/env python3 from distutils.core import setup setup( description = 'File downloader for danbooru', author = 'Todd Gaunt', url = 'https://www.github.com/toddgaunt/danboorsync', download_url = 'https://www.github.com/toddgaunt/danboorsync', author_email = 'toddgaunt@protonmail.ch', version = '1.0', packages = ['danboorsync'], package_dir = {'danboorsync':'src'}, # Change these per distribution data_files = [('/usr/share/man/man1', ['doc/danboorsync.1']), ('/usr/share/licenses/danboorsync/LICENSE', ['doc/LICENSE'])], scripts = ['/usr/bin/danboorsync'], name = 'danboorsync' )
#! /usr/bin/env python3 from distutils.core import setup setup( description = 'File downloader for danbooru', author = 'Todd Gaunt', url = 'https://www.github.com/toddgaunt/danboorsync', download_url = 'https://www.github.com/toddgaunt/danboorsync', author_email = 'toddgaunt@protonmail.ch', version = '1.0', packages = ['danboorsync'], package_dir = {'danboorsync':'src'}, # Change these per distribution data_files = [('usr/share/man/man1', ['doc/danboorsync.1']), ('usr/share/licenses/imgfetch/LICENSE', ['doc/LICENSE'])], scripts = ['/usr/bin/danboorsync'], name = 'danboorsync' )
Fix Snippet failing test, ``image`` field is blank.
from nose.tools import eq_, ok_ from django.test import TestCase from us_ignite.snippets.models import Snippet class TestSnippetModel(TestCase): def tearDown(self): Snippet.objects.all().delete() def get_instance(self): data = { 'name': 'Gigabit snippets', 'slug': 'featured', 'url': 'http://us-ignite.org/', } return Snippet.objects.create(**data) def test_instance_is_created_successfully(self): instance = self.get_instance() eq_(instance.name, 'Gigabit snippets') eq_(instance.status, Snippet.DRAFT) eq_(instance.url, 'http://us-ignite.org/') eq_(instance.url_text, '') eq_(instance.body, '') eq_(instance.image, '') eq_(instance.is_featured, False) ok_(instance.created) ok_(instance.modified) eq_(instance.slug, 'featured') ok_(instance.id)
from nose.tools import eq_, ok_ from django.test import TestCase from us_ignite.snippets.models import Snippet class TestSnippetModel(TestCase): def tearDown(self): Snippet.objects.all().delete() def get_instance(self): data = { 'name': 'Gigabit snippets', 'slug': 'featured', 'url': 'http://us-ignite.org/', } return Snippet.objects.create(**data) def test_instance_is_created_successfully(self): instance = self.get_instance() eq_(instance.name, 'Gigabit snippets') eq_(instance.status, Snippet.DRAFT) eq_(instance.url, 'http://us-ignite.org/') eq_(instance.url_text, '') eq_(instance.body, '') eq_(instance.image, 'ad.png') eq_(instance.is_featured, False) ok_(instance.created) ok_(instance.modified) eq_(instance.slug, 'featured') ok_(instance.id)
Fix the trover classifier and license
from setuptools import setup classifiers = ['Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Libraries', 'Topic :: Software Development :: Libraries :: Python Modules'] setup(name='avroconsumer', version='0.1.0', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="gavinr@aweber.com", url="https://github.com/aweber/avroconsumer", install_requires=['rejected', 'avro'], license='BSDv3', package_data={'': ['LICENSE', 'README.rst']}, py_modules=['avroconsumer'], classifiers=classifiers)
from setuptools import setup classifiers = ['Development Status :: 4 - Production/Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Libraries', 'Topic :: Software Development :: Libraries :: Python Modules'] setup(name='avroconsumer', version='0.1.0', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="gavinr@aweber.com", url="https://github.com/aweber/avroconsumer", install_requires=['rejected', 'avro'], license=open('LICENSE').read(), package_data={'': ['LICENSE', 'README.rst']}, py_modules=['avroconsumer'], classifiers=classifiers)
Add Chrome browser definition with the extension loaded
process.env.NODE_ENV = 'test'; const path = require('path'); var webpackConfig = require(path.join(__dirname, './node_modules/react-scripts/config/webpack.config.dev.js')); webpackConfig.devtool = 'inline-source-map'; module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine'], files: ['src/**/**.test.js'], exclude: [], preprocessors: { 'src/**/**.test.js': ['webpack', 'sourcemap'] }, webpack: webpackConfig, reporters: ['mocha'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: false, browsers: ['Chrome', 'Firefox'], singleRun: true, concurrency: 1, customLaunchers: { ex_Chrome: { base: 'Chrome', flags: ['--load-extension=../extension'] } } }) }
process.env.NODE_ENV = 'test'; const path = require('path'); var webpackConfig = require(path.join(__dirname, './node_modules/react-scripts/config/webpack.config.dev.js')); webpackConfig.devtool = 'inline-source-map'; module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine'], files: ['src/**/**.test.js'], exclude: [], preprocessors: { 'src/**/**.test.js': ['webpack', 'sourcemap'] }, webpack: webpackConfig, reporters: ['mocha'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: false, browsers: ['Chrome', 'Firefox'], singleRun: true, concurrency: 1, }) }
Update how exact match is found
import {find, isEqual, uniqueId} from 'lodash'; import getOptionLabel from './getOptionLabel'; /** * Filter out options that don't match the input string or, if multiple * selections are allowed, that have already been selected. */ function getFilteredOptions(options=[], text='', selected=[], props={}) { const {allowNew, labelKey, minLength, multiple} = props; if (text.length < minLength) { return []; } let filteredOptions = options.filter(option => { const labelString = getOptionLabel(option, labelKey); return !( labelString.toLowerCase().indexOf(text.toLowerCase()) === -1 || multiple && find(selected, o => isEqual(o, option)) ); }); const exactMatchFound = find(filteredOptions, o => ( getOptionLabel(o, labelKey) === text )); if ( allowNew && !!text.trim() && !(filteredOptions.length && exactMatchFound) ) { let newOption = { id: uniqueId('new-id-'), customOption: true, }; newOption[labelKey] = text; filteredOptions.push(newOption); } return filteredOptions; } export default getFilteredOptions;
import {find, isEqual, uniqueId} from 'lodash'; import getOptionLabel from './getOptionLabel'; /** * Filter out options that don't match the input string or, if multiple * selections are allowed, that have already been selected. */ function getFilteredOptions(options=[], text='', selected=[], props={}) { const {allowNew, labelKey, minLength, multiple} = props; if (text.length < minLength) { return []; } let exactMatchFound = false; let filteredOptions = options.filter(option => { const labelString = getOptionLabel(option, labelKey); if (labelString === text) { exactMatchFound = true; } return !( labelString.toLowerCase().indexOf(text.toLowerCase()) === -1 || multiple && find(selected, o => isEqual(o, option)) ); }); if ( allowNew && !!text.trim() && !(filteredOptions.length && exactMatchFound) ) { let newOption = { id: uniqueId('new-id-'), customOption: true, }; newOption[labelKey] = text; filteredOptions.push(newOption); } return filteredOptions; } export default getFilteredOptions;
Fix typo in Platform check
'use strict'; import { NativeEventEmitter, NativeModules, Platform } from 'react-native'; const { RNPusherPushNotifications } = NativeModules const rnPusherPushNotificationsEmitter = new NativeEventEmitter(RNPusherPushNotifications) export default { setAppKey: (appKey) => { RNPusherPushNotifications.setAppKey(appKey) }, subscribe: (channel, onError, onSuccess) => { if (Platform.OS === 'ios') { RNPusherPushNotifications.subscribe(channel) } else { RNPusherPushNotifications.subscribe(channel, onError, onSuccess) } }, unsubscribe: (channel, onError, onSuccess) => { if (Platform.OS === 'ios') { RNPusherPushNotifications.unsubscribe(channel) } else { RNPusherPushNotifications.unsubscribe(channel, onError, onSuccess) } }, on: (eventName, callback) => { rnPusherPushNotificationsEmitter.addListener( eventName, (payload) => callback(payload) ) } };
'use strict'; import { NativeEventEmitter, NativeModules, Platform } from 'react-native'; const { RNPusherPushNotifications } = NativeModules const rnPusherPushNotificationsEmitter = new NativeEventEmitter(RNPusherPushNotifications) export default { setAppKey: (appKey) => { RNPusherPushNotifications.setAppKey(appKey) }, subscribe: (channel, onError, onSuccess) => { if (Platform.os === 'ios') { RNPusherPushNotifications.subscribe(channel) } else { RNPusherPushNotifications.subscribe(channel, onError, onSuccess) } }, unsubscribe: (channel, onError, onSuccess) => { if (Platform.os === 'ios') { RNPusherPushNotifications.unsubscribe(channel) } else { RNPusherPushNotifications.unsubscribe(channel, onError, onSuccess) } }, on: (eventName, callback) => { rnPusherPushNotificationsEmitter.addListener( eventName, (payload) => callback(payload) ) } };
Tests(blob): Use byte string for test
import pytest from sqlobject import BLOBCol, SQLObject from sqlobject.compat import PY2 from sqlobject.tests.dbtest import setupClass, supports ######################################## # BLOB columns ######################################## class ImageData(SQLObject): image = BLOBCol(default=b'emptydata', length=256) def test_BLOBCol(): if not supports('blobData'): pytest.skip("blobData isn't supported") setupClass(ImageData) if PY2: data = ''.join([chr(x) for x in range(256)]) else: data = bytes(range(256)) prof = ImageData(image=data) iid = prof.id ImageData._connection.cache.clear() prof2 = ImageData.get(iid) assert prof2.image == data ImageData(image=b'string') assert ImageData.selectBy(image=b'string').count() == 1
import pytest from sqlobject import BLOBCol, SQLObject from sqlobject.compat import PY2 from sqlobject.tests.dbtest import setupClass, supports ######################################## # BLOB columns ######################################## class ImageData(SQLObject): image = BLOBCol(default=b'emptydata', length=256) def test_BLOBCol(): if not supports('blobData'): pytest.skip("blobData isn't supported") setupClass(ImageData) if PY2: data = ''.join([chr(x) for x in range(256)]) else: data = bytes(range(256)) prof = ImageData() prof.image = data iid = prof.id ImageData._connection.cache.clear() prof2 = ImageData.get(iid) assert prof2.image == data ImageData(image='string') assert ImageData.selectBy(image='string').count() == 1
Check for config file first
<?php namespace Morrislaptop\LaravelFivePackageBridges; use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\File; use ReflectionClass; trait LaravelFivePackageBridgeTrait { public function boot() { $this->loadViewsFrom($this->namespace, $this->guessPackagePath() . '/views'); $this->loadTranslationsFrom($this->namespace, $this->guessPackagePath() . '/lang'); $this->setConfig(); } protected function guessPackagePath() { $path = (new ReflectionClass(get_parent_class()))->getFileName(); return realpath(dirname($path).'/../../'); } protected function setConfig() { $path = $this->guessPackagePath() . '/config/config.php'; $files = App::make('files'); if ( $files->exists($path) ) { $config = require $path; $this->app['config']->set($this->namespace, $config); } } }
<?php namespace Morrislaptop\LaravelFivePackageBridges; use ReflectionClass; trait LaravelFivePackageBridgeTrait { public function boot() { $this->loadViewsFrom($this->namespace, $this->guessPackagePath() . '/views'); $this->loadTranslationsFrom($this->namespace, $this->guessPackagePath() . '/lang'); $this->setConfig(); $this->app['config']->package($this->vendor . '/' . $this->namespace, $this->guessPackagePath() . '/config', $this->namespace); } protected function guessPackagePath() { $path = (new ReflectionClass(get_parent_class()))->getFileName(); return realpath(dirname($path).'/../../'); } protected function setConfig() { $config = require $this->guessPackagePath() . '/config/config.php'; $this->app['config']->set($this->namespace, $config); } }
Call pip install before running server.
import os import subprocess import sys import time bin_dir = os.path.expanduser('~/FrameworkBenchmarks/installs/py2/bin') python = os.path.expanduser(os.path.join(bin_dir, 'python')) pip = os.path.expanduser(os.path.join(bin_dir, 'pip')) cwd = os.path.expanduser('~/FrameworkBenchmarks/tornado') def start(args, logfile, errfile): subprocess.call(pip + ' install -r requirements.txt', cwd=cwd, shell=True, stderr=errfile, stdout=logfile) subprocess.Popen( python + ' server.py --port=8080 --postgres=%s --logging=error' % (args.database_host,), shell=True, cwd=cwd, stderr=errfile, stdout=logfile) return 0 def stop(logfile, errfile): for line in subprocess.check_output(['ps', 'aux']).splitlines(): if 'server.py --port=8080' in line: pid = int(line.split(None, 2)[1]) os.kill(pid, 9) return 0 if __name__ == '__main__': class DummyArg: database_host = 'localhost' start(DummyArg(), sys.stderr, sys.stderr) time.sleep(1) stop(sys.stderr, sys.stderr)
from os.path import expanduser from os import kill import subprocess import sys import time python = expanduser('~/FrameworkBenchmarks/installs/py2/bin/python') cwd = expanduser('~/FrameworkBenchmarks/tornado') def start(args, logfile, errfile): subprocess.Popen( python + " server.py --port=8080 --postgres=%s --logging=error" % (args.database_host,), shell=True, cwd=cwd, stderr=errfile, stdout=logfile) return 0 def stop(logfile, errfile): for line in subprocess.check_output(["ps", "aux"]).splitlines(): if 'server.py --port=8080' in line: pid = int(line.split(None,2)[1]) kill(pid, 9) return 0 if __name__ == '__main__': class DummyArg: database_host = 'localhost' start(DummyArg(), sys.stderr, sys.stderr) time.sleep(1) stop(sys.stderr, sys.stderr)
Return the actual bank number in 0xFF70.
package eu.rekawek.coffeegb.memory; import eu.rekawek.coffeegb.AddressSpace; public class GbcRam implements AddressSpace { private int[] ram = new int[7 * 0x1000]; private int svbk; @Override public boolean accepts(int address) { return address == 0xff70 || (address >= 0xd000 && address < 0xe000); } @Override public void setByte(int address, int value) { if (address == 0xff70) { this.svbk = value; } else { ram[translate(address)] = value; } } @Override public int getByte(int address) { if (address == 0xff70) { return svbk; } else { return ram[translate(address)]; } } private int translate(int address) { int ramBank = svbk & 0x7; if (ramBank == 0) { ramBank = 1; } int result = address - 0xd000 + (ramBank - 1) * 0x1000; if (result < 0 || result >= ram.length) { throw new IllegalArgumentException(); } return result; } }
package eu.rekawek.coffeegb.memory; import eu.rekawek.coffeegb.AddressSpace; public class GbcRam implements AddressSpace { private int[] ram = new int[7 * 0x1000]; private int svbk; @Override public boolean accepts(int address) { return address == 0xff70 || (address >= 0xd000 && address < 0xe000); } @Override public void setByte(int address, int value) { if (address == 0xff70) { this.svbk = value; } else { ram[translate(address)] = value; } } @Override public int getByte(int address) { if (address == 0xff70) { return 0xff; } else { return ram[translate(address)]; } } private int translate(int address) { int ramBank = svbk & 0x7; if (ramBank == 0) { ramBank = 1; } int result = address - 0xd000 + (ramBank - 1) * 0x1000; if (result < 0 || result >= ram.length) { throw new IllegalArgumentException(); } return result; } }
Add fallback to app.import if this.import is not available
/* jshint node: true */ // jscs: disable 'use strict'; module.exports = { name: 'ember-l10n', isDevelopingAddon: function() { // @see: https://ember-cli.com/extending/#link-to-addon-while-developing return false; // Set this to true for local development }, includedCommands: function() { return { 'l10n:install': require('./lib/commands/install'), 'l10n:extract': require('./lib/commands/extract'), 'l10n:convert': require('./lib/commands/convert'), 'l10n:sync': require('./lib/commands/sync') }; }, included: function(app) { this._super.included(app); // In nested addons, app.bowerDirectory might not be available var bowerDirectory = app.bowerDirectory || 'bower_components'; // In ember-cli < 2.7, this.import is not available, so fall back to use app.import var importShim = typeof this.import !== 'undefined' ? this : app; importShim.import(bowerDirectory + '/gettext.js/dist/gettext.min.js', { exports: { 'i18n': [ 'default' ] } }); } };
/* jshint node: true */ // jscs: disable 'use strict'; module.exports = { name: 'ember-l10n', isDevelopingAddon: function() { // @see: https://ember-cli.com/extending/#link-to-addon-while-developing return false; // Set this to true for local development }, includedCommands: function() { return { 'l10n:install': require('./lib/commands/install'), 'l10n:extract': require('./lib/commands/extract'), 'l10n:convert': require('./lib/commands/convert'), 'l10n:sync': require('./lib/commands/sync') }; }, included: function(app) { this._super.included(app); var bowerDirectory = app.bowerDirectory || 'bower_components'; this.import(bowerDirectory + '/gettext.js/dist/gettext.min.js', { exports: { 'i18n': [ 'default' ] } }); } };
Allow personal_access tokens grant to get "*" scope
<?php namespace Laravel\Passport\Bridge; use Laravel\Passport\Passport; use League\OAuth2\Server\Entities\ClientEntityInterface; use League\OAuth2\Server\Repositories\ScopeRepositoryInterface; class ScopeRepository implements ScopeRepositoryInterface { /** * {@inheritdoc} */ public function getScopeEntityByIdentifier($identifier) { if (Passport::hasScope($identifier)) { return new Scope($identifier); } } /** * {@inheritdoc} */ public function finalizeScopes( array $scopes, $grantType, ClientEntityInterface $clientEntity, $userIdentifier = null) { if (! in_array($grantType, ['password', 'personal_access'])) { $scopes = collect($scopes)->reject(function ($scope) { return trim($scope->getIdentifier()) === '*'; })->values()->all(); } return collect($scopes)->filter(function ($scope) { return Passport::hasScope($scope->getIdentifier()); })->values()->all(); } }
<?php namespace Laravel\Passport\Bridge; use Laravel\Passport\Passport; use League\OAuth2\Server\Entities\ClientEntityInterface; use League\OAuth2\Server\Repositories\ScopeRepositoryInterface; class ScopeRepository implements ScopeRepositoryInterface { /** * {@inheritdoc} */ public function getScopeEntityByIdentifier($identifier) { if (Passport::hasScope($identifier)) { return new Scope($identifier); } } /** * {@inheritdoc} */ public function finalizeScopes( array $scopes, $grantType, ClientEntityInterface $clientEntity, $userIdentifier = null) { if ($grantType !== 'password') { $scopes = collect($scopes)->reject(function ($scope) { return trim($scope->getIdentifier()) === '*'; })->values()->all(); } return collect($scopes)->filter(function ($scope) { return Passport::hasScope($scope->getIdentifier()); })->values()->all(); } }
Add author and home page information
from setuptools import Extension, find_packages, setup arpreq = Extension('arpreq', sources=['arpreq/arpreq.c'], extra_compile_args=['-std=c99']) setup(name='arpreq', author='Sebastian Schrader', author_email='sebastian.schrader@ossmail.de', url='https://github.com/sebschrader/python-arpreq', version='0.1.0', description="Query the Kernel ARP cache for the MAC address " "corresponding to IP address", packages=find_packages(exclude=["*.tests"]), ext_modules=[arpreq], classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: MIT License', 'Intended Audience :: System Administrators', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: Implementation :: CPython', 'Topic :: System :: Networking', ], )
from setuptools import Extension, find_packages, setup arpreq = Extension('arpreq', sources=['arpreq/arpreq.c'], extra_compile_args=['-std=c99']) setup(name='arpreq', version='0.1.0', description="Query the Kernel ARP cache for the MAC address " "corresponding to IP address", packages=find_packages(exclude=["*.tests"]), ext_modules=[arpreq], classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: MIT License', 'Intended Audience :: System Administrators', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: Implementation :: CPython', 'Topic :: System :: Networking', ], )
Test Commit. Attempt to fix username.
package mazegenerator; import java.util.ArrayList; import java.util.Arrays; import util.MathUtil; /** * * @author mallory */ public class MazeGenerator { public static void main(String[] args) throws Exception { // byte value = 0; // for(; value < 33; value++){ // MazeTile tile = new MazeTile(value); // System.out.println(tile + " " + value); // System.out.println(); // } // MazeTile[][] maze = new MazeTile[2][2]; // maze[0][0] = new MazeTile(true,false,true,false); // maze[0][1] = new MazeTile(false,true,true,false); // maze[1][0] = new MazeTile(true,false,false,true); // maze[1][1] = new MazeTile(false,true,false,true); Maze maze = new Maze(47, 11, 1,1); //Test //Test 2 maze.generate(); System.out.print(maze.toString()); } }
package mazegenerator; import java.util.ArrayList; import java.util.Arrays; import util.MathUtil; /** * * @author mallory */ public class MazeGenerator { public static void main(String[] args) throws Exception { // byte value = 0; // for(; value < 33; value++){ // MazeTile tile = new MazeTile(value); // System.out.println(tile + " " + value); // System.out.println(); // } // MazeTile[][] maze = new MazeTile[2][2]; // maze[0][0] = new MazeTile(true,false,true,false); // maze[0][1] = new MazeTile(false,true,true,false); // maze[1][0] = new MazeTile(true,false,false,true); // maze[1][1] = new MazeTile(false,true,false,true); Maze maze = new Maze(47, 11, 1,1); //Test maze.generate(); System.out.print(maze.toString()); } }
Make the Module set ordered and keep it sorted
package com.demonwav.mcdev.toolwindow; import com.demonwav.mcdev.platform.MinecraftModule; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.project.Project; import com.intellij.util.containers.OrderedSet; import org.jetbrains.annotations.NotNull; import java.util.Collections; import javax.swing.JPanel; public class MinecraftToolWindow { private JPanel panel; private Project project; private OrderedSet<MinecraftModule> mcModules = new OrderedSet<>(); public void setProjectAndInit(@NotNull Project project) { this.project = project; final Module[] modules = ModuleManager.getInstance(project).getModules(); for (Module module : modules) { final MinecraftModule instance = MinecraftModule.getInstance(module); if (instance != null) { mcModules.add(instance); } } Collections.sort(mcModules, (m1, m2) -> m1.getIdeaModule().getName().compareTo(m2.getIdeaModule().getName())); } public JPanel getPanel() { return panel; } }
package com.demonwav.mcdev.toolwindow; import com.demonwav.mcdev.platform.MinecraftModule; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; import java.util.HashSet; import java.util.Set; import javax.swing.JPanel; public class MinecraftToolWindow { private JPanel panel; private Project project; private Set<MinecraftModule> mcModules = new HashSet<>(); public void setProjectAndInit(@NotNull Project project) { this.project = project; final Module[] modules = ModuleManager.getInstance(project).getModules(); for (Module module : modules) { final MinecraftModule instance = MinecraftModule.getInstance(module); if (instance != null) { mcModules.add(instance); } } } public JPanel getPanel() { return panel; } }
Remove test for <link> removal
'use strict'; var chai = require('chai'); var expect = chai.expect; var requireHelper = require('../../require_helper'); var resourceAdder = requireHelper('util/resourceAdder'); describe("resourceAdder", function(){ describe("scripts", function(){ it("should add", function(){ resourceAdder.addScript('test.js'); expect( $("script[src*='test.js']").length ).to.equal( 1 ); }); it("should remove on load", function(){ $("script[src*='test.js']")[0].onload(); expect( $("script[src*='test.js']").length ).to.equal( 0 ); }); }); describe("styles", function(){ it("should add", function(){ resourceAdder.addStyle('test.css'); expect( $("link[href*='test.css']").length ).to.equal( 1 ); }); }); });
'use strict'; var chai = require('chai'); var expect = chai.expect; var requireHelper = require('../../require_helper'); var resourceAdder = requireHelper('util/resourceAdder'); describe("resourceAdder", function(){ describe("scripts", function(){ it("should add", function(){ resourceAdder.addScript('test.js'); expect( $("script[src*='test.js']").length ).to.equal( 1 ); }); it("should remove on load", function(){ $("script[src*='test.js']")[0].onload(); expect( $("script[src*='test.js']").length ).to.equal( 0 ); }); }); describe("styles", function(){ it("should add", function(){ resourceAdder.addStyle('test.css'); expect( $("link[href*='test.css']").length ).to.equal( 1 ); }); it("should remove on load", function(){ $("link[href*='test.css']")[0].onload(); expect( $("link[href*='test.css']").length ).to.equal( 0 ); }); }); });
Remove json import, not needed yet
import sys, os sys.path.insert(0, os.path.abspath('./python-tastypie-client')) import tastypie_client url_root = "http://vorol-dev.cdlib.org/" path_collection_registry = "collection_registry/api/v1" url_api = url_root+path_collection_registry entrypoint_entrypoint_key = "list_entrypoint" entrypoint_schema_key = "schema" collection_name = "provenancialcollection" tp = tastypie_client.Api(url_api) provenancialcollection = None for c in tp.collections: #print c, dir(c), c.url try: c.url.index(collection_name) provenancialcollection = c except: pass print provenancialcollection.url #print type(provenancialcollection) #print dir(provenancialcollection) import time;time.sleep(5) obj_list = [] for obj in provenancialcollection:#.next(): #print "OBJ?", obj.fields if obj.fields['url_local']: print obj.fields['resource_uri'], obj.fields['url_local'] obj_list.append(obj) print "LENGTH:::", len(obj_list) print "COLLECTION:"#, dir(provenancialcollection) print provenancialcollection.meta print obj.fields #import code;code.interact(local=locals())
import json import sys, os sys.path.insert(0, os.path.abspath('./python-tastypie-client')) import tastypie_client url_root = "http://vorol-dev.cdlib.org/" path_collection_registry = "collection_registry/api/v1" url_api = url_root+path_collection_registry entrypoint_entrypoint_key = "list_entrypoint" entrypoint_schema_key = "schema" collection_name = "provenancialcollection" tp = tastypie_client.Api(url_api) provenancialcollection = None for c in tp.collections: #print c, dir(c), c.url try: c.url.index(collection_name) provenancialcollection = c except: pass print provenancialcollection.url #print type(provenancialcollection) #print dir(provenancialcollection) import time;time.sleep(5) obj_list = [] for obj in provenancialcollection:#.next(): #print "OBJ?", obj.fields if obj.fields['url_local']: print obj.fields['resource_uri'], obj.fields['url_local'] obj_list.append(obj) print "LENGTH:::", len(obj_list) print "COLLECTION:"#, dir(provenancialcollection) print provenancialcollection.meta print obj.fields #import code;code.interact(local=locals())
BB-8120: Test and merge - cr fixes
<?php namespace Oro\Bundle\ConfigBundle\Tests\Behat\Context; use Oro\Bundle\ConfigBundle\Tests\Behat\Element\SidebarConfigMenu; use Oro\Bundle\TestFrameworkBundle\Behat\Context\OroFeatureContext; use Oro\Bundle\TestFrameworkBundle\Behat\Element\OroPageObjectAware; use Oro\Bundle\TestFrameworkBundle\Tests\Behat\Context\PageObjectDictionary; class FeatureContext extends OroFeatureContext implements OroPageObjectAware { use PageObjectDictionary; /** * Click link on sidebar in configuration menu * * Example: Given I click "Inventory" on configuration sidebar * * @When /^(?:|I )click "(?P<link>(?:[^"]|\\")*)" on configuration sidebar$/ */ public function clickLinkOnConfigurationSidebar($link) { /** @var SidebarConfigMenu $sidebarConfigMenu */ $sidebarConfigMenu = $this->getPage()->getElement('SidebarConfigMenu'); $sidebarConfigMenu->clickLink($link); } }
<?php namespace Oro\Bundle\ConfigBundle\Tests\Behat\Context; use Oro\Bundle\ConfigBundle\Tests\Behat\Element\SidebarConfigMenu; use Oro\Bundle\TestFrameworkBundle\Behat\Context\OroFeatureContext; use Oro\Bundle\TestFrameworkBundle\Behat\Element\OroPageObjectAware; use Oro\Bundle\TestFrameworkBundle\Tests\Behat\Context\PageObjectDictionary; class FeatureContext extends OroFeatureContext implements OroPageObjectAware { use PageObjectDictionary; /** * Click on button or link on left panel in configuration menu * Example: Given I click "Edit" on left panel * Example: When I click "Save and Close" on left panel * * @When /^(?:|I )click "(?P<button>(?:[^"]|\\")*)" on left panel$/ */ public function pressButtonOnLeftPanel($button) { /** @var SidebarConfigMenu $sidebarConfigMenu */ $sidebarConfigMenu = $this->getPage()->getElement('SidebarConfigMenu'); $sidebarConfigMenu->clickLink($button); } }
Fix getting money from arcade games.
from saylua import db from saylua.wrappers import api_login_required from flask import g, request from models.db import Game, GameLog from saylua.utils import int_or_none import json # Send a score to the API. @api_login_required() def api_send_score(game_id): try: gameName = Game(game_id) except IndexError: return json.dumps(dict(error='Invalid game!')), 400 finally: if gameName == "blocks": # TODO sanity check the game log and other variables sent to catch # low hanging fruit attempts at cheating. data = request.get_json() score = int_or_none(data.get('score')) or 0 GameLog.record_score(g.user.id, game_id, score) g.user.cloud_coins += score db.session.commit() return json.dumps(dict(cloud_coins=g.user.cloud_coins, star_shards=g.user.star_shards)) return json.dumps(dict(error='Bad request.')), 400
from saylua.wrappers import api_login_required from flask import g, request from models.db import Game, GameLog from saylua.utils import int_or_none import json # Send a score to the API. @api_login_required() def api_send_score(game_id): try: gameName = Game(game_id) except IndexError: return json.dumps(dict(error='Invalid game!')), 400 finally: if gameName == "blocks": # TODO sanity check the game log and other variables sent to catch # low hanging fruit attempts at cheating. data = request.get_json() score = int_or_none(data.get('score')) or 0 GameLog.record_score(g.user.id, game_id, score) g.user.cloud_coins += score return json.dumps(dict(cloud_coins=g.user.cloud_coins, star_shards=g.user.star_shards)) return json.dumps(dict(error='Bad request.')), 400
Drop trailing slashes from routing paths
<?php error_reporting(E_ALL); ini_set('display_errors', 1); /* * Establish our routing table. */ $router = array(); $router['registrars'] = 'registrars'; $router['validator'] = 'validator'; $router['submit'] = 'submit'; $router['bounce'] = 'bounce'; /* * Identify which method is being requested. */ $url_components = parse_url($_SERVER['REQUEST_URI']); $method = str_replace('/api/', '', $url_components['path']); if (strpos($method, '/') !== FALSE) { $method = substr($url_components['path'], 1, strpos($method, '/')); } if ( ($method === FALSE) || !isset($router[$method]) ) { header("HTTP/1.0 404 Not Found"); echo '404 Not Found'; } include $router[$method] . '.php'; /* * Enable cross-origin resource sharing (CORS). */ header("Access-Control-Allow-Origin: *");
<?php error_reporting(E_ALL); ini_set('display_errors', 1); /* * Establish our routing table. */ $router = array(); $router['registrars'] = 'registrars/'; $router['validator'] = 'validator/'; $router['submit'] = 'submit/'; $router['bounce'] = 'bounce/'; /* * Identify which method is being requested. */ $url_components = parse_url($_SERVER['REQUEST_URI']); $method = str_replace('/api/', '', $url_components['path']); if (strpos($method, '/') !== FALSE) { $method = substr($url_components['path'], 1, strpos($method, '/')); } if ( ($method === FALSE) || !isset($router[$method]) ) { header("HTTP/1.0 404 Not Found"); echo '404 Not Found'; } include $router[$method] . '.php'; /* * Enable cross-origin resource sharing (CORS). */ header("Access-Control-Allow-Origin: *");
Exit with status code 1 if retrieval of the configuration filename from the environment fails
# -*- coding: utf-8 -*- """ byceps.util.system ~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2016 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ import os import sys CONFIG_VAR_NAME = 'BYCEPS_CONFIG' def get_config_filename_from_env(): """Return the configuration filename set via environment variable. Raise an exception if it isn't set. """ env = os.environ.get(CONFIG_VAR_NAME) if not env: raise Exception( "No configuration file was specified via the '{}' " "environment variable.".format(CONFIG_VAR_NAME)) return env def get_config_filename_from_env_or_exit(): """Return the configuration filename set via environment variable. Exit if it isn't set. """ try: return get_config_filename_from_env() except Exception as e: sys.stderr.write("{}\n".format(e)) sys.exit(1)
# -*- coding: utf-8 -*- """ byceps.util.system ~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2016 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ import os import sys CONFIG_VAR_NAME = 'BYCEPS_CONFIG' def get_config_filename_from_env(): """Return the configuration filename set via environment variable. Raise an exception if it isn't set. """ env = os.environ.get(CONFIG_VAR_NAME) if not env: raise Exception( "No configuration file was specified via the '{}' " "environment variable.".format(CONFIG_VAR_NAME)) return env def get_config_filename_from_env_or_exit(): """Return the configuration filename set via environment variable. Exit if it isn't set. """ try: return get_config_filename_from_env() except Exception as e: sys.stderr.write("{}\n".format(e)) sys.exit()
Add backwards compatibility for old Symfony versions
<?php namespace AppBundle\Controller; use AppBundle\Model\CastingUser; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; if (class_exists('Symfony\\Bundle\\FrameworkBundle\\Controller\\AbstractController')) { class ParentFormController extends AbstractController {} } else { class ParentFormController extends Controller {} } class FormController extends ParentFormController { public function create(Request $request) { $user = new CastingUser(); $form = $this->createFormBuilder($user) ->add('name') ->add('password') ->add('date_of_birth') ->add('is_admin') ->add('submit', SubmitType::class) ->getForm(); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $user->save(); return new Response('Successfully created user!'); } return $this->render('form/create.twig', ['form' => $form->createView()]); } }
<?php namespace AppBundle\Controller; use AppBundle\Model\CastingUser; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; class FormController extends AbstractController { public function create(Request $request) { $user = new CastingUser(); $form = $this->createFormBuilder($user) ->add('name') ->add('password') ->add('date_of_birth') ->add('is_admin') ->add('submit', SubmitType::class) ->getForm(); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $user->save(); return new Response('Successfully created user!'); } return $this->render('form/create.twig', ['form' => $form->createView()]); } }
Revert "Removed unused method. PL-1321." This reverts commit a43684f4c0f4753d6906ca6f7e1cf9409bc24488.
package com.amee.platform.science; import org.joda.time.DateTime; import java.util.Date; public abstract class BaseDate extends java.util.Date { protected String dateStr; public BaseDate(long time) { setTime(time); setDefaultDateStr(); } public BaseDate(String dateStr) { super(); if (dateStr != null) { setTime(parseStr(dateStr)); this.dateStr = dateStr; } else { setTime(defaultDate()); setDefaultDateStr(); } } protected abstract long parseStr(String dateStr); protected abstract void setDefaultDateStr(); protected abstract long defaultDate(); public String toString() { return dateStr; } public DateTime toDateTime() { return new DateTime(this.getTime()); } public Date toDate() { return new DateTime(this.getTime()).toDate(); } }
package com.amee.platform.science; import org.joda.time.DateTime; import java.util.Date; public abstract class BaseDate extends java.util.Date { protected String dateStr; public BaseDate(long time) { setTime(time); setDefaultDateStr(); } public BaseDate(String dateStr) { super(); if (dateStr != null) { setTime(parseStr(dateStr)); this.dateStr = dateStr; } else { setTime(defaultDate()); setDefaultDateStr(); } } protected abstract long parseStr(String dateStr); protected abstract void setDefaultDateStr(); protected abstract long defaultDate(); public String toString() { return dateStr; } public DateTime toDateTime() { return new DateTime(this.getTime()); } }
Add loading spinner to the podcast details pane Shown while waiting for the contents for the pane.
<div id="podcast-details" class="sidebar-content" ng-controller="PodcastDetailsController" ng-if="contentType=='podcastChannel' || contentType=='podcastEpisode'"> <div class="albumart clickable" ng-show="details.image" ng-click="scrollToEntity(contentType, entity)"></div> <dl class="tags" ng-show="details"> <dt ng-repeat-start="(key, value) in details" ng-if="keyShown(key, value)">{{ formatKey(key) }}</dt> <dd ng-if="keyShown(key, value) && keyHasDetails(key)" class="clickable" ng-click="showKeyDetails(key, value)">{{ formatValue(key, value) }}<button class="icon-info"></button></dd> <dd ng-if="keyShown(key, value) && keyMayCollapse(key)" collapsible-html="formatValue(key, value)" on-expand="adjustFixedPositions"></dd> <dd ng-repeat-end ng-if="keyShown(key, value) && !keyHasDetails(key) && !keyMayCollapse(key)" ng-bind-html="formatValue(key, value)"></dd> </dl> <div class="icon-loading" ng-if="!details"></div> </div>
<div id="podcast-details" class="sidebar-content" ng-controller="PodcastDetailsController" ng-if="contentType=='podcastChannel' || contentType=='podcastEpisode'"> <div class="albumart clickable" ng-show="details.image" ng-click="scrollToEntity(contentType, entity)"></div> <dl class="tags"> <dt ng-repeat-start="(key, value) in details" ng-if="keyShown(key, value)">{{ formatKey(key) }}</dt> <dd ng-if="keyShown(key, value) && keyHasDetails(key)" class="clickable" ng-click="showKeyDetails(key, value)">{{ formatValue(key, value) }}<button class="icon-info"></button></dd> <dd ng-if="keyShown(key, value) && keyMayCollapse(key)" collapsible-html="formatValue(key, value)" on-expand="adjustFixedPositions"></dd> <dd ng-repeat-end ng-if="keyShown(key, value) && !keyHasDetails(key) && !keyMayCollapse(key)" ng-bind-html="formatValue(key, value)"></dd> </dl> </div>
Adjust nav element scrolling functions The functions are now functioning in Firefox as well as Chrome
$(document).ready(function () { // Selecting some DOM elements for further handling var dom = { window: $(window), body: $('body'), navItem: $('.nav-item'), navBarLogo: $('.navbar-logo') }; // Handling the navigation links dom.navItem.click(function () { var scrollElement = $(this).find('.nav-link').data('link'), scrollPosition = $(scrollElement).offset().top - 100; $('html, body').animate({ scrollTop: scrollPosition }, 500); }); // Displaying the logo at the navigation bar dom.window.scroll(function () { if (dom.window.scrollTop() >= 300) { dom.navBarLogo.addClass('show'); } else { dom.navBarLogo.removeClass('show'); } }); // Scroll to top on the logo click dom.navBarLogo.click(function () { $('html, body').animate({ scrollTop: 0 }, 300); }); // Promo stuff console.log('Powered by Jekyll Instagram Portfolio Theme'); console.log('Project: https://github.com/portfolio-central/jekyll-instagram-portfolio-theme') });
$(document).ready(function () { // Selecting some DOM elements for further handling var dom = { window: $(window), body: $('body'), navItem: $('.nav-item'), navBarLogo: $('.navbar-logo') }; // Handling the navigation links dom.navItem.click(function () { var scrollElement = $(this).find('.nav-link').data('link'), scrollPosition = $(scrollElement).offset().top - 100; dom.body.animate({ scrollTop: scrollPosition }, 500); }); // Displaying the logo at the navigation bar dom.window.scroll(function () { if (dom.window.scrollTop() >= 300) { dom.navBarLogo.addClass('show'); } else { dom.navBarLogo.removeClass('show'); } }); // Scroll to top on the logo click dom.navBarLogo.click(function () { dom.body.animate({ scrollTop: 0 }, 300); }); // Promo stuff console.log('Powered by Jekyll Instagram Portfolio Theme'); console.log('Project: https://github.com/portfolio-central/jekyll-instagram-portfolio-theme') });
Change test directory to get it work on travis ci
<?php namespace Tooly\Tests\Script\Helper; use org\bovigo\vfs\vfsStream; use phpmock\phpunit\PHPMock; use Tooly\Script\Helper\Filesystem; /** * @package Tooly\Tests\Script\Helper */ class FilesystemTest extends \PHPUnit_Framework_TestCase { /** * @var Filesystem */ private $filesystem; /** * @var string */ private $testDirectory; /** * @var string */ private $testFile; public function setUp() { $this->filesystem = new Filesystem; $this->testDirectory = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'test'; $this->testFile = $this->testDirectory . DIRECTORY_SEPARATOR . 'file'; } public function tearDown() { if (is_dir($this->testDirectory)) { $this->filesystem->removeDirectory($this->testDirectory); } } public function testCanRelativeSymlinkAFile() { $symlink = $this->testDirectory . DIRECTORY_SEPARATOR . '/foo/symlink'; $this->assertTrue($this->filesystem->symlinkFile($this->testFile, $symlink)); $this->assertNotEquals('/', substr(readlink($symlink), '0', 1)); } }
<?php namespace Tooly\Tests\Script\Helper; use org\bovigo\vfs\vfsStream; use phpmock\phpunit\PHPMock; use Tooly\Script\Helper\Filesystem; /** * @package Tooly\Tests\Script\Helper */ class FilesystemTest extends \PHPUnit_Framework_TestCase { /** * @var Filesystem */ private $filesystem; /** * @var string */ private $testDirectory; /** * @var string */ private $testFile; public function setUp() { $this->filesystem = new Filesystem; $this->testDirectory = sys_get_temp_dir(); $this->testFile = $this->testDirectory . DIRECTORY_SEPARATOR . 'file'; } public function tearDown() { if (is_dir($this->testDirectory)) { $this->filesystem->removeDirectory($this->testDirectory); } } public function testCanRelativeSymlinkAFile() { $symlink = $this->testDirectory . DIRECTORY_SEPARATOR . '/foo/symlink'; $this->assertTrue($this->filesystem->symlinkFile($this->testFile, $symlink)); $this->assertNotEquals('/', substr(readlink($symlink), '0', 1)); } }
Add ordering by weight when getting terms by vocabulary.
<?php namespace AbleCore; class TaxonomyTerm extends EntityExtension { /** * Gets the entity type of the current class. * * @return string The entity type. */ static function getEntityType() { return 'taxonomy_term'; } /** * By Vocabulary * * Gets all taxonomy terms by the specified vocabulary. * * @param string $vocabulary_machine_name The machine name of the vocabulary. * * @return array An array of TaxonomyTerm items. */ public static function byVocabulary($vocabulary_machine_name) { $query = db_select('taxonomy_term_data', 'td'); $query->addJoin('inner', 'taxonomy_vocabulary', 'tv', 'tv.vid = td.vid'); $query->condition('tv.machine_name', $vocabulary_machine_name); $query->addField('td', 'tid'); $query->orderBy('weight'); return static::mapQuery($query); } }
<?php namespace AbleCore; class TaxonomyTerm extends EntityExtension { /** * Gets the entity type of the current class. * * @return string The entity type. */ static function getEntityType() { return 'taxonomy_term'; } /** * By Vocabulary * * Gets all taxonomy terms by the specified vocabulary. * * @param string $vocabulary_machine_name The machine name of the vocabulary. * * @return array An array of TaxonomyTerm items. */ public static function byVocabulary($vocabulary_machine_name) { $query = db_select('taxonomy_term_data', 'td'); $query->addJoin('inner', 'taxonomy_vocabulary', 'tv', 'tv.vid = td.vid'); $query->condition('tv.machine_name', $vocabulary_machine_name); $query->addField('td', 'tid'); return static::mapQuery($query); } }
Declare dependency on httplib2, and bump version.
# Copyright 2015 Alburnum Ltd. This software is licensed under # the GNU Affero General Public License version 3 (see LICENSE). """Distutils installer for alburnum-maas-client.""" from __future__ import ( absolute_import, print_function, unicode_literals, ) __metaclass__ = type from setuptools import ( find_packages, setup, ) setup( name='alburnum-maas-client', author='Gavin Panella', author_email='gavinpanella@gmail.com', url='https://github.com/alburnum/alburnum-maas-client', version="0.1.2", classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Programming Language :: Python :: 3', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries', ], packages=find_packages(), install_requires={ "httplib2 >= 0.9", }, test_suite="alburnum.maas.tests", description="A client API library specially for MAAS.", )
# Copyright 2015 Alburnum Ltd. This software is licensed under # the GNU Affero General Public License version 3 (see LICENSE). """Distutils installer for alburnum-maas-client.""" from __future__ import ( absolute_import, print_function, unicode_literals, ) __metaclass__ = type from setuptools import ( find_packages, setup, ) setup( name='alburnum-maas-client', author='Gavin Panella', author_email='gavinpanella@gmail.com', url='https://github.com/alburnum/alburnum-maas-client', version="0.1.1", classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Programming Language :: Python :: 3', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries', ], packages=find_packages(), test_suite="alburnum.maas.tests", description="A client API library specially for MAAS.", )
Move backward on FactoryPass type
<?php /* * This file is part of the OverblogThriftBundle package. * * (c) Overblog <http://github.com/overblog/> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Overblog\ThriftBundle; use Overblog\ThriftBundle\DependencyInjection\Compiler\FactoryPass; use Symfony\Component\DependencyInjection\Compiler\PassConfig; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\HttpKernel\Bundle\Bundle; /** * Overblog Thrift Bundle. * * @author Xavier HAUSHERR */ class OverblogThriftBundle extends Bundle { /** * Builds the bundle. * * It is only ever called once when the cache is empty. * * This method can be overridden to register compilation passes, * other extensions, ... * * @param ContainerBuilder $container A ContainerBuilder instance */ public function build(ContainerBuilder $container) { parent::build($container); $container->addCompilerPass(new FactoryPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION, 1000) } }
<?php /* * This file is part of the OverblogThriftBundle package. * * (c) Overblog <http://github.com/overblog/> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Overblog\ThriftBundle; use Overblog\ThriftBundle\DependencyInjection\Compiler\FactoryPass; use Symfony\Component\DependencyInjection\Compiler\PassConfig; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\HttpKernel\Bundle\Bundle; /** * Overblog Thrift Bundle. * * @author Xavier HAUSHERR */ class OverblogThriftBundle extends Bundle { /** * Builds the bundle. * * It is only ever called once when the cache is empty. * * This method can be overridden to register compilation passes, * other extensions, ... * * @param ContainerBuilder $container A ContainerBuilder instance */ public function build(ContainerBuilder $container) { parent::build($container); $container->addCompilerPass(new FactoryPass(), PassConfig::TYPE_BEFORE_REMOVING); } }
Mark the CSS3DBlueBox pixel test as failing. There seems to be a problem with this test, as it seems to change often after being rebaselined recently. BUG=416719 Review URL: https://codereview.chromium.org/587753004 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#296124}
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry.page import test_expectations # Valid expectation conditions are: # # Operating systems: # win, xp, vista, win7, mac, leopard, snowleopard, lion, mountainlion, # linux, chromeos, android # # GPU vendors: # amd, arm, broadcom, hisilicon, intel, imagination, nvidia, qualcomm, # vivante # # Specific GPUs can be listed as a tuple with vendor name and device ID. # Examples: ('nvidia', 0x1234), ('arm', 'Mali-T604') # Device IDs must be paired with a GPU vendor. class PixelExpectations(test_expectations.TestExpectations): def SetExpectations(self): # Sample Usage: # self.Fail('Pixel.Canvas2DRedBox', # ['mac', 'amd', ('nvidia', 0x1234)], bug=123) self.Fail('Pixel.CSS3DBlueBox',bug=416719) pass
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry.page import test_expectations # Valid expectation conditions are: # # Operating systems: # win, xp, vista, win7, mac, leopard, snowleopard, lion, mountainlion, # linux, chromeos, android # # GPU vendors: # amd, arm, broadcom, hisilicon, intel, imagination, nvidia, qualcomm, # vivante # # Specific GPUs can be listed as a tuple with vendor name and device ID. # Examples: ('nvidia', 0x1234), ('arm', 'Mali-T604') # Device IDs must be paired with a GPU vendor. class PixelExpectations(test_expectations.TestExpectations): def SetExpectations(self): # Sample Usage: # self.Fail('Pixel.Canvas2DRedBox', # ['mac', 'amd', ('nvidia', 0x1234)], bug=123) pass
Fix issue with empty content type header in request builder
<?php /** * HTTP request object factory * * This factory should be used in index.php for request object initialization. * Example: * * $validator = (new Validator)->setAdapter(new PhpFilters); * $request = RequestFactory::create($_SERVER['CONTENT_TYPE'])->setValidator($validator); * * @file RequestFactory.php * * PHP version 5.6+ * * @author Yancharuk Alexander <alex at itvault dot info> * @copyright © 2012-2017 Alexander Yancharuk <alex at itvault at info> * @date 2017-04-23 16:12 * @license The BSD 3-Clause License * <https://tldrlegal.com/license/bsd-3-clause-license-(revised)> */ namespace Veles\Request; class RequestFactory { /** * Create HTTP-request object depending on Content-type HTTP-header * * @param string $type Value of Content-type HTTP-header * * @return HttpRequestAbstract */ public static function create($type) { if (empty($type) || 0 === strpos($type, 'text/html')) { return new HttpGetRequest; } return new HttpPostRequest; } }
<?php /** * HTTP request object factory * * This factory should be used in index.php for request object initialization. * Example: * * $validator = (new Validator)->setAdapter(new PhpFilters); * $request = RequestFactory::create($_SERVER['CONTENT_TYPE'])->setValidator($validator); * * @file RequestFactory.php * * PHP version 5.6+ * * @author Yancharuk Alexander <alex at itvault dot info> * @copyright © 2012-2017 Alexander Yancharuk <alex at itvault at info> * @date 2017-04-23 16:12 * @license The BSD 3-Clause License * <https://tldrlegal.com/license/bsd-3-clause-license-(revised)> */ namespace Veles\Request; class RequestFactory { /** * Create HTTP-request object depending on Content-type HTTP-header * * @param string $type Value of Content-type HTTP-header * * @return HttpRequestAbstract */ public static function create($type) { if (!isset($type) or 0 === strpos($type, 'text/html')) { return new HttpGetRequest; } return new HttpPostRequest; } }