text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Make the script self starting
#!/usr/bin/env node /*jslint node: true */ 'use strict'; var cluster = require('cluster'); var netflow = require('node-netflowv9'); var numCPUs = require('os').cpus().length; var NetFlowStorage = require('./lib/NetFlowStorage.js'); main(); function main() { var nfStore = new NetFlowStorage(); if (cluster.isMaster) { // Setup, then fork the workers nfStore.createIndex(); for (var i = 0; i < numCPUs; i++) { cluster.fork(); } } else { // Setup the worker netflow(function(flow) { console.log('%s\t flows', flow.flows.length); for (var i = 0; i < flow.flows.length; i++) { nfStore.storeFlow(flow.flows[i]); } }).listen(2055); } }
/*jslint node: true */ 'use strict'; var cluster = require('cluster'); var netflow = require('node-netflowv9'); var numCPUs = require('os').cpus().length; var NetFlowStorage = require('./lib/NetFlowStorage.js'); main(); function main() { var nfStore = new NetFlowStorage(); if (cluster.isMaster) { // Setup, then fork the workers nfStore.createIndex(); for (var i = 0; i < numCPUs; i++) { cluster.fork(); } } else { // Setup the worker netflow(function(flow) { console.log('%s\t flows', flow.flows.length); for (var i = 0; i < flow.flows.length; i++) { nfStore.storeFlow(flow.flows[i]); } }).listen(2055); } }
Use new official java (openjdk-jre) base images
/** * Copyright 2014 Transmode AB * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package se.transmode.gradle.plugins.docker; import org.gradle.api.JavaVersion; /** * @author Matthias Grüter, matthias.gruter@transmode.com */ public enum JavaBaseImage { JAVA6("java:openjdk-6-jre", JavaVersion.VERSION_1_6), JAVA7("java:openjdk-7-jre", JavaVersion.VERSION_1_7), JAVA8("java:openjdk-8-jre", JavaVersion.VERSION_1_8); final String imageName; final JavaVersion target; JavaBaseImage(String imageName, JavaVersion target) { this.imageName = imageName; this.target = target; } public static JavaBaseImage imageFor(JavaVersion target) { for(JavaBaseImage image: JavaBaseImage.values()) { if(image.target == target) { return image; } } throw new IllegalArgumentException("No Java base image for target " + target + " found."); } }
/** * Copyright 2014 Transmode AB * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package se.transmode.gradle.plugins.docker; import org.gradle.api.JavaVersion; /** * @author Matthias Grüter, matthias.gruter@transmode.com */ public enum JavaBaseImage { JAVA6("fkautz/java6-jre", JavaVersion.VERSION_1_6), JAVA7("dockerfile/java", JavaVersion.VERSION_1_7), JAVA8("aglover/java8-pier", JavaVersion.VERSION_1_8); final String imageName; final JavaVersion target; JavaBaseImage(String imageName, JavaVersion target) { this.imageName = imageName; this.target = target; } public static JavaBaseImage imageFor(JavaVersion target) { for(JavaBaseImage image: JavaBaseImage.values()) { if(image.target == target) { return image; } } throw new IllegalArgumentException("No Java base image for the supplied target " + target + " found."); } }
Rename methods for creating spiders to be more clear and simple
package spider import "io" type spinFunc func(*Context) error type spiderFunc struct { method string url string body io.Reader fn spinFunc } func (s *spiderFunc) Setup(parent *Context) (*Context, error) { return NewHTTPContext(s.method, s.url, s.body) } func (s *spiderFunc) Spin(ctx *Context) error { return s.fn(ctx) } func NewHTTPSpider(method, url string, body io.Reader, fn spinFunc) *spiderFunc { return &spiderFunc{ method: method, url: url, body: body, fn: fn, } } func Get(url string, fn spinFunc) *spiderFunc { return NewHTTPSpider("GET", url, nil, fn) } func Post(url string, body io.Reader, fn spinFunc) *spiderFunc { return NewHTTPSpider("POST", url, body, fn) } func Put(url string, body io.Reader, fn spinFunc) *spiderFunc { return NewHTTPSpider("PUT", url, body, fn) } func Delete(url string, fn spinFunc) *spiderFunc { return NewHTTPSpider("DELETE", url, nil, fn) }
package spider import "io" type spinFunc func(*Context) error type spiderFunc struct { method string url string body io.Reader fn spinFunc } func (s *spiderFunc) Setup(parent *Context) (*Context, error) { return NewHTTPContext(s.method, s.url, s.body) } func (s *spiderFunc) Spin(ctx *Context) error { return s.fn(ctx) } func NewHTTPSpider(method, url string, body io.Reader, fn spinFunc) *spiderFunc { return &spiderFunc{ method: method, url: url, body: body, fn: fn, } } func NewGETSpider(url string, fn spinFunc) *spiderFunc { return NewHTTPSpider("GET", url, nil, fn) } func NewPOSTSpider(url string, body io.Reader, fn spinFunc) *spiderFunc { return NewHTTPSpider("POST", url, body, fn) } func NewPUTSpider(url string, body io.Reader, fn spinFunc) *spiderFunc { return NewHTTPSpider("PUT", url, body, fn) } func NewDELETESpider(url string, fn spinFunc) *spiderFunc { return NewHTTPSpider("DELETE", url, nil, fn) }
Add comment explaining non js prepended classes
require([ "jquery", "lib/analytics/analytics" ], function($, Analytics) { "use strict"; var omniCode = "LP highlights Insurance", analytics = new Analytics(); analytics.trackView(); // Set up Omniture event handlers var windowUnloadedFromSubmitClick = false; // If the user clicks anywhere else on the page, reset the click tracker $(document).on("click", function() { windowUnloadedFromSubmitClick = false; }); // When the user clicks on the submit button, track that it's what // is causing the onbeforeunload event to fire (below) $(document).on("click", "button.cta-button-primary", function(e) { windowUnloadedFromSubmitClick = true; e.stopPropagation(); }); // Before redirection (which the WN widget does, it's not a form submit) // if the user clicked on the submit button, track click with Omniture window.onbeforeunload = function() { if (windowUnloadedFromSubmitClick) { window.s.events = "event42"; window.s.t(); } }; // The following should really be using `.js-` prepended classes, but that's all in the Landing Pages repo. $(".nomads-links a").on("click", function() { analytics.track({ events: "event42" }); }); $(".article--row a").on("click", function() { window.s.linkTrackVars = "eVar54"; window.s.eVar54 = omniCode; window.s.events = "event45"; window.s.tl(this, "o", omniCode); }); });
require([ "jquery", "lib/analytics/analytics" ], function($, Analytics) { "use strict"; var omniCode = "LP highlights Insurance", analytics = new Analytics(); analytics.trackView(); // Set up Omniture event handlers var windowUnloadedFromSubmitClick = false; // If the user clicks anywhere else on the page, reset the click tracker $(document).on("click", function() { windowUnloadedFromSubmitClick = false; }); // When the user clicks on the submit button, track that it's what // is causing the onbeforeunload event to fire (below) $(document).on("click", "button.cta-button-primary", function(e) { windowUnloadedFromSubmitClick = true; e.stopPropagation(); }); // Before redirection (which the WN widget does, it's not a form submit) // if the user clicked on the submit button, track click with Omniture window.onbeforeunload = function() { if (windowUnloadedFromSubmitClick) { window.s.events = "event42"; window.s.t(); } }; $(".nomads-links a").on("click", function() { analytics.track({ events: "event42" }); }); $(".article--row a").on("click", function() { window.s.linkTrackVars = "eVar54"; window.s.eVar54 = omniCode; window.s.events = "event45"; window.s.tl(this, "o", omniCode); }); });
Use context manager for the offline tests
# coding: utf-8 # Python modules from __future__ import unicode_literals, print_function import os from codecs import open from contextlib import contextmanager # Third-party modules import pytest # Project modules from requests import Response from tests import request_is_valid def make_requests_get_mock(filename): def mockreturn(*args, **kwargs): response = Response() with open(os.path.join(os.path.dirname(__file__), '../assets', filename), 'r', 'utf-8') as fd: response._content = fd.read().encode('utf-8') return response return mockreturn class ContextualTest(object): def __init__(self, monkeypatch, manager, action, service): self.manager = manager self.action = action self.service = service monkeypatch.setattr('requests.post', make_requests_get_mock(self.action + '_response.xml')) def close(self): request = getattr(self.manager, self.service + '_request') assert request_is_valid(request, self.action, self.service)
# coding: utf-8 from __future__ import unicode_literals, print_function import os import pytest from codecs import open from contextlib import contextmanager from requests import Response def make_requests_get_mock(filename): def mockreturn(*args, **kwargs): response = Response() with open(os.path.join(os.path.dirname(__file__), 'assets', filename), 'r', 'utf-8') as fd: response._content = fd.read().encode('utf-8') return response return mockreturn def make_simple_text_mock(filename): def mockreturn(*args, **kwargs): with open(os.path.join(os.path.dirname(__file__), 'assets', filename), 'r', 'utf-8') as fd: return fd.read() return mockreturn @contextmanager def assert_raises(exception_class, msg=None): """Check that an exception is raised and its message contains `msg`.""" with pytest.raises(exception_class) as exception: yield if msg is not None: message = '%s' % exception assert msg.lower() in message.lower()
Allow more liberal promise detection, es5 compat
'use strict'; var Promise = require('es6-promise').Promise; module.exports = function(array, haltCallback) { if(!(haltCallback instanceof Function)) { haltCallback = function() { return true; }; } return new Promise(function(resolve, reject) { var i = 0, len = array.length, results = []; function processPromise(result) { results[i] = result; if(!haltCallback(result)) { return resolve(results); } i++; next(); } function next() { if(i >= len) return resolve(results); var method = array[i]; if(typeof method !== 'function') { return processPromise(method); } var p = method(); if(typeof p.then === 'function' && typeof p.catch === 'function') { p.then(processPromise).catch(reject); } else { processPromise(p); } } next(); }); };
'use strict'; var Promise = require('es6-promise').Promise; module.exports = function(array, haltCallback) { if(!(haltCallback instanceof Function)) { haltCallback = function() { return true; }; } return new Promise(function(resolve, reject) { var i = 0, len = array.length, results = []; function processPromise(result) { results[i] = result; if(!haltCallback(result)) { return resolve(results); } i++; next(); } function next() { if(i >= len) return resolve(results); var method = array[i]; if(!(method instanceof Function)) { return processPromise(method); } var p = method(); if((p instanceof Promise)) { p.then(processPromise).catch(reject); } else { processPromise(p); } } next(); }); };
Make imagenet server tester logging better.
#!/usr/bin/python import logging def _configure_logging(): """ Configure logging handlers. """ # Configure root logger. root = logging.getLogger() root.setLevel(logging.DEBUG) file_handler = logging.FileHandler("test_image_getter.log") file_handler.setLevel(logging.DEBUG) stream_handler = logging.StreamHandler() stream_handler.setLevel(logging.INFO) formatter = logging.Formatter("%(name)s@%(asctime)s: " + "[%(levelname)s] %(message)s") file_handler.setFormatter(formatter) stream_handler.setFormatter(formatter) root.addHandler(file_handler) root.addHandler(stream_handler) # Some modules need logging configured immediately to work. _configure_logging() import os import cv2 import numpy as np import image_getter def main(): logging.info("Starting...") getter = image_getter.FilteredImageGetter("ilsvrc12_urls.txt", "image_cache", 10, preload_batches=2) for x in range(0, 3): batch = getter.get_random_train_batch() print batch[1] print len(batch[1]) i = 0 for image in batch[0]: print "Showing image: %d" % (i) i += 1 cv2.imshow("test", np.transpose(image, (1, 2, 0))) cv2.waitKey(0) main()
#!/usr/bin/python import logging import os import cv2 import numpy as np import image_getter def main(): # Configure root logger. root = logging.getLogger() root.setLevel(logging.DEBUG) file_handler = logging.FileHandler("test_image_getter.log") file_handler.setLevel(logging.DEBUG) stream_handler = logging.StreamHandler() stream_handler.setLevel(logging.INFO) formatter = logging.Formatter("%(name)s@%(asctime)s: " + "[%(levelname)s] %(message)s") file_handler.setFormatter(formatter) stream_handler.setFormatter(formatter) root.addHandler(file_handler) root.addHandler(stream_handler) root.info("Starting...") getter = image_getter.FilteredImageGetter("ilsvrc12_urls.txt", "image_cache", 10, preload_batches=2) for x in range(0, 3): batch = getter.get_random_test_batch() print batch[1] print len(batch[1]) i = 0 for image in batch[0]: print "Showing image: %d" % (i) i += 1 cv2.imshow("test", np.transpose(image, (1, 2, 0))) cv2.waitKey(0) main()
Remove a useless 'use' directive.
<?php namespace Predis; use Predis\Network\IConnection; use Predis\Network\IConnectionCluster; class Utils { public static function isCluster(IConnection $connection) { return $connection instanceof IConnectionCluster; } public static function onCommunicationException(CommunicationException $exception) { if ($exception->shouldResetConnection()) { $connection = $exception->getConnection(); if ($connection->isConnected()) { $connection->disconnect(); } } throw $exception; } public static function filterArrayArguments(Array $arguments) { if (count($arguments) === 1 && is_array($arguments[0])) { return $arguments[0]; } return $arguments; } }
<?php namespace Predis; use Predis\Network\IConnection; use Predis\Network\IConnectionCluster; use Predis\Network\ConnectionCluster; class Utils { public static function isCluster(IConnection $connection) { return $connection instanceof IConnectionCluster; } public static function onCommunicationException(CommunicationException $exception) { if ($exception->shouldResetConnection()) { $connection = $exception->getConnection(); if ($connection->isConnected()) { $connection->disconnect(); } } throw $exception; } public static function filterArrayArguments(Array $arguments) { if (count($arguments) === 1 && is_array($arguments[0])) { return $arguments[0]; } return $arguments; } }
Add get_read_only and remove old change_view customization
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django_services import admin from ..service.maintenance import MaintenanceService from ..forms import MaintenanceForm class MaintenanceAdmin(admin.DjangoServicesAdmin): service_class = MaintenanceService search_fields = ("scheduled_for", "description", "maximum_workers", 'status') list_display = ("scheduled_for", "description", "maximum_workers", 'status') fields = ( "description", "scheduled_for", "main_script", "rollback_script", "host_query","maximum_workers", "status", "celery_task_id",) save_on_top = True form = MaintenanceForm def get_readonly_fields(self, request, obj=None): maintenance = obj if maintenance: if maintenance.celery_task_id: return self.fields return ('status', 'celery_task_id',)
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django_services import admin from ..models import Maintenance from ..service.maintenance import MaintenanceService from ..forms import MaintenanceForm class MaintenanceAdmin(admin.DjangoServicesAdmin): service_class = MaintenanceService search_fields = ("scheduled_for", "description", "maximum_workers", 'status') list_display = ("scheduled_for", "description", "maximum_workers", 'status') fields = ( "description", "scheduled_for", "main_script", "rollback_script", "host_query","maximum_workers", "status", "celery_task_id",) save_on_top = True readonly_fields = ('status', 'celery_task_id') form = MaintenanceForm def change_view(self, request, object_id, form_url='', extra_context=None): maintenance = Maintenance.objects.get(id=object_id) if maintenance.celery_task_id: self.readonly_fields = self.fields return super(MaintenanceAdmin, self).change_view(request, object_id, form_url, extra_context=extra_context)
Support both json and stdout the same
import csv from argparse import ArgumentParser from json import dumps from pycargr.model import to_dict from pycargr.parser import parse_car_page parser = ArgumentParser() parser.add_argument('car_ids', nargs='+') parser.add_argument('--output', choices=['csv', 'json', 'stdout'], default='stdout') def main(): args = parser.parse_args() car_ids = args.car_ids output = args.output results = [] for cid in car_ids: results.append(to_dict(parse_car_page(cid))) if output == 'csv': with open('data.csv', 'w') as f: writer = csv.DictWriter(f, fieldnames=results[0].keys()) writer.writeheader() for d in results: # images is a list - not suitable for csv d.pop('images') writer.writerow(d) elif output == 'json' or output == 'stdout': print(dumps(results, sort_keys=True, indent=4, ensure_ascii=False)) if __name__ == '__main__': main()
import csv from argparse import ArgumentParser from json import dumps from pycargr.model import to_dict from pycargr.parser import parse_car_page parser = ArgumentParser() parser.add_argument('car_ids', nargs='+') parser.add_argument('--output', choices=['csv', 'json', 'stdout'], default='stdout') def main(): args = parser.parse_args() car_ids = args.car_ids output = args.output results = [] for cid in car_ids: results.append(to_dict(parse_car_page(cid))) if output == 'csv': with open('data.csv', 'w') as f: writer = csv.DictWriter(f, fieldnames=results[0].keys()) writer.writeheader() for d in results: # images is a list - not suitable for csv d.pop('images') writer.writerow(d) elif output == 'stdout': print(dumps(results, sort_keys=True, indent=4, ensure_ascii=False)) if __name__ == '__main__': main()
Add simple error handling during iframe creation.
var Promise = require('es6-promise').Promise; module.exports = { init: function(url) { createIframe(url) .then(sendHandshake) .then(undefined, errorHandler); } }; function createIframe(url) { var iframe = document.createElement('iframe'); iframe.src = url; var iframeLoaded = new Promise(function(resolve, reject) { try { onIframeLoad(iframe, resolve.bind(null, iframe)); } catch (ex) { reject(ex); } }); document.body.appendChild(iframe); return iframeLoaded; } function onIframeLoad(iframe, callback) { if (iframe.attachEvent){ iframe.attachEvent('onload', callback); } else { iframe.addEventListener('load', callback, false); } } function sendHandshake(iframe) { send(iframe, 'handshake'); } function send(iframe, data) { iframe.contentWindow.postMessage(data); } function errorHandler(error) { console.error(error.toString()); console.error(error.stack); }
var Promise = require('es6-promise').Promise; module.exports = { init: function(url) { createIframe(url) .then(sendHandshake); } }; function createIframe(url) { var iframe = document.createElement('iframe'); iframe.src = url; var iframeLoaded = new Promise(function(resolve, reject) { onIframeLoad(iframe, resolve.bind(null, iframe)); }); document.body.appendChild(iframe); return iframeLoaded; } function onIframeLoad(iframe, callback) { if (iframe.attachEvent){ iframe.attachEvent('onload', callback); } else { iframe.addEventListener('load', callback, false); } } function sendHandshake(iframe) { send(iframe, 'handshake'); } function send(iframe, data) { iframe.contentWindow.postMessage(data); }
Remove deprecated experiment details field from api
from rest_framework import serializers, viewsets from rest_framework import filters from django.contrib.auth.models import User from dakis.core.models import Experiment, Task class ExperimentSerializer(serializers.HyperlinkedModelSerializer): id = serializers.IntegerField(label='ID', read_only=True) class Meta: model = Experiment exclude = ('author',) def create(self, data): user = self.context['request'].user if user.is_authenticated(): data['author'] = user return super(ExperimentSerializer, self).create(data) class TaskSerializer(serializers.HyperlinkedModelSerializer): id = serializers.IntegerField(label='ID', read_only=True) class Meta: model = Task class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('first_name', 'last_name', 'username', 'email') class ExperimentViewSet(viewsets.ModelViewSet): queryset = Experiment.objects.all() serializer_class = ExperimentSerializer class TaskViewSet(viewsets.ModelViewSet): queryset = Task.objects.all() serializer_class = TaskSerializer filter_fields = ('experiment', 'func_cls', 'func_id', 'status') filter_backends = (filters.DjangoFilterBackend,) class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer
from rest_framework import serializers, viewsets from rest_framework import filters from django.contrib.auth.models import User from dakis.core.models import Experiment, Task class ExperimentSerializer(serializers.HyperlinkedModelSerializer): id = serializers.IntegerField(label='ID', read_only=True) class Meta: model = Experiment exclude = ('author', 'details') def create(self, data): user = self.context['request'].user if user.is_authenticated(): data['author'] = user return super(ExperimentSerializer, self).create(data) class TaskSerializer(serializers.HyperlinkedModelSerializer): id = serializers.IntegerField(label='ID', read_only=True) class Meta: model = Task class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('first_name', 'last_name', 'username', 'email') class ExperimentViewSet(viewsets.ModelViewSet): queryset = Experiment.objects.all() serializer_class = ExperimentSerializer class TaskViewSet(viewsets.ModelViewSet): queryset = Task.objects.all() serializer_class = TaskSerializer filter_fields = ('experiment', 'func_cls', 'func_id', 'status') filter_backends = (filters.DjangoFilterBackend,) class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer
Handle spaces in older versions of Illuminate
<?php namespace Silber\Bouncer\Database\Titles; use Illuminate\Support\Str; abstract class Title { /** * The human-readable title. * * @var string */ protected $title = ''; /** * Convert the given string into a human-readable format. * * @param string $value * @return string */ protected function humanize($value) { // Older versions of Laravel's inflector strip out spaces // in the original string, so we'll first swap out all // spaces with underscores, then convert them back. $value = str_replace(' ', '_', $value); // First we'll convert the string to snake case. Then we'll // convert all dashes and underscores to spaces. Finally, // we'll add a space before a pound (Laravel doesn't). $value = Str::snake($value); $value = preg_replace('~(?:-|_)+~', ' ', $value); $value = preg_replace('~([^ ])(?:#)+~', '$1 #', $value); return ucfirst($value); } /** * Get the title as a string. * * @return string */ public function __toString() { return $this->title; } }
<?php namespace Silber\Bouncer\Database\Titles; use Illuminate\Support\Str; abstract class Title { /** * The human-readable title. * * @var string */ protected $title = ''; /** * Convert the given string into a human-readable format. * * @param string $value * @return string */ protected function humanize($value) { // First we'll convert the string to snake case. Then we'll // convert all dashes and underscores to spaces. Finally, // we'll add a space before a pound (Laravel doesn't). $value = Str::snake($value); $value = preg_replace('~(?:-|_)+~', ' ', $value); $value = preg_replace('~([^ ])(?:#)+~', '$1 #', $value); return ucfirst($value); } /** * Get the title as a string. * * @return string */ public function __toString() { return $this->title; } }
Increase timeout of ukwsj to get more consistent SKP captures BUG=skia:3574 TBR=borenet NOTRY=true Review URL: https://codereview.chromium.org/1038443002
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=W0401,W0614 from telemetry.page import page as page_module from telemetry.page import page_set as page_set_module class SkiaBuildbotDesktopPage(page_module.Page): def __init__(self, url, page_set): super(SkiaBuildbotDesktopPage, self).__init__( url=url, page_set=page_set, credentials_path='data/credentials.json') self.user_agent_type = 'tablet' self.archive_data_file = 'data/skia_ukwsj_nexus10.json' def RunNavigateSteps(self, action_runner): action_runner.NavigateToPage(self) action_runner.Wait(15) class SkiaUkwsjNexus10PageSet(page_set_module.PageSet): """ Pages designed to represent the median, not highly optimized web """ def __init__(self): super(SkiaUkwsjNexus10PageSet, self).__init__( user_agent_type='tablet', archive_data_file='data/skia_ukwsj_nexus10.json') urls_list = [ # Why: for Clank CY 'http://uk.wsj.com/home-page', ] for url in urls_list: self.AddUserStory(SkiaBuildbotDesktopPage(url, self))
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=W0401,W0614 from telemetry.page import page as page_module from telemetry.page import page_set as page_set_module class SkiaBuildbotDesktopPage(page_module.Page): def __init__(self, url, page_set): super(SkiaBuildbotDesktopPage, self).__init__( url=url, page_set=page_set, credentials_path='data/credentials.json') self.user_agent_type = 'tablet' self.archive_data_file = 'data/skia_ukwsj_nexus10.json' def RunNavigateSteps(self, action_runner): action_runner.NavigateToPage(self) action_runner.Wait(5) class SkiaUkwsjNexus10PageSet(page_set_module.PageSet): """ Pages designed to represent the median, not highly optimized web """ def __init__(self): super(SkiaUkwsjNexus10PageSet, self).__init__( user_agent_type='tablet', archive_data_file='data/skia_ukwsj_nexus10.json') urls_list = [ # Why: for Clank CY 'http://uk.wsj.com/home-page', ] for url in urls_list: self.AddUserStory(SkiaBuildbotDesktopPage(url, self))
Update loot table register to the new system
package info.u_team.u_team_core.intern.init; import info.u_team.u_team_core.UCoreMod; import info.u_team.u_team_core.intern.loot.SetTileEntityNBTLootFunction; import net.minecraft.block.Block; import net.minecraft.loot.LootFunctionType; import net.minecraft.util.ResourceLocation; import net.minecraft.util.registry.Registry; import net.minecraftforge.event.RegistryEvent.Register; import net.minecraftforge.eventbus.api.IEventBus; public class UCoreLootTableRegistry { public static final LootFunctionType SET_TILEENTITY_NBT = new LootFunctionType(new SetTileEntityNBTLootFunction.Serializer()); private static void registerLootFunction(Register<Block> event) { Registry.register(Registry.LOOT_FUNCTION_TYPE, new ResourceLocation(UCoreMod.MODID, "set_tileentity_nbt"), SET_TILEENTITY_NBT); } public static void registerMod(IEventBus bus) { bus.addGenericListener(Block.class, UCoreLootTableRegistry::registerLootFunction); } }
package info.u_team.u_team_core.intern.init; import info.u_team.u_team_core.UCoreMod; import info.u_team.u_team_core.intern.loot.SetTileEntityNBTLootFunction; import net.minecraft.block.Block; import net.minecraft.loot.LootFunctionType; import net.minecraft.util.ResourceLocation; import net.minecraft.util.registry.Registry; import net.minecraftforge.event.RegistryEvent.Register; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus; @EventBusSubscriber(modid = UCoreMod.MODID, bus = Bus.MOD) public class UCoreLootTableRegistry { public static LootFunctionType SET_TILEENTITY_NBT; @SubscribeEvent public static void register(Register<Block> event) { SET_TILEENTITY_NBT = Registry.register(Registry.LOOT_FUNCTION_TYPE, new ResourceLocation(UCoreMod.MODID, "set_tileentity_nbt"), new LootFunctionType(new SetTileEntityNBTLootFunction.Serializer())); } }
Use alternate port in production
var path = require('path'), rootPath = path.normalize(__dirname + '/..'), fs = require('fs'), env = process.env.NODE_ENV || 'development'; var db_path = path.join( process.env['UU_PATH'] || process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'], ".uu/"); var db_file = path.join(db_path, "paste_db"); var db_binary = path.join(db_path, "binary_files"); [db_path, db_binary].forEach(function(folder) { if(!fs.existsSync(folder)) { console.log("Creating folder %s...", folder); fs.mkdirSync(folder, "0700"); } }); var config = { development: { root: rootPath, app: { name: 'uu.js' }, port: 3000 }, test: { root: rootPath, app: { name: 'uu.js' }, port: 3000 }, production: { root: rootPath, app: { name: 'uu.js' }, port: 8080 } }; module.exports = config[env]; config[env].db_path = db_path; config[env].db_file = db_file; config[env].db_binary_directory = db_binary;
var path = require('path'), rootPath = path.normalize(__dirname + '/..'), fs = require('fs'), env = process.env.NODE_ENV || 'development'; var db_path = path.join( process.env['UU_PATH'] || process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'], ".uu/"); var db_file = path.join(db_path, "paste_db"); var db_binary = path.join(db_path, "binary_files"); [db_path, db_binary].forEach(function(folder) { if(!fs.existsSync(folder)) { console.log("Creating folder %s...", folder); fs.mkdirSync(folder, "0700"); } }); var config = { development: { root: rootPath, app: { name: 'uu.js' }, port: 3000 }, test: { root: rootPath, app: { name: 'uu.js' }, port: 3000 }, production: { root: rootPath, app: { name: 'uu.js' }, port: 3000 } }; module.exports = config[env]; config[env].db_path = db_path; config[env].db_file = db_file; config[env].db_binary_directory = db_binary;
Update decimal tests to only run on text/none. Change-Id: I9a35f9e1687171fc3f06c17516bca2ea4b9af9e1 Reviewed-on: http://gerrit.ent.cloudera.com:8080/2217 Tested-by: jenkins Reviewed-by: Ishaan Joshi <d1d1e60202ec9f2503deb1b724986485a125d802@cloudera.com> Reviewed-on: http://gerrit.ent.cloudera.com:8080/2431 Reviewed-by: Nong Li <99a5e5f8f5911755b88e0b536d46aafa102bed41@cloudera.com>
#!/usr/bin/env python # Copyright (c) 2012 Cloudera, Inc. All rights reserved. # Targeted tests for decimal type. # import logging import pytest from copy import copy from tests.common.test_vector import * from tests.common.impala_test_suite import * class TestDecimalQueries(ImpalaTestSuite): BATCH_SIZES = [0, 1] @classmethod def get_workload(cls): return 'functional-query' @classmethod def add_test_dimensions(cls): super(TestDecimalQueries, cls).add_test_dimensions() cls.TestMatrix.add_dimension( TestDimension('batch_size', *TestDecimalQueries.BATCH_SIZES)) # TODO: add parquet when that is supported. # On CDH4, hive does not support decimal so we can't run these tests against # the other file formats. Enable them on C5. cls.TestMatrix.add_constraint(lambda v:\ v.get_value('table_format').file_format == 'text' and v.get_value('table_format').compression_codec == 'none') def test_queries(self, vector): new_vector = copy(vector) new_vector.get_value('exec_option')['batch_size'] = vector.get_value('batch_size') self.run_test_case('QueryTest/decimal', new_vector)
#!/usr/bin/env python # Copyright (c) 2012 Cloudera, Inc. All rights reserved. # Targeted tests for decimal type. # import logging import pytest from copy import copy from tests.common.test_vector import * from tests.common.impala_test_suite import * class TestDecimalQueries(ImpalaTestSuite): BATCH_SIZES = [0, 1] @classmethod def get_workload(cls): return 'functional-query' @classmethod def add_test_dimensions(cls): super(TestDecimalQueries, cls).add_test_dimensions() cls.TestMatrix.add_dimension( TestDimension('batch_size', *TestDecimalQueries.BATCH_SIZES)) # TODO: add parquet when that is supported. # On CDH4, hive does not support decimal so we can't run these tests against # the other file formats. Enable them on C5. cls.TestMatrix.add_constraint(lambda v:\ v.get_value('table_format').file_format == 'text') def test_queries(self, vector): new_vector = copy(vector) new_vector.get_value('exec_option')['batch_size'] = vector.get_value('batch_size') self.run_test_case('QueryTest/decimal', new_vector)
Change default service port 8080 to 8888
/* Copyright 2015 The Trustees of Princeton University Licensed under the Apache License, Version 2.0 (the "License" ); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * Expose root class */ module.exports = { parse_args: function(args) { var options = { port: 8888 }; // parse // start from 1, [0] is "syndicate-ug-http.js" var i; for(i=1;i<args.length;i++) { if(args[i] === "--port" || args[i] === "-p") { if(i+1 < args.length) { options.port = parseInt(args[i+1]); i++; } continue; } } return options; } };
/* Copyright 2015 The Trustees of Princeton University Licensed under the Apache License, Version 2.0 (the "License" ); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * Expose root class */ module.exports = { parse_args: function(args) { var options = { port: 8080 }; // parse // start from 1, [0] is "syndicate-ug-http.js" var i; for(i=1;i<args.length;i++) { if(args[i] === "--port" || args[i] === "-p") { if(i+1 < args.length) { options.port = parseInt(args[i+1]); i++; } continue; } } return options; } };
Update copyright header of changed files
/* * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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.springframework.boot.configurationsample.recursive; import org.springframework.boot.configurationsample.ConfigurationProperties; @ConfigurationProperties("prefix") public class RecursiveProperties { private RecursiveProperties recursive; public RecursiveProperties getRecursive() { return this.recursive; } public void setRecursive(RecursiveProperties recursive) { this.recursive = recursive; } }
/* * Copyright 2012-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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.springframework.boot.configurationsample.recursive; import org.springframework.boot.configurationsample.ConfigurationProperties; @ConfigurationProperties("prefix") public class RecursiveProperties { private RecursiveProperties recursive; public RecursiveProperties getRecursive() { return this.recursive; } public void setRecursive(RecursiveProperties recursive) { this.recursive = recursive; } }
Rename mushroom to ship / player
/* globals __DEV__ */ import Phaser from 'phaser' import Ship from '../sprites/Ship' export default class extends Phaser.State { init () {} preload () {} create () { game.physics.startSystem(Phaser.Physics.ARCADE) // Set up game input. game.cursors = game.input.keyboard.createCursorKeys() game.input.keyboard.addKeyCapture([ Phaser.Keyboard.SPACEBAR ]) this.player = new Ship({ game: this, x: this.world.centerX, y: this.world.centerY, asset: 'mushroom' }) this.game.add.existing(this.player) } render () { if (__DEV__) { this.game.debug.spriteInfo(this.player, 32, 32) } } }
/* globals __DEV__ */ import Phaser from 'phaser' import Mushroom from '../sprites/Ship' export default class extends Phaser.State { init () {} preload () {} create () { game.physics.startSystem(Phaser.Physics.ARCADE) // Set up game input. game.cursors = game.input.keyboard.createCursorKeys() game.input.keyboard.addKeyCapture([ Phaser.Keyboard.SPACEBAR ]) this.mushroom = new Mushroom({ game: this, x: this.world.centerX, y: this.world.centerY, asset: 'mushroom' }) this.game.add.existing(this.mushroom) } render () { if (__DEV__) { this.game.debug.spriteInfo(this.mushroom, 32, 32) } } }
Fix TZ-dependent return values from time_in_seconds() time.mktime assumes that the time tuple is in local time, rather than UTC. Use calendar.timegm instead for consistency.
""" random utility functions """ import calendar import datetime import functools from .errors import InvalidTypeError def timedelta_to_seconds(delta): """ converts a timedelta object to seconds """ seconds = delta.microseconds seconds += (delta.seconds + delta.days * 24 * 3600) * 10 ** 6 return float(seconds) / 10 ** 6 def time_in_seconds(value): """ normalized either a datetime.date, datetime.datetime or float to a float """ if isinstance(value, (float, int)): return value elif isinstance(value, (datetime.date, datetime.datetime)): return calendar.timegm(value.timetuple()) else: raise InvalidTypeError(value) #adopted from: http://www.snip2code.com/Snippet/2535/Fluent-interface-decorators def chained(method): """ Method decorator to allow chaining. """ @functools.wraps(method) def wrapper(self, *args, **kwargs): """ fluent wrapper """ result = method(self, *args, **kwargs) return self if result is None else result return wrapper
""" random utility functions """ import datetime import functools import time from .errors import InvalidTypeError def timedelta_to_seconds(delta): """ converts a timedelta object to seconds """ seconds = delta.microseconds seconds += (delta.seconds + delta.days * 24 * 3600) * 10 ** 6 return float(seconds) / 10 ** 6 def time_in_seconds(value): """ normalized either a datetime.date, datetime.datetime or float to a float """ if isinstance(value, (float, int)): return value elif isinstance(value, (datetime.date, datetime.datetime)): return time.mktime(value.timetuple()) else: raise InvalidTypeError(value) #adopted from: http://www.snip2code.com/Snippet/2535/Fluent-interface-decorators def chained(method): """ Method decorator to allow chaining. """ @functools.wraps(method) def wrapper(self, *args, **kwargs): """ fluent wrapper """ result = method(self, *args, **kwargs) return self if result is None else result return wrapper
Include czech moment locales in webpack
/* eslint-disable import/no-extraneous-dependencies */ import path from 'path'; import webpack from 'webpack'; export const globalOptions = { resolve: { extensions: ['', '.js', '.jsx'], }, }; export const serverEntry = path.resolve(__dirname, '../src/server/main.js'); export const frontendEntry = path.resolve(__dirname, '../src/web/main.jsx'); export const frontendPlugins = [ new webpack.ContextReplacementPlugin(/moment[/]locale$/, /^\.\/(en|cs|ko|ja|zh-cn)$/), ]; export const loaders = [ { test: /\.jsx?$/, exclude: /node_modules/, loaders: ['babel?presets[]=react,presets[]=es2015'], }, { test: /\.json$/, loader: 'json-loader', }, { test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'url-loader?limit=10000&minetype=application/font-woff', }, { test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'file-loader', }, ]; export const optimizePlugins = [ new webpack.optimize.OccurenceOrderPlugin(true), new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false, }, }), ];
/* eslint-disable import/no-extraneous-dependencies */ import path from 'path'; import webpack from 'webpack'; export const globalOptions = { resolve: { extensions: ['', '.js', '.jsx'], }, }; export const serverEntry = path.resolve(__dirname, '../src/server/main.js'); export const frontendEntry = path.resolve(__dirname, '../src/web/main.jsx'); export const frontendPlugins = [ new webpack.ContextReplacementPlugin(/moment[/]locale$/, /^\.\/(en|ko|ja|zh-cn)$/), ]; export const loaders = [ { test: /\.jsx?$/, exclude: /node_modules/, loaders: ['babel?presets[]=react,presets[]=es2015'], }, { test: /\.json$/, loader: 'json-loader', }, { test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'url-loader?limit=10000&minetype=application/font-woff', }, { test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'file-loader', }, ]; export const optimizePlugins = [ new webpack.optimize.OccurenceOrderPlugin(true), new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false, }, }), ];
Change port from 5000 to 4000
import logging from tornado.wsgi import WSGIContainer from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop, PeriodicCallback from caaas import app from caaas.cleanup_thread import cleanup_task from caaas.config_parser import config DEBUG = True log = logging.getLogger("caaas") def main(): if DEBUG: logging.basicConfig(level=logging.DEBUG) logging.getLogger("requests").setLevel(logging.WARNING) logging.getLogger("tornado").setLevel(logging.WARNING) print("Starting app...") app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 http_server = HTTPServer(WSGIContainer(app)) http_server.listen(4000, "0.0.0.0") ioloop = IOLoop.instance() PeriodicCallback(cleanup_task, int(config.cleanup_thread_interval) * 1000).start() ioloop.start() if __name__ == "__main__": main()
import logging from tornado.wsgi import WSGIContainer from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop, PeriodicCallback from caaas import app from caaas.cleanup_thread import cleanup_task from caaas.config_parser import config DEBUG = True log = logging.getLogger("caaas") def main(): if DEBUG: logging.basicConfig(level=logging.DEBUG) logging.getLogger("requests").setLevel(logging.WARNING) logging.getLogger("tornado").setLevel(logging.WARNING) print("Starting app...") app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 http_server = HTTPServer(WSGIContainer(app)) http_server.listen(5000, "0.0.0.0") ioloop = IOLoop.instance() PeriodicCallback(cleanup_task, int(config.cleanup_thread_interval) * 1000).start() ioloop.start() if __name__ == "__main__": main()
Call the items going into the pool simply item rather than callback
jsio('from shared.javascript import Class') exports = Class(function(){ this.init = function() { this._pool = {} this._counts = {} this._uniqueId = 0 } this.add = function(name, item) { if (!this._pool[name]) { this._pool[name] = {} this._counts[name] = 0 } this._counts[name]++ var id = 'p' + this._uniqueId++ this._pool[name][id] = item return id } this.remove = function(name, id) { delete this._pool[name][id] if (this._counts[name]-- == 0) { delete this._counts[name] } } this.get = function(name) { return this._pool[name] } this.count = function(name) { return this._counts[name] || 0 } })
jsio('from shared.javascript import Class') exports = Class(function(){ this.init = function() { this._pool = {} this._counts = {} this._uniqueId = 0 } this.add = function(name, callback) { if (!this._pool[name]) { this._pool[name] = {} this._counts[name] = 0 } this._counts[name]++ var id = 'p' + this._uniqueId++ this._pool[name][id] = callback return id } this.remove = function(name, id) { delete this._pool[name][id] if (this._counts[name]-- == 0) { delete this._counts[name] } } this.get = function(name) { return this._pool[name] } this.count = function(name) { return this._counts[name] || 0 } })
Use localhost instead of 127.0.0.1
import webbrowser from uuid import uuid4 from alertaclient.auth.token import TokenHandler def login(client, oidc_auth_url, client_id): xsrf_token = str(uuid4()) redirect_uri = 'http://localhost:9004' # azure only supports 'localhost' url = ( '{oidc_auth_url}?' 'response_type=code' '&client_id={client_id}' '&redirect_uri={redirect_uri}' '&scope=openid%20profile%20email' '&state={state}' ).format( oidc_auth_url=oidc_auth_url, client_id=client_id, redirect_uri=redirect_uri, state=xsrf_token ) webbrowser.open(url, new=0, autoraise=True) auth = TokenHandler() access_token = auth.get_access_token(xsrf_token) data = { 'code': access_token, 'clientId': client_id, 'redirectUri': redirect_uri } return client.token('openid', data)
import webbrowser from uuid import uuid4 from alertaclient.auth.token import TokenHandler def login(client, oidc_auth_url, client_id): xsrf_token = str(uuid4()) redirect_uri = 'http://127.0.0.1:9004' url = ( '{oidc_auth_url}?' 'response_type=code' '&client_id={client_id}' '&redirect_uri={redirect_uri}' '&scope=openid%20profile%20email' '&state={state}' ).format( oidc_auth_url=oidc_auth_url, client_id=client_id, redirect_uri=redirect_uri, state=xsrf_token ) webbrowser.open(url, new=0, autoraise=True) auth = TokenHandler() access_token = auth.get_access_token(xsrf_token) data = { 'code': access_token, 'clientId': client_id, 'redirectUri': redirect_uri } return client.token('openid', data)
Update to a new extension execution struction. Add global variable to verify pre-execution script gets injected only once. Change pre-execution script from sendMessage to executeScript because script functionality has changed. Change collapse/expand script from executeScript to sendMessage because functionality will get updated.
// Global variables only exist for the life of the page, so they get reset // each time the page is unloaded. let attachedTabs = {}; let scriptInjected = false; // Called when the user clicks on the browser action. chrome.browserAction.onClicked.addListener(function (tab) { let tabId = tab.id; // https://developer.chrome.com/extensions/content_scripts#pi if (!scriptInjected) { chrome.tabs.executeScript(tabId, { file: 'src/bg/textcontent.js' }, function (response) { scriptInjected = response; }); } if (!attachedTabs[tabId]) { attachedTabs[tabId] = 'collapsed'; chrome.browserAction.setIcon({ tabId: tabId, path: 'icons/pause.png' }); chrome.browserAction.setTitle({ tabId: tabId, title: 'Pause collapsing' }); chrome.tabs.sendMessage(tabId, { collapse: false }); } else if (attachedTabs[tabId]) { delete attachedTabs[tabId]; chrome.browserAction.setIcon({ tabId: tabId, path: 'icons/continue.png' }); chrome.browserAction.setTitle({ tabId: tabId, title: 'Enable collapsing' }); chrome.tabs.sendMessage(tabId, { collapse: true }); } });
let attachedTabs = {}; let textContentArr; // Called when the user clicks on the browser action. chrome.browserAction.onClicked.addListener(function (tab) { let tabId = tab.id; // https://developer.chrome.com/extensions/content_scripts#pi chrome.tabs.executeScript(tabId, { file: 'src/bg/textcontent.js' }, function () { chrome.tabs.sendMessage(tabId, {}, function (response) { textContentArr = response; console.log(textContentArr); }); }); if (!attachedTabs[tabId]) { attachedTabs[tabId] = 'collapsed'; chrome.browserAction.setIcon({ tabId: tabId, path: 'icons/pause.png' }); chrome.browserAction.setTitle({ tabId: tabId, title: 'Pause collapsing' }); chrome.tabs.executeScript({ file: 'src/bg/collapse.js' }); } else if (attachedTabs[tabId]) { delete attachedTabs[tabId]; chrome.browserAction.setIcon({ tabId: tabId, path: 'icons/continue.png' }); chrome.browserAction.setTitle({ tabId: tabId, title: 'Enable collapsing' }); chrome.tabs.executeScript({ file: 'src/bg/expand.js' }); } });
Use the x-forwarded-for address, if available Otherwise the server would log the reverse proxy's ip, in case it is used with a reverse proxy.
const slaveService = require('../services/slave'); const versionService = require('../services/version'); const version = { currentVersion(req, res) { const {slaveUID, slaveVersion} = req.params, remoteAddress = req.headers['x-forwarded-for'] || req.connection.remoteAddress, tag = versionService.getCurrent(); const respondWithTag = () => { res.json(200, {tag}); }; slaveService.updateSlave(slaveUID, slaveVersion, remoteAddress) .then(respondWithTag) .catch(error => { console.error(`An error occurred when updating ${slaveUID}: ${error}`); // send back current version regardless respondWithTag(); }); } } module.exports = version;
const slaveService = require('../services/slave'); const versionService = require('../services/version'); const version = { currentVersion(req, res) { const {slaveUID, slaveVersion} = req.params, remoteAddress = req.connection.remoteAddress, tag = versionService.getCurrent(); const respondWithTag = () => { res.json(200, {tag}); }; slaveService.updateSlave(slaveUID, slaveVersion, remoteAddress) .then(respondWithTag) .catch(error => { console.error(`An error occurred when updating ${slaveUID}: ${error}`); // send back current version regardless respondWithTag(); }); } } module.exports = version;
Read gray scale image with alpha channel
#!/usr/bin/env python # simple script to publish a image from a file. import rospy import cv2 import sensor_msgs.msg #change these to fit the expected topic names IMAGE_MESSAGE_TOPIC = 'grid_map_image' IMAGE_PATH = 'test2.png' def callback(self): """ Convert a image to a ROS compatible message (sensor_msgs.Image). """ img = cv2.imread(IMAGE_PATH, -1) rosimage = sensor_msgs.msg.Image() rosimage.encoding = 'mono16' rosimage.width = img.shape[1] rosimage.height = img.shape[0] rosimage.step = img.strides[0] rosimage.data = img.tostring() # rosimage.data = img.flatten().tolist() publisher.publish(rosimage) #Main function initializes node and subscribers and starts the ROS loop def main_program(): global publisher rospy.init_node('image_publisher') publisher = rospy.Publisher(IMAGE_MESSAGE_TOPIC, sensor_msgs.msg.Image, queue_size=10) rospy.Timer(rospy.Duration(0.5), callback) rospy.spin() if __name__ == '__main__': try: main_program() except rospy.ROSInterruptException: pass
#!/usr/bin/env python # simple script to publish a image from a file. import rospy import cv2 import sensor_msgs.msg #change these to fit the expected topic names IMAGE_MESSAGE_TOPIC = 'grid_map_image' IMAGE_PATH = 'test2.png' def callback(self): """ Convert a image to a ROS compatible message (sensor_msgs.Image). """ img = cv2.imread(IMAGE_PATH) rosimage = sensor_msgs.msg.Image() rosimage.encoding = 'mono16' rosimage.width = img.shape[1] rosimage.height = img.shape[0] rosimage.step = img.strides[0] rosimage.data = img.tostring() # rosimage.data = img.flatten().tolist() publisher.publish(rosimage) #Main function initializes node and subscribers and starts the ROS loop def main_program(): global publisher rospy.init_node('image_publisher') publisher = rospy.Publisher(IMAGE_MESSAGE_TOPIC, sensor_msgs.msg.Image, queue_size=10) rospy.Timer(rospy.Duration(0.5), callback) rospy.spin() if __name__ == '__main__': try: main_program() except rospy.ROSInterruptException: pass
Disable auto fetch by default
<?php /////////////////////////////////////// // Config. $config["info"] = array( "debug" => FALSE, "version" => "1.0", "title" => "The OpenGL vs Mesa matrix", "description" => "Show Mesa progress for the OpenGL implementation into an easy to read HTML page.", "git_url" => "http://cgit.freedesktop.org/mesa/mesa", "gl3_file" => "src/gl3.txt", "log_file" => "src/gl3_log.txt", ); $config["auto_fetch"] = array( "enabled" => FALSE, "timeout" => 3600, "url" => "http://cgit.freedesktop.org/mesa/mesa/plain/docs/GL3.txt", ); $config["flattr"] = array( "enabled" => FALSE, "id" => "your_flattr_id", "language" => "en_US", "tags" => "mesa,opengl", ); /////////////////////////////////////// // Common code for all pages. date_default_timezone_set('UTC'); if($config["info"]["debug"]) { ini_set('display_errors', 1); ini_set('error_reporting', E_ALL); } function debug_print($line) { if($config["info"]["debug"]) { print("DEBUG: ".$line."<br />\n"); } } ?>
<?php /////////////////////////////////////// // Config. $config["info"] = array( "debug" => FALSE, "version" => "1.0", "title" => "The OpenGL vs Mesa matrix", "description" => "Show Mesa progress for the OpenGL implementation into an easy to read HTML page.", "git_url" => "http://cgit.freedesktop.org/mesa/mesa", "gl3_file" => "src/gl3.txt", "log_file" => "src/gl3_log.txt", ); $config["auto_fetch"] = array( "enabled" => TRUE, "timeout" => 3600, "url" => "http://cgit.freedesktop.org/mesa/mesa/plain/docs/GL3.txt", ); $config["flattr"] = array( "enabled" => FALSE, "id" => "your_flattr_id", "language" => "en_US", "tags" => "mesa,opengl", ); /////////////////////////////////////// // Common code for all pages. date_default_timezone_set('UTC'); if($config["info"]["debug"]) { ini_set('display_errors', 1); ini_set('error_reporting', E_ALL); } function debug_print($line) { if($config["info"]["debug"]) { print("DEBUG: ".$line."<br />\n"); } } ?>
Use author's email address if no name given
"use strict"; var Immutable = require('immutable') const AUTHORS_BY_MSG_ID = {} const EMPTY_ITEM_MAP = Immutable.Map({ total: 0, trend: 0 }) , inc = n => n + 1 , incCounts = counts => counts.update('total', inc).update('trend', inc) , updateMapCounts = val => map => map.update(val, EMPTY_ITEM_MAP, incCounts) const RE_REGEX = /re:\s+/i const sortCountMap = map => map.sort((a, b) => { a = a.get('trend'); b = b.get('trend'); return a === b ? 0 : b > a ? 1 : -1; }) module.exports = function addCommunication(communications, msg) { let author = msg.from[0].name || msg.from[0].address , inReplyTo = (msg.inReplyTo || [{}])[0] , pair , subject AUTHORS_BY_MSG_ID[msg.messageId] = author; if (!inReplyTo) { pair = Immutable.Set([author]); } else { pair = Immutable.Set([author, AUTHORS_BY_MSG_ID[inReplyTo]]).sort(); } subject = (msg.subject || '(no_subject)').replace(RE_REGEX, ''); return communications .update('pair', Immutable.Map(), updateMapCounts(pair)) .update('author', Immutable.Map(), updateMapCounts(author)) .update('subject', Immutable.Map(), updateMapCounts(subject)) .map(sortCountMap) }
"use strict"; var Immutable = require('immutable') const AUTHORS_BY_MSG_ID = {} const EMPTY_ITEM_MAP = Immutable.Map({ total: 0, trend: 0 }) , inc = n => n + 1 , incCounts = counts => counts.update('total', inc).update('trend', inc) , updateMapCounts = val => map => map.update(val, EMPTY_ITEM_MAP, incCounts) const RE_REGEX = /re:\s+/i const sortCountMap = map => map.sort((a, b) => { a = a.get('trend'); b = b.get('trend'); return a === b ? 0 : b > a ? 1 : -1; }) module.exports = function addCommunication(communications, msg) { let author = msg.from[0].name , inReplyTo = (msg.inReplyTo || [{}])[0] , pair , subject AUTHORS_BY_MSG_ID[msg.messageId] = author; if (!inReplyTo) { pair = Immutable.Set([author]); } else { pair = Immutable.Set([author, AUTHORS_BY_MSG_ID[inReplyTo]]).sort(); } subject = (msg.subject || '(no_subject)').replace(RE_REGEX, ''); return communications .update('pair', Immutable.Map(), updateMapCounts(pair)) .update('author', Immutable.Map(), updateMapCounts(author)) .update('subject', Immutable.Map(), updateMapCounts(subject)) .map(sortCountMap) }
Change variable name & int comparison.
from flask import jsonify, current_app from . import status from . import utils from .. import api_client @status.route('/_status') def status(): api_response = utils.return_response_from_api_status_call( api_client.status ) apis_with_errors = [] if api_response is None or api_response.status_code != 200: apis_with_errors.append("(Data) API") # if no errors found, return everything if not apis_with_errors: return jsonify( status="ok", version=utils.get_version_label(), api_status=api_response.json(), ) message = "Error connecting to the " \ + (" and the ".join(apis_with_errors)) \ + "." current_app.logger.error(message) return jsonify( status="error", version=utils.get_version_label(), api_status=utils.return_json_or_none(api_response), message=message, ), 500
from flask import jsonify, current_app from . import status from . import utils from .. import api_client @status.route('/_status') def status(): api_response = utils.return_response_from_api_status_call( api_client.status ) apis_wot_got_errors = [] if api_response is None or api_response.status_code is not 200: apis_wot_got_errors.append("(Data) API") # if no errors found, return everything if not apis_wot_got_errors: return jsonify( status="ok", version=utils.get_version_label(), api_status=api_response.json(), ) message = "Error connecting to the " \ + (" and the ".join(apis_wot_got_errors)) \ + "." current_app.logger.error(message) return jsonify( status="error", version=utils.get_version_label(), api_status=utils.return_json_or_none(api_response), message=message, ), 500
fix: Use status code for 404 response
/*jshint es5:true */ module.exports = function(opts) { 'use strict'; var port = opts.port || 8080 , webroot = process.cwd(); var connect = require('connect') , http = require('http'); var indexes = [ /index\.html/i, /readme\.md/i, /readme\.markdown/i ]; var app = connect() .use(require('./lib/mid-logger')()) .use(require('./lib/mid-index')(webroot, opts.index)) .use(require('./lib/mid-lr')(opts.watch)) .use(require('./lib/mid-buttle')(webroot)) .use(require('./lib/mid-dir')(webroot,opts.nodir)) .use(require('./lib/mid-php')(webroot)) .use(connect.static(webroot)) .use(require('./lib/mid-less')(webroot)) .use(function(req, res){ res.writeHead(404); res.end('Where you goin? NOWHERE!'); }); http.createServer(app).listen(port, function() { console.log('Listening on port ' + port); if(opts.open) { require('open')( require('url').resolve('http://localhost:' + port, opts.open) ); } }); require('./lib/live-reload-server')(opts.watch); };
/*jshint es5:true */ module.exports = function(opts) { 'use strict'; var port = opts.port || 8080 , webroot = process.cwd(); var connect = require('connect') , http = require('http'); var indexes = [ /index\.html/i, /readme\.md/i, /readme\.markdown/i ]; var app = connect() .use(require('./lib/mid-logger')()) .use(require('./lib/mid-index')(webroot, opts.index)) .use(require('./lib/mid-lr')(opts.watch)) .use(require('./lib/mid-buttle')(webroot)) .use(require('./lib/mid-dir')(webroot,opts.nodir)) .use(require('./lib/mid-php')(webroot)) .use(connect.static(webroot)) .use(require('./lib/mid-less')(webroot)) .use(function(req, res){ res.end('A thousand apologies, but there are none to be had.\n'); }); http.createServer(app).listen(port, function() { console.log('Listening on port ' + port); if(opts.open) { require('open')( require('url').resolve('http://localhost:' + port, opts.open) ); } }); require('./lib/live-reload-server')(opts.watch); };
Add job document name as metadata to S3 object
'use stirct' var opbeat = require('opbeat').start() var uuid = require('node-uuid') var AWS = require('aws-sdk') var Printer = require('ipp-printer') var port = process.env.PORT || 3000 var s3 = new AWS.S3() var printer = new Printer({ name: 'printbin', port: port, zeroconf: false }) printer.on('job', function (job) { var key = uuid.v4() + '.ps' console.log('processing job %d (key: %s)', job.id, key) job.on('end', function () { console.log('done reading job %d (key: %s)', job.id, key) }) var params = { Bucket: 'watson-printbin', ACL: 'public-read', ContentType: 'application/postscript', StorageClass: 'REDUCED_REDUNDANCY', Metadata: { name: job.name }, Key: key, Body: job } s3.upload(params, function (err, data) { if (err) return opbeat.captureError(err) console.log('done uploading job %d (key: %s)', job.id, key) }) })
'use stirct' var opbeat = require('opbeat').start() var uuid = require('node-uuid') var AWS = require('aws-sdk') var Printer = require('ipp-printer') var port = process.env.PORT || 3000 var s3 = new AWS.S3() var printer = new Printer({ name: 'printbin', port: port, zeroconf: false }) printer.on('job', function (job) { var key = uuid.v4() + '.ps' console.log('processing job %d (key: %s)', job.id, key) job.on('end', function () { console.log('done reading job %d (key: %s)', job.id, key) }) var params = { Bucket: 'watson-printbin', ACL: 'public-read', ContentType: 'application/postscript', StorageClass: 'REDUCED_REDUNDANCY', Key: key, Body: job } s3.upload(params, function (err, data) { if (err) return opbeat.captureError(err) console.log('done uploading job %d (key: %s)', job.id, key) }) })
Add a doc comment for the whole project.
// FLiP.Earth is the website for the Friendly Linux Players community. // // See https://FriendlyLinuxPlayers.org for the live website and // https://github.com/FriendlyLinuxPlayers/flip.earth for the code. package main import ( "fmt" _ "github.com/friendlylinuxplayers/flip.earth/config" _ "github.com/friendlylinuxplayers/flip.earth/router" _ "github.com/friendlylinuxplayers/flip.earth/server" "github.com/friendlylinuxplayers/flip.earth/service" cs "github.com/friendlylinuxplayers/flip.earth/service/config" ) // TODO refactor out everything so main only contains minimal code func main() { b := new(service.Builder) configDef := service.Definition{ Name: "config", Initializer: cs.Reader{}, } b.Insert(configDef) container, error := b.Build() if error != nil { panic(error) } service, error := container.Get("config") if error != nil { panic(error) } fmt.Printf("Config %+v \n", service) }
package main import ( "fmt" _ "github.com/friendlylinuxplayers/flip.earth/config" _ "github.com/friendlylinuxplayers/flip.earth/router" _ "github.com/friendlylinuxplayers/flip.earth/server" "github.com/friendlylinuxplayers/flip.earth/service" cs "github.com/friendlylinuxplayers/flip.earth/service/config" ) // TODO refactor out everything so main only contains minimal code func main() { b := new(service.Builder) configDef := service.Definition{ Name: "config", Initializer: cs.Reader{}, } b.Insert(configDef) container, error := b.Build() if error != nil { panic(error) } service, error := container.Get("config") if error != nil { panic(error) } fmt.Printf("Config %+v \n", service) }
Remove lodash dependency when auto registering Vue components
/** * First we will load all of this project's JavaScript dependencies which * include Vue and Vue Resource. This gives a great starting point for * building robust, powerful web applications using Vue and Laravel. */ require('./bootstrap'); /** * Vue is a modern JavaScript library for building interactive web interfaces * using reactive data binding and reusable components. Vue's API is clean * and simple, leaving you to focus on building your next great project. */ window.Vue = require('vue'); /** * The following block of code may be used to automatically register your * Vue components. It will recursively scan this directory for the Vue * components and automatically register them with their "basename". * * Eg. ./components/ExampleComponent.vue -> <example-component></example-component> */ Vue.component('example-component', require('./components/ExampleComponent.vue')); // const files = require.context('./', true, /\.vue$/i) // files.keys().map(key => { // return Vue.component(key.split('/').pop().split('.')[0], files(key)) // // }) /** * Next, we will create a fresh Vue application instance and attach it to * the page. Then, you may begin adding components to this application * or customize the JavaScript scaffolding to fit your unique needs. */ const app = new Vue({ el: '#app' });
/** * First we will load all of this project's JavaScript dependencies which * include Vue and Vue Resource. This gives a great starting point for * building robust, powerful web applications using Vue and Laravel. */ require('./bootstrap'); /** * Vue is a modern JavaScript library for building interactive web interfaces * using reactive data binding and reusable components. Vue's API is clean * and simple, leaving you to focus on building your next great project. */ window.Vue = require('vue'); /** * The following block of code may be used to automatically register your * Vue components. It will recursively scan this directory for the Vue * components and automatically register them with their "basename". * * Eg. ./components/ExampleComponent.vue -> <example-component></example-component> */ Vue.component('example-component', require('./components/ExampleComponent.vue')); // const files = require.context('./', true, /\.vue$/i) // files.keys().map(key => { // return Vue.component(_.last(key.split('/')).split('.')[0], files(key)) // }) /** * Next, we will create a fresh Vue application instance and attach it to * the page. Then, you may begin adding components to this application * or customize the JavaScript scaffolding to fit your unique needs. */ const app = new Vue({ el: '#app' });
Fix unmatched field in Authorization The field in the formatted string was not matching the args
""" .. module: lemur.authorizations.models :platform: unix :copyright: (c) 2018 by Netflix Inc., see AUTHORS for more :license: Apache, see LICENSE for more details. .. moduleauthor:: Netflix Secops <secops@netflix.com> """ from sqlalchemy import Column, Integer, String from sqlalchemy_utils import JSONType from lemur.database import db from lemur.plugins.base import plugins class Authorization(db.Model): __tablename__ = "pending_dns_authorizations" id = Column(Integer, primary_key=True, autoincrement=True) account_number = Column(String(128)) domains = Column(JSONType) dns_provider_type = Column(String(128)) options = Column(JSONType) @property def plugin(self): return plugins.get(self.plugin_name) def __repr__(self): return "Authorization(id={id})".format(id=self.id) def __init__(self, account_number, domains, dns_provider_type, options=None): self.account_number = account_number self.domains = domains self.dns_provider_type = dns_provider_type self.options = options
""" .. module: lemur.authorizations.models :platform: unix :copyright: (c) 2018 by Netflix Inc., see AUTHORS for more :license: Apache, see LICENSE for more details. .. moduleauthor:: Netflix Secops <secops@netflix.com> """ from sqlalchemy import Column, Integer, String from sqlalchemy_utils import JSONType from lemur.database import db from lemur.plugins.base import plugins class Authorization(db.Model): __tablename__ = "pending_dns_authorizations" id = Column(Integer, primary_key=True, autoincrement=True) account_number = Column(String(128)) domains = Column(JSONType) dns_provider_type = Column(String(128)) options = Column(JSONType) @property def plugin(self): return plugins.get(self.plugin_name) def __repr__(self): return "Authorization(id={id})".format(label=self.id) def __init__(self, account_number, domains, dns_provider_type, options=None): self.account_number = account_number self.domains = domains self.dns_provider_type = dns_provider_type self.options = options
Fix restoreConsole test util not working properly
const fs = require('fs'); export const makeAsyncCallback = (callbackValue) => { let promiseResolve; const promise = new Promise((resolve) => { promiseResolve = resolve; }); const func = jest.fn( callbackValue ? () => promiseResolve(callbackValue) : (...args) => promiseResolve(args.length === 1 ? args[0] : args), ); return { promise, func }; }; export const loadPDF = (path) => { const raw = fs.readFileSync(path); const arrayBuffer = raw.buffer; return { raw, arrayBuffer, get blob() { return new Blob([arrayBuffer], { type: 'application/pdf' }); }, get data() { return new Uint8Array(raw); }, get dataURI() { return `data:application/pdf;base64,${raw.toString('base64')}`; }, get file() { return new File([arrayBuffer], { type: 'application/pdf' }); }, }; }; export const muteConsole = () => { jest.spyOn(global.console, 'log').mockImplementation(() => {}); jest.spyOn(global.console, 'error').mockImplementation(() => {}); jest.spyOn(global.console, 'warn').mockImplementation(() => {}); }; export const restoreConsole = () => { global.console.log.mockRestore(); global.console.error.mockRestore(); global.console.warn.mockRestore(); };
const fs = require('fs'); export const makeAsyncCallback = (callbackValue) => { let promiseResolve; const promise = new Promise((resolve) => { promiseResolve = resolve; }); const func = jest.fn( callbackValue ? () => promiseResolve(callbackValue) : (...args) => promiseResolve(args.length === 1 ? args[0] : args), ); return { promise, func }; }; export const loadPDF = (path) => { const raw = fs.readFileSync(path); const arrayBuffer = raw.buffer; return { raw, arrayBuffer, get blob() { return new Blob([arrayBuffer], { type: 'application/pdf' }); }, get data() { return new Uint8Array(raw); }, get dataURI() { return `data:application/pdf;base64,${raw.toString('base64')}`; }, get file() { return new File([arrayBuffer], { type: 'application/pdf' }); }, }; }; export const muteConsole = () => { jest.spyOn(global.console, 'log').mockImplementation(() => {}); jest.spyOn(global.console, 'error').mockImplementation(() => {}); jest.spyOn(global.console, 'warn').mockImplementation(() => {}); }; export const restoreConsole = () => { global.console.log.mockClear(); global.console.error.mockClear(); global.console.warn.mockClear(); };
Fix wards code sequences restart
# -*- coding: utf-8 -*- from django.db import models, migrations from facilities.models import Facility def set_min_code_value(apps, schema_editor): from django.db import connection cursor = connection.cursor() sql = """ ALTER SEQUENCE common_constituency_code_seq restart 1000 start 1000 minvalue 1000; ALTER SEQUENCE common_county_code_seq restart 1000 start 1000 minvalue 1000; ALTER SEQUENCE common_subcounty_code_seq restart 1000 start 1000 minvalue 1000; ALTER SEQUENCE common_ward_code_seq restart 10000 start 10000 minvalue 10000; """ cursor = cursor.execute(sql) class Migration(migrations.Migration): dependencies = [ ('common', '0001_initial'), ] operations = [ migrations.RunPython(set_min_code_value), ]
# -*- coding: utf-8 -*- from django.db import models, migrations from facilities.models import Facility def set_min_code_value(apps, schema_editor): from django.db import connection cursor = connection.cursor() sql = """ ALTER SEQUENCE common_constituency_code_seq restart 1000 start 1000 minvalue 1000; ALTER SEQUENCE common_county_code_seq restart 1000 start 1000 minvalue 1000; ALTER SEQUENCE common_subcounty_code_seq restart 1000 start 1000 minvalue 1000; ALTER SEQUENCE common_ward_code_seq restart 1000 start 1000 minvalue 1000; """ cursor = cursor.execute(sql) class Migration(migrations.Migration): dependencies = [ ('common', '0001_initial'), ] operations = [ migrations.RunPython(set_min_code_value), ]
Add summary to book listing
DEFAULT_FIELDS = [ 'locales.title', 'locales.summary', 'locales.description', 'locales.lang', 'author', 'editor', 'activities', 'url', 'isbn', 'book_types', 'publication_date', 'langs', 'nb_pages' ] DEFAULT_REQUIRED = [ 'locales', 'locales.title', 'book_types' ] LISTING_FIELDS = [ 'locales', 'locales.title', 'locales.summary', 'activities', 'author', 'quality', 'book_types' ] fields_book = { 'fields': DEFAULT_FIELDS, 'required': DEFAULT_REQUIRED, 'listing': LISTING_FIELDS }
DEFAULT_FIELDS = [ 'locales.title', 'locales.summary', 'locales.description', 'locales.lang', 'author', 'editor', 'activities', 'url', 'isbn', 'book_types', 'publication_date', 'langs', 'nb_pages' ] DEFAULT_REQUIRED = [ 'locales', 'locales.title', 'book_types' ] LISTING_FIELDS = [ 'locales', 'locales.title', 'activities', 'author', 'quality', 'book_types' ] fields_book = { 'fields': DEFAULT_FIELDS, 'required': DEFAULT_REQUIRED, 'listing': LISTING_FIELDS }
Remove unnecessary line from test
import asyncio import sys from scrapy import Spider from scrapy.crawler import CrawlerProcess from scrapy.utils.defer import deferred_from_coro from twisted.internet.defer import Deferred class UppercasePipeline: async def _open_spider(self, spider): spider.logger.info("async pipeline opened!") await asyncio.sleep(0.1) def open_spider(self, spider): return deferred_from_coro(self._open_spider(spider)) def process_item(self, item, spider): return {"url": item["url"].upper()} class UrlSpider(Spider): name = "url_spider" start_urls = ["data:,"] custom_settings = { "ITEM_PIPELINES": {UppercasePipeline: 100}, } def parse(self, response): yield {"url": response.url} if __name__ == "__main__": try: ASYNCIO_EVENT_LOOP = sys.argv[1] except IndexError: ASYNCIO_EVENT_LOOP = None process = CrawlerProcess(settings={ "TWISTED_REACTOR": "twisted.internet.asyncioreactor.AsyncioSelectorReactor", "ASYNCIO_EVENT_LOOP": ASYNCIO_EVENT_LOOP, }) process.crawl(UrlSpider) process.start()
import asyncio import sys from scrapy import Spider from scrapy.crawler import CrawlerProcess from scrapy.utils.defer import deferred_from_coro from twisted.internet.defer import Deferred class UppercasePipeline: async def _open_spider(self, spider): spider.logger.info("async pipeline opened!") await asyncio.sleep(0.1) def open_spider(self, spider): loop = asyncio.get_event_loop() return deferred_from_coro(self._open_spider(spider)) def process_item(self, item, spider): return {"url": item["url"].upper()} class UrlSpider(Spider): name = "url_spider" start_urls = ["data:,"] custom_settings = { "ITEM_PIPELINES": {UppercasePipeline: 100}, } def parse(self, response): yield {"url": response.url} if __name__ == "__main__": try: ASYNCIO_EVENT_LOOP = sys.argv[1] except IndexError: ASYNCIO_EVENT_LOOP = None process = CrawlerProcess(settings={ "TWISTED_REACTOR": "twisted.internet.asyncioreactor.AsyncioSelectorReactor", "ASYNCIO_EVENT_LOOP": ASYNCIO_EVENT_LOOP, }) process.crawl(UrlSpider) process.start()
Fix Unexpected 'else' after 'return' (no-else-return)
'use strict'; var AblySubscriber = function AblySubscriber(options) { this.test = options.test; if (options.hasOwnProperty('variant')) { this.variant = options.variant; } this.callback = options.callback; }; AblySubscriber.prototype.notify = function(test) { var self = this; setTimeout(function notifySubscriberNow() { self.callback(test); }, 1); }; AblySubscriber.prototype.matchesTest = function(test) { return this.test === test.name; }; AblySubscriber.prototype.matchesTestAndVariant = function(test, variant) { if (this.hasOwnProperty('variant')) { return this.test === test && this.variant === variant; } return this.test === test; }; module.exports = AblySubscriber;
'use strict'; var AblySubscriber = function AblySubscriber(options) { this.test = options.test; if (options.hasOwnProperty('variant')) { this.variant = options.variant; } this.callback = options.callback; }; AblySubscriber.prototype.notify = function(test) { var self = this; setTimeout(function notifySubscriberNow() { self.callback(test); }, 1); }; AblySubscriber.prototype.matchesTest = function(test) { return this.test === test.name; }; AblySubscriber.prototype.matchesTestAndVariant = function(test, variant) { if (this.hasOwnProperty('variant')) { return this.test === test && this.variant === variant; } else { return this.test === test; } }; module.exports = AblySubscriber;
Use transactions instead of migrations for testing database
<?php use Canvas\Models\Tag; use Canvas\Models\Post; use Canvas\Models\User; use Illuminate\Foundation\Testing\DatabaseTransactions; trait InteractsWithDatabase { use DatabaseTransactions; /** * Set up the test environment. * * @return void */ protected function setUp() { parent::setUp(); // Disable searchable trait to speed up tests. Post::disableSearchSyncing(); Tag::disableSearchSyncing(); User::disableSearchSyncing(); $this->runDatabaseMigrations(); $this->seed(\Canvas\TestDatabaseSeeder::class); } /** * Define hooks to migrate the database before and after each test. * * @return void */ public function runDatabaseMigrations() { $this->artisan('migrate'); $this->beforeApplicationDestroyed(function () { $this->artisan('migrate:reset'); }); } }
<?php namespace Tests; use Canvas\Models\Tag; use Canvas\Models\Post; use Canvas\Models\User; use Canvas\TestDatabaseSeeder; use Illuminate\Foundation\Testing\DatabaseMigrations; trait InteractsWithDatabase { use DatabaseMigrations; /** * Set up the test environment. * * @return void */ public function setUp() { // Disable searchable trait to speed up tests. Post::disableSearchSyncing(); Tag::disableSearchSyncing(); User::disableSearchSyncing(); $this->runDatabaseMigrations(); $this->seed(TestDatabaseSeeder::class); } /** * Define hooks to migrate the database before and after each test. * * @return void */ // public function runDatabaseMigrations() // { // $this->artisan('migrate'); // // $this->beforeApplicationDestroyed(function () { // $this->artisan('migrate:reset'); // }); // } }
Fix help link not displayed
package kg.apc.jmeter.modifiers; import java.awt.BorderLayout; import kg.apc.jmeter.JMeterPluginsUtils; import org.apache.jmeter.processor.gui.AbstractPreProcessorGui; import org.apache.jmeter.testelement.TestElement; public class AnchorModifierGui extends AbstractPreProcessorGui { private static final String WIKIPAGE = "SpiderPreProcessor"; public AnchorModifierGui() { super(); init(); } @Override public String getStaticLabel() { return JMeterPluginsUtils.prefixLabel("Spider PreProcessor"); } @Override public String getLabelResource() { return this.getClass().getName(); } @Override public TestElement createTestElement() { AnchorModifier modifier = new AnchorModifier(); modifyTestElement(modifier); return modifier; } /** * Modifies a given TestElement to mirror the data in the gui components. * * @see * org.apache.jmeter.gui.JMeterGUIComponent#modifyTestElement(TestElement) */ @Override public void modifyTestElement(TestElement modifier) { configureTestElement(modifier); } private void init() { setLayout(new BorderLayout(0, 5)); setBorder(makeBorder()); add(JMeterPluginsUtils.addHelpLinkToPanel(makeTitlePanel(), WIKIPAGE), BorderLayout.NORTH); } }
package kg.apc.jmeter.modifiers; import java.awt.BorderLayout; import kg.apc.jmeter.JMeterPluginsUtils; import org.apache.jmeter.processor.gui.AbstractPreProcessorGui; import org.apache.jmeter.testelement.TestElement; public class AnchorModifierGui extends AbstractPreProcessorGui { private static final String WIKIPAGE = "SpiderPreProcessor"; public AnchorModifierGui() { init(); } @Override public String getStaticLabel() { return JMeterPluginsUtils.prefixLabel("Spider PreProcessor"); } public String getLabelResource() { return this.getClass().getName(); } public TestElement createTestElement() { AnchorModifier modifier = new AnchorModifier(); modifyTestElement(modifier); return modifier; } /** * Modifies a given TestElement to mirror the data in the gui components. * * @see * org.apache.jmeter.gui.JMeterGUIComponent#modifyTestElement(TestElement) */ public void modifyTestElement(TestElement modifier) { configureTestElement(modifier); } private void init() { setLayout(new BorderLayout(0, 5)); setBorder(makeBorder()); add(JMeterPluginsUtils.addHelpLinkToPanel(makeTitlePanel(), WIKIPAGE), BorderLayout.NORTH); add(makeTitlePanel(), BorderLayout.NORTH); } }
Mark XmlMaterialProfile as type "material" so the import/export code can find it Contributes to CURA-341
# Copyright (c) 2016 Ultimaker B.V. # Cura is released under the terms of the AGPLv3 or higher. from . import XmlMaterialProfile from UM.MimeTypeDatabase import MimeType, MimeTypeDatabase from UM.i18n import i18nCatalog catalog = i18nCatalog("cura") def getMetaData(): return { "plugin": { "name": catalog.i18nc("@label", "Material Profiles"), "author": "Ultimaker", "version": "1.0", "description": catalog.i18nc("@info:whatsthis", "Provides capabilities to read and write XML-based material profiles."), "api": 3 }, "settings_container": { "type": "material", "mimetype": "application/x-ultimaker-material-profile" } } def register(app): mime_type = MimeType( name = "application/x-ultimaker-material-profile", comment = "Ultimaker Material Profile", suffixes = [ "xml.fdm_material" ] ) MimeTypeDatabase.addMimeType(mime_type) return { "settings_container": XmlMaterialProfile.XmlMaterialProfile("default_xml_material_profile") }
# Copyright (c) 2016 Ultimaker B.V. # Cura is released under the terms of the AGPLv3 or higher. from . import XmlMaterialProfile from UM.MimeTypeDatabase import MimeType, MimeTypeDatabase from UM.i18n import i18nCatalog catalog = i18nCatalog("cura") def getMetaData(): return { "plugin": { "name": catalog.i18nc("@label", "Material Profiles"), "author": "Ultimaker", "version": "1.0", "description": catalog.i18nc("@info:whatsthis", "Provides capabilities to read and write XML-based material profiles."), "api": 3 }, "settings_container": { "mimetype": "application/x-ultimaker-material-profile" } } def register(app): mime_type = MimeType( name = "application/x-ultimaker-material-profile", comment = "Ultimaker Material Profile", suffixes = [ "xml.fdm_material" ] ) MimeTypeDatabase.addMimeType(mime_type) return { "settings_container": XmlMaterialProfile.XmlMaterialProfile("default_xml_material_profile") }
Add additional validation to request parameters H1 59701 Former-commit-id: 07d778157b1e49e8177d18733293bc48caf94968 Former-commit-id: 1943dca20dd598f0a882a6b8652985518ab88b8f
<? defined('C5_EXECUTE') or die("Access Denied."); $val = \Core::make('helper/validation/numbers'); $cID = 0; if ($val->integer($_REQUEST['cID'])) { $cID = $_REQUEST['cID']; } if (!is_array($_REQUEST['cvID'])) { die(t('Invalid Request.')); } ?> <div style="height: 100%"> <? $tabs = array(); foreach ($_REQUEST['cvID'] as $key => $cvID) { if (!$val->integer($cvID)) { unset($_REQUEST['cvID'][$key]); } else { $tabs[] = array('view-version-' . $cvID, t('Version %s', $cvID), $checked); $checked = false; } } print $ih->tabs($tabs); foreach ($_REQUEST['cvID'] as $cvID) { ?> <div id="ccm-tab-content-view-version-<?=$cvID?>" style="display: <?=$display?>; height: 100%"> <iframe border="0" id="v<?=time()?>" frameborder="0" height="100%" width="100%" src="<?=REL_DIR_FILES_TOOLS_REQUIRED?>/pages/preview_version?cvID=<?=$cvID?>&amp;cID=<?=$cID?>" /> </div> <? if ($display == 'block') { $display = 'none'; } ?> <? } ?> </div>
<? defined('C5_EXECUTE') or die("Access Denied."); ?> <div style="height: 100%"> <? foreach($_REQUEST['cvID'] as $cvID) { $tabs[] = array('view-version-' . $cvID, t('Version %s', $cvID), $checked); $checked = false; } print $ih->tabs($tabs); foreach($_REQUEST['cvID'] as $cvID) { ?> <div id="ccm-tab-content-view-version-<?=$cvID?>" style="display: <?=$display?>; height: 100%"> <iframe border="0" id="v<?=time()?>" frameborder="0" height="100%" width="100%" src="<?=REL_DIR_FILES_TOOLS_REQUIRED?>/pages/preview_version?cvID=<?=$cvID?>&amp;cID=<?=$_REQUEST['cID']?>" /> </div> <? if ($display == 'block') { $display = 'none'; } ?> <? } ?> </div>
[Consistency] Rename session name (to be accurate with the others) And as mentioned in pH7CMS's Coding Conventions: https://ph7cms.com/doc/en/code-convention#function-global-variable-array-names
<?php /** * @author Pierre-Henry Soria <hello@ph7cms.com> * @copyright (c) 2019, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / App / System / Core / Class */ namespace PH7; use PH7\Framework\Cookie\Cookie; use PH7\Framework\Security\Security; use PH7\Framework\Session\Session; use stdClass; class RememberMeCore { const CHECKBOX_FIELD_NAME = 'remember'; const STAY_LOGGED_IN_REQUESTED = 'stayed_logged_requested'; /** * @param Session $oSession * * @return bool */ public function isEligible(Session $oSession) { return $oSession->exists(self::STAY_LOGGED_IN_REQUESTED); } public function enableSession(stdClass $oUserData) { $aCookieData = [ // Hash one more time the password for the cookie 'member_remember' => Security::hashCookie($oUserData->password), 'member_id' => $oUserData->profileId ]; (new Cookie)->set($aCookieData); } }
<?php /** * @author Pierre-Henry Soria <hello@ph7cms.com> * @copyright (c) 2019, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / App / System / Core / Class */ namespace PH7; use PH7\Framework\Cookie\Cookie; use PH7\Framework\Security\Security; use PH7\Framework\Session\Session; use stdClass; class RememberMeCore { const CHECKBOX_FIELD_NAME = 'remember'; const STAY_LOGGED_IN_REQUESTED = 'stayedLoggedInRequested'; /** * @param Session $oSession * * @return bool */ public function isEligible(Session $oSession) { return $oSession->exists(self::STAY_LOGGED_IN_REQUESTED); } public function enableSession(stdClass $oUserData) { $aCookieData = [ // Hash one more time the password for the cookie 'member_remember' => Security::hashCookie($oUserData->password), 'member_id' => $oUserData->profileId ]; (new Cookie)->set($aCookieData); } }
Remove PyObjC requirement since it's not avialable at PyPi yet.
#!/usr/bin/env python # coding=utf-8 __author__ = 'kulakov.ilya@gmail.com' from setuptools import setup from sys import platform REQUIREMENTS = [] # Not avaialable at PyPi yet # if platform.startswith('darwin'): # REQUIREMENTS.append('pyobjc >= 2.5') setup( name="Power", version="1.1", description="Cross-platform system power status information.", author="Ilya Kulakov", author_email="kulakov.ilya@gmail.com", url="https://github.com/Kentzo/Power", platforms=["Mac OS X 10.6+", "Windows XP+", "Linux 2.6+"], packages=['power'], classifiers=[ 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX :: Linux', 'Topic :: System :: Power (UPS)', 'Topic :: System :: Hardware', 'Topic :: System :: Monitoring' ], install_requires=REQUIREMENTS )
#!/usr/bin/env python # coding=utf-8 __author__ = 'kulakov.ilya@gmail.com' from setuptools import setup from sys import platform REQUIREMENTS = [] if platform.startswith('darwin'): REQUIREMENTS.append('pyobjc >= 2.5') setup( name="Power", version="1.1", description="Cross-platform system power status information.", author="Ilya Kulakov", author_email="kulakov.ilya@gmail.com", url="https://github.com/Kentzo/Power", platforms=["Mac OS X 10.6+", "Windows XP+", "Linux 2.6+"], packages=['power'], classifiers=[ 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX :: Linux', 'Topic :: System :: Power (UPS)', 'Topic :: System :: Hardware', 'Topic :: System :: Monitoring' ], install_requires=REQUIREMENTS )
Fix name not containing the e
package info.u_team.u_team_test.init; import info.u_team.u_team_test.TestMod; import info.u_team.u_team_test.potion.RadiationPotion; import net.minecraft.potion.Potion; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.fml.RegistryObject; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus; import net.minecraftforge.registries.*; @EventBusSubscriber(modid = TestMod.MODID, bus = Bus.MOD) public class TestPotions { public static final DeferredRegister<Potion> POTIONS = DeferredRegister.create(ForgeRegistries.POTION_TYPES, TestMod.MODID); public static final RegistryObject<Potion> RADIATION = POTIONS.register("radiation", () -> new RadiationPotion(1200, 0)); public static final RegistryObject<Potion> RADIATION_LONG = POTIONS.register("radiation_long", () -> new RadiationPotion(2400, 1)); public static final RegistryObject<Potion> RADIATION_EXTREME = POTIONS.register("radiation_extreme", () -> new RadiationPotion(1200, 2)); public static void register(IEventBus bus) { POTIONS.register(bus); } }
package info.u_team.u_team_test.init; import info.u_team.u_team_test.TestMod; import info.u_team.u_team_test.potion.RadiationPotion; import net.minecraft.potion.Potion; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.fml.RegistryObject; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus; import net.minecraftforge.registries.*; @EventBusSubscriber(modid = TestMod.MODID, bus = Bus.MOD) public class TestPotions { public static final DeferredRegister<Potion> POTIONS = DeferredRegister.create(ForgeRegistries.POTION_TYPES, TestMod.MODID); public static final RegistryObject<Potion> RADIATION = POTIONS.register("radiation", () -> new RadiationPotion(1200, 0)); public static final RegistryObject<Potion> RADIATION_LONG = POTIONS.register("radiation_long", () -> new RadiationPotion(2400, 1)); public static final RegistryObject<Potion> RADIATION_EXTREME = POTIONS.register("radiation_extrem", () -> new RadiationPotion(1200, 2)); public static void register(IEventBus bus) { POTIONS.register(bus); } }
Fix merge (phpdoc => typehint)
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bundle\SecurityBundle\Security; use Symfony\Component\Security\Http\Firewall\ExceptionListener; /** * This is a wrapper around the actual firewall configuration which allows us * to lazy load the context for one specific firewall only when we need it. * * @author Johannes M. Schmitt <schmittjoh@gmail.com> */ class FirewallContext { private $listeners; private $exceptionListener; private $config; public function __construct(iterable $listeners, ExceptionListener $exceptionListener = null, FirewallConfig $config = null) { $this->listeners = $listeners; $this->exceptionListener = $exceptionListener; $this->config = $config; } public function getConfig() { return $this->config; } public function getListeners(): iterable { return $this->listeners; } public function getExceptionListener() { return $this->exceptionListener; } }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bundle\SecurityBundle\Security; use Symfony\Component\Security\Http\Firewall\ExceptionListener; /** * This is a wrapper around the actual firewall configuration which allows us * to lazy load the context for one specific firewall only when we need it. * * @author Johannes M. Schmitt <schmittjoh@gmail.com> */ class FirewallContext { private $listeners; private $exceptionListener; private $config; /** * @param \Traversable|array $listeners * @param ExceptionListener|null $exceptionListener * @param FirewallConfig|null $firewallConfig */ public function __construct($listeners, ExceptionListener $exceptionListener = null, FirewallConfig $config = null) { $this->listeners = $listeners; $this->exceptionListener = $exceptionListener; $this->config = $config; } public function getConfig() { return $this->config; } /** * @return \Traversable|array */ public function getListeners() { return $this->listeners; } public function getExceptionListener() { return $this->exceptionListener; } }
tests: Fix broken setup/teardown in tests/index.html In QUnit 1.16, module setup/teardown was renamed to beforeEach and afterEach (old names kept for back-compat). The back-compat aliases were removed in QUnit 2.0. This didn't break the karma run because we only used setup/teardown to create an element qunit-fixture for each test, which qunit-karma does internally for us as well (because that too is a deprecated feature that was removed long ago). As such, these setup/teardown handles have been unused for a while but didn't cause problems unless running tests manually. Change-Id: I6135706db9c79a2f49279d03fe772bf0a404ff98
( function () { // Extend QUnit.module to provide a fixture element. This used to be in tests/index.html, but // dynamic test runners like Karma build their own web page. ( function () { var orgModule = QUnit.module; QUnit.module = function ( name, localEnv ) { localEnv = localEnv || {}; orgModule( name, { beforeEach: function () { this.fixture = document.createElement( 'div' ); this.fixture.id = 'qunit-fixture'; document.body.appendChild( this.fixture ); if ( localEnv.name ) { localEnv.name.call( this ); } }, afterEach: function () { if ( localEnv.afterEach ) { localEnv.afterEach.call( this ); } this.fixture.parentNode.removeChild( this.fixture ); } } ); }; }() ); /** * Utility for creating iframes. * @return {HTMLElement} */ QUnit.tmpIframe = function () { var iframe = document.createElement( 'iframe' ); // Will be removed automatically by afterEach document.getElementById( 'qunit-fixture' ).appendChild( iframe ); return iframe; }; }() );
( function () { // Extend QUnit.module to provide a fixture element. This used to be in tests/index.html, but // dynamic test runners like Karma build their own web page. ( function () { var orgModule = QUnit.module; QUnit.module = function ( name, localEnv ) { localEnv = localEnv || {}; orgModule( name, { setup: function () { this.fixture = document.createElement( 'div' ); this.fixture.id = 'qunit-fixture'; document.body.appendChild( this.fixture ); if ( localEnv.setup ) { localEnv.setup.call( this ); } }, teardown: function () { if ( localEnv.teardown ) { localEnv.teardown.call( this ); } this.fixture.parentNode.removeChild( this.fixture ); } } ); }; }() ); /** * Utility for creating iframes. * @return {HTMLElement} */ QUnit.tmpIframe = function () { var iframe = document.createElement( 'iframe' ); // Will be removed automatically by module teardown document.getElementById( 'qunit-fixture' ).appendChild( iframe ); return iframe; }; }() );
Check if the summary have diaries
package main import ( "flag" "fmt" "log" "time" "github.com/publicgov/spain-boe-reader/net" "github.com/publicgov/spain-boe-reader/params" "github.com/publicgov/spain-boe-reader/summary" ) var currentDate string func main() { // parse command line argument flag.StringVar(&currentDate, "date", defaultTime(), "BOE publication date in format YYYYMMDD") flag.Parse() // create the URL for the day p := params.Params{ SummaryType: "BOE", ItemType: "S", Date: currentDate, } // make the network request client := net.New(p) summary := client.MakeRequest() if len(summary.Diaries) == 0 { log.Println("No diaries found for date", currentDate) return } // print basic info log.Println(showBasicInfo(summary)) } func defaultTime() string { time := time.Now().UTC() time.Format("2006-01-02") return fmt.Sprintf("%d%02d%02d", time.Year(), time.Month(), time.Day()) } func showBasicInfo(b summary.BoeSummary) string { return fmt.Sprintf("Date(%s) Found %d diaries with %d sections", b.Meta.PublicationDate, len(b.Diaries), b.SectionsSize()) }
package main import ( "flag" "fmt" "log" "time" "github.com/publicgov/spain-boe-reader/net" "github.com/publicgov/spain-boe-reader/params" "github.com/publicgov/spain-boe-reader/summary" ) var currentDate string func main() { // parse command line argument flag.StringVar(&currentDate, "date", defaultTime(), "BOE publication date in format YYYYMMDD") flag.Parse() // create the URL for the day p := params.Params{ SummaryType: "BOE", ItemType: "S", Date: currentDate, } // make the network request client := net.New(p) summary := client.MakeRequest() // print basic info log.Println(showBasicInfo(summary)) } func defaultTime() string { time := time.Now().UTC() time.Format("2006-01-02") return fmt.Sprintf("%d%02d%02d", time.Year(), time.Month(), time.Day()) } func showBasicInfo(b summary.BoeSummary) string { return fmt.Sprintf("Date(%s) Found %d diaries with %d sections", b.Meta.PublicationDate, len(b.Diaries), b.SectionsSize()) }
Fix PluginRegistry error (missing global.require)
// @flow import path from 'path'; import PluginRegistory from '../../src/services/plugin-registory' describe('PluginRegistory', () => { it('exporting: PluginFeatures', () => { expect(PluginRegistory.PluginFeatures).to.not.eql(null) expect(PluginRegistory.PluginFeatures).to.be.an('object') }) it('loading plugins', async () => { // mock missing method in mocha global.require = require const r = new PluginRegistory() const result = await r.loadPackageDir(path.join(__dirname, '../../src/plugins')) expect(result).to.not.empty() expect(result).to.have.key('packages') expect(result).to.have.key('failed') expect(result.packages).to.be.an('object') expect(result.failed).to.be.an(Array) delete global.require }) })
// @flow import path from 'path'; import PluginRegistory from '../../src/services/plugin-registory' describe('PluginRegistory', () => { it('exporting: PluginFeatures', () => { expect(PluginRegistory.PluginFeatures).to.not.eql(null) expect(PluginRegistory.PluginFeatures).to.be.an('object') }) it('loading plugins', async () => { const r = new PluginRegistory() const result = await r.loadPackageDir(path.join(__dirname, '../../src/plugins')) expect(result).to.not.empty() expect(result).to.have.key('packages') expect(result).to.have.key('failed') expect(result.packages).to.be.an('object') expect(result.failed).to.be.an(Array) }) })
Update guests table migation to use varchars.
var dbm = require('db-migrate'), type = dbm.dataType; exports.up = function (db, callback) { db.createTable('guests', { columns: { id: { autoIncrement: true, primaryKey : true, type : 'int' }, invitation_id: 'int', title: {type: 'string', length: 8}, name : {type: 'string', length: 64}, email: {type: 'string', length: 128}, is_attending: 'boolean', is_plusone : {type: 'boolean', defaultValue: false} }, ifNotExists: true }, function (err) { if (err) { return callback(err); } db.runSql( 'ALTER TABLE guests ' + 'ADD FOREIGN KEY (invitation_id) REFERENCES invitations;', callback); }); }; exports.down = function (db, callback) { db.dropTable('guests', {ifExists: true}, callback); };
var dbm = require('db-migrate'), type = dbm.dataType; exports.up = function (db, callback) { db.createTable('guests', { columns: { id: { autoIncrement: true, primaryKey : true, type : 'int' }, invitation_id: 'int', title: 'text', name : 'text', email: 'text', is_attending: 'boolean', is_plusone : {type: 'boolean', defaultValue: false} }, ifNotExists: true }, function (err) { if (err) { return callback(err); } db.runSql( 'ALTER TABLE guests ' + 'ADD FOREIGN KEY (invitation_id) REFERENCES invitations;', callback); }); }; exports.down = function (db, callback) { db.dropTable('guests', {ifExists: true}, callback); };
Set task serializer to json
# -*- encoding: utf-8 -*- import os, sys sys.path.insert(0, '..') PROJECT_ROOT = os.path.dirname(__file__) DEBUG = True TEMPLATE_DEBUG = DEBUG DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test' } } MIDDLEWARE_CLASSES = () TIME_ZONE = 'America/Chicago' LANGUAGE_CODE = 'en-us' ADMIN_MEDIA_PREFIX = '/static/admin/' STATICFILES_DIRS = () SECRET_KEY = 'di!n($kqa3)nd%ikad#kcjpkd^uw*h%*kj=*pm7$vbo6ir7h=l' INSTALLED_APPS = ( 'djmail', 'djcelery', 'testing', ) import djcelery djcelery.setup_loader() CELERY_ALWAYS_EAGER = True CELERY_TASK_SERIALIZER = 'json'
# -*- encoding: utf-8 -*- import os, sys sys.path.insert(0, '..') PROJECT_ROOT = os.path.dirname(__file__) DEBUG = True TEMPLATE_DEBUG = DEBUG DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test' } } MIDDLEWARE_CLASSES = () TIME_ZONE = 'America/Chicago' LANGUAGE_CODE = 'en-us' ADMIN_MEDIA_PREFIX = '/static/admin/' STATICFILES_DIRS = () SECRET_KEY = 'di!n($kqa3)nd%ikad#kcjpkd^uw*h%*kj=*pm7$vbo6ir7h=l' INSTALLED_APPS = ( 'djmail', 'djcelery', 'testing', ) import djcelery djcelery.setup_loader() CELERY_ALWAYS_EAGER = True
Use FMLClientHandler for consistency's sake, and add missing SideOnly annotation
package info.tehnut.xtones.network; import info.tehnut.xtones.client.XtonesClient; import net.minecraftforge.fml.client.FMLClientHandler; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.checkerframework.checker.nullness.qual.Nullable; final class ConfigSyncHandler implements IMessageHandler<ConfigSyncMessage, IMessage> { static final ConfigSyncHandler INSTANCE = new ConfigSyncHandler(); private ConfigSyncHandler() { } private static void readConfig(final ConfigSyncMessage config) { XtonesClient.setServerXtoneCycling(config.hasXtoneCycling()); } @Override @Nullable @SideOnly(Side.CLIENT) public IMessage onMessage(final ConfigSyncMessage config, final MessageContext context) { FMLClientHandler.instance().getClient().addScheduledTask(() -> readConfig(config)); return null; } }
package info.tehnut.xtones.network; import info.tehnut.xtones.client.XtonesClient; import net.minecraft.client.Minecraft; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; import org.checkerframework.checker.nullness.qual.Nullable; final class ConfigSyncHandler implements IMessageHandler<ConfigSyncMessage, IMessage> { static final ConfigSyncHandler INSTANCE = new ConfigSyncHandler(); private ConfigSyncHandler() { } private static void readConfig(final ConfigSyncMessage config) { XtonesClient.setServerXtoneCycling(config.hasXtoneCycling()); } @Override @Nullable public IMessage onMessage(final ConfigSyncMessage config, final MessageContext context) { Minecraft.getMinecraft().addScheduledTask(() -> readConfig(config)); return null; } }
Add default value for List Filter
<?php namespace Podlove\Modules\Networks\Template; use Podlove\Template\Wrapper; /** * List Template Wrapper * * Requires the "Networks" module. * * @templatetag podlove */ class Podlove extends Wrapper { public function __construct() { } protected function getExtraFilterArgs() { return array(); } public function lists( $args=array() ) { if ( isset($args['slug']) ) { $list_with_slug = \Podlove\Modules\Networks\Model\PodcastList::find_one_by_property( 'slug', $args['slug'] ); if ( is_object( $list_with_slug ) ) return array( new \Podlove\Modules\Networks\Template\PodcastList( $list_with_slug ) ); return; } $lists = array(); foreach ( \Podlove\Modules\Networks\Model\PodcastList::all() as $list ) { $lists[] = new \Podlove\Modules\Networks\Template\PodcastList( $list ); } return $lists; } }
<?php namespace Podlove\Modules\Networks\Template; use Podlove\Template\Wrapper; /** * List Template Wrapper * * Requires the "Networks" module. * * @templatetag podlove */ class Podlove extends Wrapper { public function __construct() { } protected function getExtraFilterArgs() { return array(); } public function lists( $args ) { if ( isset($args['slug']) ) { $list_with_slug = \Podlove\Modules\Networks\Model\PodcastList::find_one_by_property( 'slug', $args['slug'] ); if ( is_object( $list_with_slug ) ) return array( new \Podlove\Modules\Networks\Template\PodcastList( $list_with_slug ) ); return; } $lists = array(); foreach ( \Podlove\Modules\Networks\Model\PodcastList::all() as $list ) { $lists[] = new \Podlove\Modules\Networks\Template\PodcastList( $list ); } return $lists; } }
Remove unnecessary pycroft import in migration
"""add account_pattern Revision ID: fb8d553a7268 Revises: 28e56bf6f62c Create Date: 2021-04-26 22:16:41.772282 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'fb8d553a7268' down_revision = '0b69e80a9388' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('account_pattern', sa.Column('id', sa.Integer(), nullable=False), sa.Column('pattern', sa.String(), nullable=False), sa.Column('account_id', sa.Integer(), nullable=False), sa.ForeignKeyConstraint(['account_id'], ['account.id'], ondelete='CASCADE'), sa.PrimaryKeyConstraint('id') ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('account_pattern') # ### end Alembic commands ###
"""add account_pattern Revision ID: fb8d553a7268 Revises: 28e56bf6f62c Create Date: 2021-04-26 22:16:41.772282 """ from alembic import op import sqlalchemy as sa import pycroft # revision identifiers, used by Alembic. revision = 'fb8d553a7268' down_revision = '0b69e80a9388' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('account_pattern', sa.Column('id', sa.Integer(), nullable=False), sa.Column('pattern', sa.String(), nullable=False), sa.Column('account_id', sa.Integer(), nullable=False), sa.ForeignKeyConstraint(['account_id'], ['account.id'], ondelete='CASCADE'), sa.PrimaryKeyConstraint('id') ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('account_pattern') # ### end Alembic commands ###
Add comments to the load current user filter
"use strict"; /*global nodeca, _*/ var me_in_fields = [ '_uname', 'locale' ]; // fetch current user info // fired before each controllers nodeca.filters.before('', { weight: -70 }, function load_current_user(params, next) { var env = this; // // fill in default (guest) values // env.user = null; env.runtime.user_name = ''; env.runtime.is_member = false; env.runtime.is_guest = true; // // if there's no session or session has no user_id, user is guest - skip // if (!env.session || !env.session.user_id) { next(); return; } nodeca.models.users.User .findOne({ '_id': env.session.user_id }) .select(me_in_fields.join(' ')) .setOptions({ lean: true }) .exec(function(err, user){ if (err) { next(err); return; } // user in session, but db does not know this user if (!user) { next(); return; } env.user = user; env.runtime.user_name = user._uname; env.runtime.is_guest = false; env.runtime.is_member = true; next(); }); });
"use strict"; /*global nodeca, _*/ var me_in_fields = [ '_uname', 'locale' ]; var me_out_fields = [ '_uname' ]; // fetch current user info // fired before each controllers nodeca.filters.before('', { weight: -70 }, function load_current_user(params, next) { var env = this; env.user = null; env.runtime.user_name = ''; env.runtime.is_member = false; env.runtime.is_guest = true; if (!env.session.user_id) { next(); return; } nodeca.models.users.User .findOne({ '_id': env.session.user_id }) .select(me_in_fields.join(' ')) .setOptions({ lean: true }) .exec(function(err, user){ if (err) { next(err); return; } // user in session, but db does not know this user if (!user) { next(); return; } env.user = user; env.runtime.user_name = user._uname; env.runtime.is_guest = false; env.runtime.is_member = true; next(); }); });
Use _this when it seems necessary Signed-off-by: Stefan Marr <46f1a0bd5592a2f9244ca321b129902a06b53e03@stefan-marr.de>
'use strict'; function SAbstractObject() { var _this = this; this.toString = function () { var clazz = _this.getClass(); if (clazz === null) { return "an Object(clazz==null)"; } return "a " + clazz.getName().getString(); }; this.send = function (selectorString, args) { var selector = window.universe.symbolFor(selectorString); var invokable = args[0].getClass().lookupInvokable(selector); return invokable.invoke(args); }; this.sendDoesNotUnderstand = function (selector, args) { // Allocate an array to hold the arguments, without receiver var argsArray = SArguments.getArgumentsWithoutReceiver(args); var dnuArgs = [args[0], selector, argsArray]; return _this.send("doesNotUnderstand:arguments:", dnuArgs); }; this.sendUnknownGlobal = function (globalName) { var args = [this, globalName]; return _this.send("unknownGlobal:", args); }; this.sendEscapedBlock = function (block) { var args = [this, block]; return _this.send("escapedBlock:", args); }; }
'use strict'; function SAbstractObject() { this.toString = function () { var clazz = getClass(); if (clazz === null) { return "an Object(clazz==null)"; } return "a " + clazz.getName().getString(); }; this.send = function (selectorString, args) { var selector = window.universe.symbolFor(selectorString); var invokable = args[0].getClass().lookupInvokable(selector); return invokable.invoke(args); }; this.sendDoesNotUnderstand = function (selector, args) { // Allocate an array to hold the arguments, without receiver var argsArray = SArguments.getArgumentsWithoutReceiver(args); var dnuArgs = [args[0], selector, argsArray]; return send("doesNotUnderstand:arguments:", dnuArgs); }; this.sendUnknownGlobal = function (globalName) { var args = [this, globalName]; return send("unknownGlobal:", arguments); }; this.sendEscapedBlock = function (block) { var args = [this, block]; return send("escapedBlock:", arguments); }; }
Test en passant d'un const en var
'use strict'; // Import Wit.Ai const botlogic = require('./botlogic/botlogic.js'); var facebook = require('./channels/facebook.js'); var messageReceived; module.exports = { receivedMessage: function(message) { receivedMessage(message); } }; /* * Fonction appelée par les channels lorsque l'on reçoit un message */ function receivedMessage(message) { /* Traitement */ messageReceived = message; // Variable globale runLogicLayer(message); } /* * Fonction qu lance la couche logique avec NLP */ function runLogicLayer(message) { botlogic.defineCallback(callbackLogicLayer); if(message.sender != undefined && message.text != undefined) { botlogic.sendMessage(message.text, `session-${message.sender}`, {}); } } /* * Fonction de callback appelée par la couche logique */ function callbackLogicLayer(request, response){ messageReceived.text = response.text console.log('Custom callback Wit : ', JSON.stringify(response)); console.log('Message to send : ', JSON.stringify(messageReceived)); sendMessage(messageReceived); } /* * Fonction qui appelle la fonction d'envoie de message */ function sendMessage(message) { if(message.channel == "Facebook") { facebook.sendMessage(message); } }
'use strict'; // Import Wit.Ai const botlogic = require('./botlogic/botlogic.js'); const facebook = require('./channels/facebook.js'); var messageReceived; module.exports = { receivedMessage: function(message) { receivedMessage(message); } }; /* * Fonction appelée par les channels lorsque l'on reçoit un message */ function receivedMessage(message) { /* Traitement */ messageReceived = message; // Variable globale runLogicLayer(message); } /* * Fonction qu lance la couche logique avec NLP */ function runLogicLayer(message) { botlogic.defineCallback(callbackLogicLayer); if(message.sender != undefined && message.text != undefined) { botlogic.sendMessage(message.text, `session-${message.sender}`, {}); } } /* * Fonction de callback appelée par la couche logique */ function callbackLogicLayer(request, response){ messageReceived.text = response.text console.log('Custom callback Wit : ', JSON.stringify(response)); console.log('Message to send : ', JSON.stringify(messageReceived)); sendMessage(messageReceived); } /* * Fonction qui appelle la fonction d'envoie de message */ function sendMessage(message) { if(message.channel == "Facebook") { facebook.sendMessage(message); } }
Remove empty line. Add bland commit message.
import os from soho.utils import register_plugin registry = {} def register_renderer(spec, *ext): """Register a renderer. ``spec`` a string that represents the full path to a class, for example ``'soho.renderers.zpt.ZPTRenderer'``. The class must implement the same interface as :class:`soho.renderers.BaseRenderer`. ``ext`` one or more file extensions to which the plugin will be associated. At least one file extension must be provided. File extensions should not contain the dot, for example ``'html'``, not ``'.html'``. """ register_plugin(registry, spec, *ext) class BaseRenderer(object): """The base class that any renderer must implement. There is only one renderer for now, so the API is subject to change (as soon as a second renderer is implemented). """ def __init__(self, template_path): # pragma: no coverage raise NotImplementedError def render(self, **bindings): # pragma: no coverage """Render the template with the given ``bindings``.""" raise NotImplementedError def get_renderer(path, *args, **kwargs): """Return a renderer for the given template, or ``None`` if none could be found. """ ext = os.path.splitext(path)[1][1:] klass = registry.get(ext, None) if klass is None: return None return klass(path, *args, **kwargs)
import os from soho.utils import register_plugin registry = {} def register_renderer(spec, *ext): """Register a renderer. ``spec`` a string that represents the full path to a class, for example ``'soho.renderers.zpt.ZPTRenderer'``. The class must implement the same interface as :class:`soho.renderers.BaseRenderer`. ``ext`` one or more file extensions to which the plugin will be associated. At least one file extension must be provided. File extensions should not contain the dot, for example ``'html'``, not ``'.html'``. """ register_plugin(registry, spec, *ext) class BaseRenderer(object): """The base class that any renderer must implement. There is only one renderer for now, so the API is subject to change (as soon as a second renderer is implemented). """ def __init__(self, template_path): # pragma: no coverage raise NotImplementedError def render(self, **bindings): # pragma: no coverage """Render the template with the given ``bindings``.""" raise NotImplementedError def get_renderer(path, *args, **kwargs): """Return a renderer for the given template, or ``None`` if none could be found. """ ext = os.path.splitext(path)[1][1:] klass = registry.get(ext, None) if klass is None: return None return klass(path, *args, **kwargs)
Add boolean parsing and renaming utilities - Add a parseBool function for converting values to Boolean values, treating the string "true" specially - Add a utility for creating a new object by renaming some of its properties based on a property mapping object
'use strict'; function defined(value) { return value !== null && typeof value !== 'undefined' && Math.abs(value) !== Infinity && !isNaN(value); } function max(data, accessor) { var m = -Infinity; accessor = accessor || Number; if (data instanceof Array) { for (var i = data.length - 1; i >= 0; i--) { m = Math.max(m, max(data[i], accessor)); } } else { var v = accessor(data); if (defined(v)) { m = Math.max(m, v); } } return m; } function min(data, accessor) { var m = Infinity; accessor = accessor || Number; if (data instanceof Array) { for (var i = data.length - 1; i >= 0; i--) { m = Math.min(m, min(data[i], accessor)); } } else { var v = accessor(data); if (defined(v)) { m = Math.min(m, v); } } return m; } function parseBool(value) { if (value instanceof String) { return value === 'true'; } return Boolean(value); } function rename(obj, mapping) { var o = {}; for (var k in obj) { o[mapping[k] || k] = obj[k]; } return o; } module.exports = { defined : defined, max : max, min : min, parseBool: parseBool, rename : rename };
'use strict'; function defined(value) { return value !== null && typeof value !== 'undefined' && Math.abs(value) !== Infinity && !isNaN(value); } function min(data, accessor) { var m = Infinity; accessor = accessor || Number; if (data instanceof Array) { for (var i = data.length - 1; i >= 0; i--) { m = Math.min(m, min(data[i], accessor)); } } else { var v = accessor(data); if (defined(v)) { m = Math.min(m, v); } } return m; } function max(data, accessor) { var m = -Infinity; accessor = accessor || Number; if (data instanceof Array) { for (var i = data.length - 1; i >= 0; i--) { m = Math.max(m, max(data[i], accessor)); } } else { var v = accessor(data); if (defined(v)) { m = Math.max(m, v); } } return m; } module.exports = { min : min, max : max, defined: defined };
Replace of the content in workspace id
'use strict'; // Requirements var User = module.parent.require('./user'), var winston = module.parent.require('winston'), var watsonDev = require('watson-developer-cloud'); // Methods var Watson = {}; Watson.response = function(postData) { var conversation = watsonDev.conversation({ username: 'c9d9cc99-b3e5-44f5-a234-ccae1578e8ae', password: 'xUtHqarwWpUk', version: 'v1', version_date: '2016-09-20' }); var context = {}; var params = { workspace_id: 'a05393b7-d022-4bed-ba76-012042930893', input: {'text': 'hahaha'}, context: context }; conversation.message(params, function (err, response) { if (err) return console.log(err); else console.log(JSON.stringify(response, null, 2)); }); } module.exports = Watson;
'use strict'; // Requirements var User = module.parent.require('./user'), winston = module.parent.require('winston'), watsonDev = require('watson-developer-cloud'), // Methods Watson = {}; Watson.response = function(postData) { var conversation = watsonDev.conversation({ username: 'c9d9cc99-b3e5-44f5-a234-ccae1578e8ae', password: 'xUtHqarwWpUk', version: 'v1', version_date: '2016-09-20' }), context = {}, params = { workspace_id: '25dfa8a0-0263-471b-8980-317e68c30488', input: {'text': 'hahaha'}, context: context }; conversation.message(params, function (err, response) { if (err) return winston.error(err); else winston.log(JSON.stringify(response, null, 2)); }); } module.exports = Watson;
Update health beta registration API request path
import { apiRequest } from '../../common/helpers/api'; export const BETA_REGISTERING = 'BETA_REGISTERING'; export const BETA_REGISTER_SUCCESS = 'BETA_REGISTER_SUCCESS'; export const BETA_REGISTER_FAILURE = 'BETA_REGISTER_FAILURE'; export function registerBeta() { return dispatch => { dispatch({ type: BETA_REGISTERING }); const settings = { method: 'POST', }; apiRequest('/beta_registration/health_account', settings, response => dispatch({ type: BETA_REGISTER_SUCCESS, username: response.user, stats: 'succeeded', }), () => dispatch({ type: BETA_REGISTER_FAILURE, stats: 'failed' }) ); }; }
import { apiRequest } from '../../common/helpers/api'; export const BETA_REGISTERING = 'BETA_REGISTERING'; export const BETA_REGISTER_SUCCESS = 'BETA_REGISTER_SUCCESS'; export const BETA_REGISTER_FAILURE = 'BETA_REGISTER_FAILURE'; export function registerBeta() { return dispatch => { dispatch({ type: BETA_REGISTERING }); const settings = { method: 'POST', }; apiRequest('/health_beta_registrations', settings, response => dispatch({ type: BETA_REGISTER_SUCCESS, username: response.user, stats: 'succeeded', }), () => dispatch({ type: BETA_REGISTER_FAILURE, stats: 'failed' }) ); }; }
Fix log not appending in gui
package com.swandiggy.poe4j.gui.log; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; import javafx.application.Platform; import javafx.collections.FXCollections; import javafx.collections.ObservableList; /** * @author Jacob Swanson * @since 12/10/2015 */ public class ObservableLogAppender extends AppenderBase<ILoggingEvent> { public static ObservableList<ILoggingEvent> events = FXCollections.observableArrayList(); @Override protected void append(ILoggingEvent event) { Platform.runLater(() -> { events.add(event); if (events.size() > 500) { events.remove(0); } }); } }
package com.swandiggy.poe4j.gui.log; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; import javafx.application.Platform; import javafx.collections.FXCollections; import javafx.collections.ObservableList; /** * @author Jacob Swanson * @since 12/10/2015 */ public class ObservableLogAppender extends AppenderBase<ILoggingEvent> { public static ObservableList<ILoggingEvent> events = FXCollections.observableArrayList(); @Override protected void append(ILoggingEvent event) { Platform.runLater(() -> { events.add(event); if (events.size() > 500) { events.remove(events.size() - 1); } }); } }
Adjust dimensions of grid to be squarer
module.exports = { Env: process.env.NODE_ENV || 'development', Permissions: { viewPage: 'viewPage' }, boxWidth: 40, boxHeight: 35, Difficulties: { 1: { name: 'Very Easy', percent: 10 }, 2: { name: 'Easy', percent: 15 }, 3: { name: 'Medium', percent: 20 }, 4: { name: 'Hard', percent: 30 }, 5: { name: 'Nightmare', percent: 60 }, 6: { name: 'Impossibruuu!!', percent: 90 } } };
module.exports = { Env: process.env.NODE_ENV || 'development', Permissions: { viewPage: 'viewPage' }, boxWidth: 55, boxHeight: 30, Difficulties: { 1: { name: 'Very Easy', percent: 10 }, 2: { name: 'Easy', percent: 15 }, 3: { name: 'Medium', percent: 20 }, 4: { name: 'Hard', percent: 30 }, 5: { name: 'Nightmare', percent: 60 }, 6: { name: 'Impossibruuu!!', percent: 90 } } };
Fix FAT constant for TI-83+
import os import requests from sys import stderr, exit from resources import get_resource_root def get_key(platform): if platform == "TI73": return 0x02 if platform == "TI83p" or platform == "TI83pSE": return 0x04 if platform == "TI84p" or platform == "TI84pSE": return 0x0A if platform == "TI84pCSE": return 0x0F def get_upgrade_ext(platform): if platform == "TI73": return '73u' if platform == "TI84pCSE": return '8cu' return '8xu' def get_privileged(platform): if platform == "TI73": return 0x1C if platform == "TI83p": return 0x1C if platform == "TI83pSE": return 0x7C if platform == "TI84p": return 0x3C if platform == "TI84pSE": return 0x7C if platform == "TI84pCSE": return 0xFC def get_fat(platform): if platform == "TI73": return 0x17 if platform == "TI83p": return 0x17 if platform == "TI83pSE": return 0x77 if platform == "TI84p": return 0x37 if platform == "TI84pSE": return 0x77 if platform == "TI84pCSE": return 0xF7
import os import requests from sys import stderr, exit from resources import get_resource_root def get_key(platform): if platform == "TI73": return 0x02 if platform == "TI83p" or platform == "TI83pSE": return 0x04 if platform == "TI84p" or platform == "TI84pSE": return 0x0A if platform == "TI84pCSE": return 0x0F def get_upgrade_ext(platform): if platform == "TI73": return '73u' if platform == "TI84pCSE": return '8cu' return '8xu' def get_privileged(platform): if platform == "TI73": return 0x1C if platform == "TI83p": return 0x1C if platform == "TI83pSE": return 0x7C if platform == "TI84p": return 0x3C if platform == "TI84pSE": return 0x7C if platform == "TI84pCSE": return 0xFC def get_fat(platform): if platform == "TI73": return 0x17 if platform == "TI83p": return 0x37 if platform == "TI83pSE": return 0x77 if platform == "TI84p": return 0x37 if platform == "TI84pSE": return 0x77 if platform == "TI84pCSE": return 0xF7
tests: Update splay_health() test to new module
"""Test ELB creation functions.""" from foremast.elb.splay_health import splay_health def test_splay(): """Splay should split Health Checks properly.""" health = splay_health('HTTP:80/test') assert health.path == '/test' assert health.port == '80' assert health.proto == 'HTTP' assert health.target == 'HTTP:80/test' health = splay_health('TCP:8000/test') assert health.path == '' assert health.port == '8000' assert health.proto == 'TCP' assert health.target == 'TCP:8000' health = splay_health('HTTPS:8000/test') assert health.path == '/test' assert health.port == '8000' assert health.proto == 'HTTPS' assert health.target == 'HTTPS:8000/test' health = splay_health('HTTPS:80') assert health.path == '/healthcheck' assert health.port == '80' assert health.proto == 'HTTPS' assert health.target == 'HTTPS:80/healthcheck'
"""Test ELB creation functions.""" from foremast.elb.create_elb import SpinnakerELB def test_splay(): """Splay should split Health Checks properly.""" health = SpinnakerELB.splay_health('HTTP:80/test') assert health.path == '/test' assert health.port == '80' assert health.proto == 'HTTP' assert health.target == 'HTTP:80/test' health = SpinnakerELB.splay_health('TCP:8000/test') assert health.path == '' assert health.port == '8000' assert health.proto == 'TCP' assert health.target == 'TCP:8000' health = SpinnakerELB.splay_health('HTTPS:8000/test') assert health.path == '/test' assert health.port == '8000' assert health.proto == 'HTTPS' assert health.target == 'HTTPS:8000/test' health = SpinnakerELB.splay_health('HTTPS:80') assert health.path == '/healthcheck' assert health.port == '80' assert health.proto == 'HTTPS' assert health.target == 'HTTPS:80/healthcheck'
Print traceback if startup fails
from traceback import print_exc from django.core.management.base import BaseCommand from cthulhubot.models import Buildmaster class Command(BaseCommand): help = 'Restart all Buildmaster processes' args = "" def handle(self, *fixture_labels, **options): verbosity = int(options.get('verbosity', 1)) commit = int(options.get('commit', 1)) if verbosity > 1: print 'Restarting buildmasters...' for b in Buildmaster.objects.all(): if verbosity > 1: print 'Handling buildmaster %s for project %s' % (str(b.id), str(b.project.name)) try: b.stop() except: print 'Failed to stop master' print_exc() try: b.start() except: print 'Failed to start master' print_exc()
from django.core.management.base import BaseCommand from cthulhubot.models import Buildmaster class Command(BaseCommand): help = 'Restart all Buildmaster processes' args = "" def handle(self, *fixture_labels, **options): verbosity = int(options.get('verbosity', 1)) commit = int(options.get('commit', 1)) if verbosity > 1: print 'Restarting buildmasters...' for b in Buildmaster.objects.all(): if verbosity > 1: print 'Handling buildmaster %s for project %s' % (str(b.id), str(b.project.name)) try: b.stop() except: print 'Failed to stop master' try: b.start() except: print 'Failed to start master'
Check that passwords match in frontend
'use strict'; define(['ChoPidoTurnos', 'services/usersService'], function(ChoPidoTurnos) { ChoPidoTurnos.controller('RecoverPasswordCtrl', ['$stateParams', 'usersService', '$state', function($stateParams, usersService, $state) { var _this = this; this.$onInit = function() { this.alerts = []; this.token = $stateParams.token; }; this.sendPasswordReset = function() { if (_this.password != _this.passwordConfirmation) { _this.alerts.push({message: 'Las contraseñas no coinciden', type: 'danger'}); return; } usersService.resetPassword({ token: _this.token, password: _this.password, passwordConfirmation: _this.passwordConfirmation }).then(function(response) { if (response.status >= 400 || response.status < 0) { _this.alerts.push({message: 'Ha ocurrido un error restableciendo su contraseña', type: 'danger'}); return; } _this.alerts.push({message: 'Su contraseña ha sido restablecida', type: 'success'}); $state.go('login'); }); }; }]); });
'use strict'; define(['ChoPidoTurnos', 'services/usersService'], function(ChoPidoTurnos) { ChoPidoTurnos.controller('RecoverPasswordCtrl', ['$stateParams', 'usersService', '$state', function($stateParams, usersService, $state) { var _this = this; this.$onInit = function() { this.alerts = []; this.token = $stateParams.token; }; this.sendPasswordReset = function() { usersService.resetPassword({ token: _this.token, password: _this.password, passwordConfirmation: _this.passwordConfirmation }).then(function(response) { if (response.status >= 400 || response.status < 0) { _this.alerts.push({message: 'Ha ocurrido un error restableciendo su contraseña', type: 'danger'}); return; } _this.alerts.push({message: 'Su contraseña ha sido restablecida', type: 'success'}); $state.go('login'); }); }; }]); });
Update IAM Role cfn resource
var AWSResource = require('../awsresource') , types = require('../types'); var Role = AWSResource.define('AWS::IAM::Role', { AssumeRolePolicyDocument : { type: types.object('iam-assume-role-policy-document'), required: true }, ManagedPolicyArns: { type: types.array }, Path : { type: types.string }, Policies : { type: types.array }, }); var Policy = AWSResource.define('AWS::IAM::Policy', { Groups : { type: types.array, required: 'conditional' }, PolicyDocument : { type: types.object('iam-policy-document'), required: true }, PolicyName : { type: types.string, required: true }, Roles : { type: types.array }, Users : { type: types.array, required: 'conditional' }, }); function PathValidator(self) { // TODO: Half assed solution. Path can be a fn.Join for eg. if (typeof self.properties.Path === 'string' && !/^\/[a-zA-Z0-9+=,.@_\-\/]*\/$/.test(self.properties.Path)) { return 'Path can contain only alphanumeric characters and / and begin and end with /'; }; } var InstanceProfile = AWSResource.define('AWS::IAM::InstanceProfile', { Path : { type: types.string, required: true, validators: [PathValidator] }, Roles : { type: types.array, required: true }, }); module.exports = { Role: Role, Policy: Policy, InstanceProfile: InstanceProfile };
var AWSResource = require('../awsresource') , types = require('../types'); var Role = AWSResource.define('AWS::IAM::Role', { AssumeRolePolicyDocument : { type: types.object('iam-assume-role-policy-document'), required: true }, Path : { type: types.string, required: true }, Policies : { type: types.array }, }); var Policy = AWSResource.define('AWS::IAM::Policy', { Groups : { type: types.array, required: 'conditional' }, PolicyDocument : { type: types.object('iam-policy-document'), required: true }, PolicyName : { type: types.string, required: true }, Roles : { type: types.array }, Users : { type: types.array, required: 'conditional' }, }); function PathValidator(self) { // TODO: Half assed solution. Path can be a fn.Join for eg. if (typeof self.properties.Path === 'string' && !/^\/[a-zA-Z0-9+=,.@_\-\/]*\/$/.test(self.properties.Path)) { return 'Path can contain only alphanumeric characters and / and begin and end with /'; }; } var InstanceProfile = AWSResource.define('AWS::IAM::InstanceProfile', { Path : { type: types.string, required: true, validators: [PathValidator] }, Roles : { type: types.array, required: true }, }); module.exports = { Role: Role, Policy: Policy, InstanceProfile: InstanceProfile };
Add real uuid for fixtures
/* @flow */ import Moment from 'moment'; import type { Poster } from '../types'; // State type State = { posters: Array<Poster> } const initialState: State = { posters: [ { key: '5ef45c84-84b7-4f7c-9b53-336970cd5759', title: 'Imperfect centered sites - a new mode of miRNA binding', thumbnailUrl: 'https://s3-eu-west-1.amazonaws.com/pfigshare-u-previews/1710259/thumb.png', authors: 'Nicole Cloonan', savedAt: Moment() }, { key: '2579ef1b-8266-4363-9ab3-2448eef068c2', title: 'The Value Proposition of Libraries in Research Information Management', thumbnailUrl: 'https://s3-eu-west-1.amazonaws.com/pfigshare-u-previews/9011278/thumb.png', authors: 'Rebecca Bryant, Holly Mercer', savedAt: Moment() }, ], }; // Actions // Action Creators // Reducer export default function reducer(state: Object = initialState, action: Object = {}) { switch (action.type) { default: return state; } }
/* @flow */ import Moment from 'moment'; import type { Poster } from '../types'; // State type State = { posters: Array<Poster> } const initialState: State = { posters: [ { key: 'uuid-01', title: 'Imperfect centered sites - a new mode of miRNA binding', thumbnailUrl: 'https://s3-eu-west-1.amazonaws.com/pfigshare-u-previews/1710259/thumb.png', authors: 'Nicole Cloonan', savedAt: Moment() }, { key: 'uuid-02', title: 'The Value Proposition of Libraries in Research Information Management', thumbnailUrl: 'https://s3-eu-west-1.amazonaws.com/pfigshare-u-previews/9011278/thumb.png', authors: 'Rebecca Bryant, Holly Mercer', savedAt: Moment() }, ], }; // Actions // Action Creators // Reducer export default function reducer(state: Object = initialState, action: Object = {}) { switch (action.type) { default: return state; } }
Fix inheritance issue in api resource getters.
const Resource = require('../api_resource').Resource; class ContentNodeResource extends Resource { constructor(...args) { super(...args); this._models = {}; } setChannel(channelId) { // Track models for different channels separately. if (!this._models[channelId]) { this._models[channelId] = {}; } this.models = this._models[channelId]; this.channelId = channelId; } get modelUrl() { // Return a function that calls the modelUrl method of the base class, but prefix the arguments // with the channelId that is currently set. // N.B. Here and below the super calls are to getters that return functions that are // immediately invoked. return (...args) => this.urls[`${this.name}_detail`](this.channelId, ...args); } get collectionUrl() { // Return a function that calls the collectionUrl method of the base class, but prefix the // arguments with the channelId that is currently set. return (...args) => this.urls[`${this.name}_list`](this.channelId, ...args); } static resourceName() { return 'contentnode'; } static idKey() { return 'pk'; } } module.exports = ContentNodeResource;
const Resource = require('../api_resource').Resource; class ContentNodeResource extends Resource { constructor(...args) { super(...args); this._models = {}; } setChannel(channelId) { // Track models for different channels separately. if (!this._models[channelId]) { this._models[channelId] = {}; } this.models = this._models[channelId]; this.channelId = channelId; } get modelUrl() { // Return a function that calls the modelUrl method of the base class, but prefix the arguments // with the channelId that is currently set. // N.B. Here and below the super calls are to getters that return functions that are // immediately invoked. return (...args) => super.modelUrl(this.channelId, ...args); } get collectionUrl() { // Return a function that calls the collectionUrl method of the base class, but prefix the // arguments with the channelId that is currently set. return (...args) => super.collectionUrl(this.channelId, ...args); } static resourceName() { return 'contentnode'; } static idKey() { return 'pk'; } } module.exports = ContentNodeResource;
Make this a parameter of the function.
<?php namespace Phortress; use PhpParser\Node\Expr\Assign; use PhpParser\Node\Expr\New_; use PhpParser\Node\Expr\Variable; use PhpParser\Node\Name; use PhpParser\Node\Param; use PhpParser\Node\Stmt; class ClassInstanceEnvironment extends Environment { use EnvironmentHasFunctionsTrait { createFunction as traitCreateFunction; } /** * The class environment for this instance. * * @var ClassEnvironment */ private $classEnvironment; /** * @param string $name The name of the class. * @param ClassEnvironment $classEnvironment The class environment for instances of this class. */ public function __construct($name, $classEnvironment) { parent::__construct($name, $classEnvironment); $this->classEnvironment = $classEnvironment; } public function shouldResolveVariablesInParentEnvironment() { // Only ourself. return false; } public function createChild() { return $this; } /** * @inheritdoc * @param Stmt\ClassMethod $function */ public function createFunction(Stmt $function) { assert($function instanceof Stmt\ClassMethod, 'Only accepts class methods'); $result = $this->traitCreateFunction($function); // Assign $this $result->variables['this'] = new Param( 'this', null, new Name($this->classEnvironment->getName()) ); return $result; } }
<?php namespace Phortress; use PhpParser\Node\Expr\Assign; use PhpParser\Node\Expr\New_; use PhpParser\Node\Expr\Variable; use PhpParser\Node\Name; use PhpParser\Node\Stmt; class ClassInstanceEnvironment extends Environment { use EnvironmentHasFunctionsTrait { createFunction as traitCreateFunction; } /** * The class environment for this instance. * * @var ClassEnvironment */ private $classEnvironment; /** * @param string $name The name of the class. * @param ClassEnvironment $classEnvironment The class environment for instances of this class. */ public function __construct($name, $classEnvironment) { parent::__construct($name, $classEnvironment); $this->classEnvironment = $classEnvironment; } public function shouldResolveVariablesInParentEnvironment() { // Only ourself. return false; } public function createChild() { return $this; } /** * @inheritdoc * @param Stmt\ClassMethod $function */ public function createFunction(Stmt $function) { assert($function instanceof Stmt\ClassMethod, 'Only accepts class methods'); $result = $this->traitCreateFunction($function); // Assign $this $result->variables['this'] = (new Assign( new Variable('this'), new New_(new Name($this->classEnvironment->getName())) )); return $result; } }
Fix issue with writing to log file when not suppose to
/*jslint node: true */ 'use strict'; var fs = require('fs'); var Logger = function() {}; var defaults = function(object, defaults) { for (var prop in defaults) { if (object[prop] === void 0) object[prop] = defaults[prop]; } return object; }; Logger.prototype.setOptions = function(options) { this.options = defaults(options || {}, {file: __dirname + '/logger.log', consoleLog: true}); if (this.options.file) { this.logger = fs.createWriteStream(this.options.file, { flags: 'a' }); } }, Logger.prototype.log = function(message) { if (message) { if (!this.options) this.setOptions(); if (this.options.consoleLog) console.log(message); if (this.logger) this.logger.write(new Date() + ' ' + JSON.stringify(message) + "\n"); } }; module.exports = new Logger();
/*jslint node: true */ 'use strict'; var fs = require('fs'); var Logger = function() {}; var defaults = function(object, defaults) { for (var prop in defaults) { if (object[prop] === void 0) object[prop] = defaults[prop]; } return object; }; Logger.prototype.setOptions = function(options) { this.options = defaults(options || {}, {file: __dirname + '/logger.log', consoleLog: true}); if (this.options.file) { this.logger = fs.createWriteStream(this.options.file, { flags: 'a' }); } }, Logger.prototype.log = function(message) { if (message) { if (!this.options) this.setOptions(); if (this.options.consoleLog) console.log(message); this.logger.write(new Date() + ' ' + JSON.stringify(message) + "\n"); } }; module.exports = new Logger();
Set construct parameter as optional This class could be call without parameter
<?php namespace App\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Validator\Constraints as Assert; class MailType extends AbstractType { private $idTournament; function __construct($idTournament = NULL) { $this->idTournament = $idTournament; } public function buildForm(FormBuilderInterface $builder, array $options ) { $builder->add('email', "email", array("constraints" => array( new Assert\NotBlank(), new Assert\Email()), "attr" => array("placeholder" => "email", "class" => "form-control")) ); $builder->add('tournament', 'hidden', array( 'data' => $this->idTournament, )); } public function getName() { return "mail"; } }
<?php namespace App\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Validator\Constraints as Assert; class MailType extends AbstractType { function __construct($idTournament) { $this->idTournament = $idTournament; } public function buildForm(FormBuilderInterface $builder, array $options ) { $builder->add('email', "email", array("constraints" => array( new Assert\NotBlank(), new Assert\Email()), "attr" => array("placeholder" => "email", "class" => "form-control")) ); $builder->add('tournament', 'hidden', array( 'data' => $this->idTournament, )); } public function getName() { return "mail"; } }
Make sure we still log the fact that the teacher logged in as someone though. Also, make the "realuser" the teacher's id, in case we want to use it later
<?PHP // $Id$ require("../config.php"); require("lib.php"); require_variable($id); // course id require_variable($user); // login as this user if (! $course = get_record("course", "id", $id)) { error("Course ID was incorrect"); } require_login($course->id); if (!isteacher($course->id)) { error("Only teachers can use this page!"); } if (!isstudent($course->id, $user)) { error("This student is not in this course!"); } // Login as this student and return to course home page. $teacher_name = "$USER->firstname $USER->lastname"; $teacher_id = "$USER->id"; $USER = get_user_info_from_db("id", $user); $USER->loggedin = true; set_moodle_cookie($USER->username); $student_name = "$USER->firstname $USER->lastname"; add_to_log($course->id, "course", "loginas", "../user/view.php?id=$course->id&user=$user", "$teacher_name -> $student_name"); $USER->realuser = $teacher_id; notice("You are now logged in as $student_name", "$CFG->wwwroot/course/view.php?id=$course->id"); ?>
<?PHP // $Id$ require("../config.php"); require("lib.php"); require_variable($id); // course id require_variable($user); // login as this user if (! $course = get_record("course", "id", $id)) { error("Course ID was incorrect"); } require_login($course->id); if (!isteacher($course->id)) { error("Only teachers can use this page!"); } if (!isstudent($course->id, $user)) { error("This student is not in this course!"); } // Login as this student and return to course home page. $teacher_name = "$USER->firstname $USER->lastname"; $USER = get_user_info_from_db("id", $user); $USER->loggedin = true; $USER->realuser = $teacher_name; set_moodle_cookie($USER->username); $student_name = "$USER->firstname $USER->lastname"; add_to_log($course->id, "course", "loginas", "../user/view.php?id=$course->id&user=$user", "$teacher_name"); notice("You are now logged in as $student_name", "$CFG->wwwroot/course/view.php?id=$course->id"); ?>
Move export into line where class is defined
/* * Copyright (c) 2015, Yahoo Inc. All rights reserved. * Copyrights licensed under the New BSD License. * See the accompanying LICENSE file for terms. */ import {BaseStore} from 'fluxible/addons'; import Immutable from 'immutable'; export default class ImmutableStore extends BaseStore { constructor(dispatcher) { super(dispatcher); this._state = Immutable.Map(); } dehydrate() { return this._state; } rehydrate(state) { this._state = Immutable.fromJS(state); } setState(newState, event, payload) { newState = Immutable.fromJS(newState); if (this._state.equals(newState)) { return false; } this._state = newState; event ? this.emit(event, payload) : this.emitChange(payload); return true; } mergeState(stateFragment, event, payload) { return this.setState( this._state.merge(stateFragment), event, payload ); } getState() { return this.dehydrate(); } }
/* * Copyright (c) 2015, Yahoo Inc. All rights reserved. * Copyrights licensed under the New BSD License. * See the accompanying LICENSE file for terms. */ import {BaseStore} from 'fluxible/addons'; import Immutable from 'immutable'; class ImmutableStore extends BaseStore { constructor(dispatcher) { super(dispatcher); this._state = Immutable.Map(); } dehydrate() { return this._state; } rehydrate(state) { this._state = Immutable.fromJS(state); } setState(newState, event, payload) { newState = Immutable.fromJS(newState); if (this._state.equals(newState)) { return false; } this._state = newState; event ? this.emit(event, payload) : this.emitChange(payload); return true; } mergeState(stateFragment, event, payload) { return this.setState( this._state.merge(stateFragment), event, payload ); } getState() { return this.dehydrate(); } } export default ImmutableStore;
[API][Product] Change identifier for shop endpoint from slug to code
<?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\Repository; use Doctrine\ORM\QueryBuilder; use Sylius\Component\Core\Model\ChannelInterface; use Sylius\Component\Core\Model\ProductInterface; use Sylius\Component\Core\Model\TaxonInterface; use Sylius\Component\Product\Repository\ProductRepositoryInterface as BaseProductRepositoryInterface; interface ProductRepositoryInterface extends BaseProductRepositoryInterface { /** * @param mixed|null $taxonId */ public function createListQueryBuilder(string $locale, $taxonId = null): QueryBuilder; public function createShopListQueryBuilder( ChannelInterface $channel, TaxonInterface $taxon, string $locale, array $sorting = [], bool $includeAllDescendants = false ): QueryBuilder; /** * @return array|ProductInterface[] */ public function findLatestByChannel(ChannelInterface $channel, string $locale, int $count): array; public function findOneByChannelAndSlug(ChannelInterface $channel, string $locale, string $slug): ?ProductInterface; public function findOneByChannelAndCode(ChannelInterface $channel, string $code): ?ProductInterface; public function findOneByCode(string $code): ?ProductInterface; }
<?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\Repository; use Doctrine\ORM\QueryBuilder; use Sylius\Component\Core\Model\ChannelInterface; use Sylius\Component\Core\Model\ProductInterface; use Sylius\Component\Core\Model\TaxonInterface; use Sylius\Component\Product\Repository\ProductRepositoryInterface as BaseProductRepositoryInterface; interface ProductRepositoryInterface extends BaseProductRepositoryInterface { /** * @param mixed|null $taxonId */ public function createListQueryBuilder(string $locale, $taxonId = null): QueryBuilder; public function createShopListQueryBuilder( ChannelInterface $channel, TaxonInterface $taxon, string $locale, array $sorting = [], bool $includeAllDescendants = false ): QueryBuilder; /** * @return array|ProductInterface[] */ public function findLatestByChannel(ChannelInterface $channel, string $locale, int $count): array; public function findOneByChannelAndSlug(ChannelInterface $channel, string $locale, string $slug): ?ProductInterface; public function findOneByCode(string $code): ?ProductInterface; }
Increase timeout in TabConsoleTest.testConsoleOutputStream twice. On machines with low performance this test can fail by timeout. Increasing timeout improves stability of this unittest passing. Change-Id: I83a97022bbf96a4aaca349211ae7cfb9d19359b1 Reviewed-on: https://chromium-review.googlesource.com/c/catapult/+/2909584 Reviewed-by: John Chen <334fbfbb4df7c78f091ea1b77c69ca6ac731a3f3@chromium.org> Commit-Queue: John Chen <334fbfbb4df7c78f091ea1b77c69ca6ac731a3f3@chromium.org>
# Copyright 2013 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 __future__ import absolute_import import re from telemetry.testing import tab_test_case import py_utils class TabConsoleTest(tab_test_case.TabTestCase): def testConsoleOutputStream(self): self.Navigate('page_that_logs_to_console.html') initial = self._tab.EvaluateJavaScript('window.__logCount') def GotLog(): current = self._tab.EvaluateJavaScript('window.__logCount') return current > initial py_utils.WaitFor(GotLog, 10) console_output = ( self._tab._inspector_backend.GetCurrentConsoleOutputBuffer()) lines = [l for l in console_output.split('\n') if len(l)] self.assertTrue(len(lines) >= 1) for line in lines: prefix = 'http://(.+)/page_that_logs_to_console.html:9' expected_line = r'\(log\) %s: Hello, world' % prefix self.assertTrue(re.match(expected_line, line))
# Copyright 2013 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 __future__ import absolute_import import re from telemetry.testing import tab_test_case import py_utils class TabConsoleTest(tab_test_case.TabTestCase): def testConsoleOutputStream(self): self.Navigate('page_that_logs_to_console.html') initial = self._tab.EvaluateJavaScript('window.__logCount') def GotLog(): current = self._tab.EvaluateJavaScript('window.__logCount') return current > initial py_utils.WaitFor(GotLog, 5) console_output = ( self._tab._inspector_backend.GetCurrentConsoleOutputBuffer()) lines = [l for l in console_output.split('\n') if len(l)] self.assertTrue(len(lines) >= 1) for line in lines: prefix = 'http://(.+)/page_that_logs_to_console.html:9' expected_line = r'\(log\) %s: Hello, world' % prefix self.assertTrue(re.match(expected_line, line))
Add a bit of safeguard against malicious attacks
package main import ( "errors" "net/http" "github.com/gin-gonic/gin" ) func killBrowserHandler(c *gin.Context) { var data struct { Action string `json:"action"` Process string `json:"process"` URL string `json:"url"` } c.BindJSON(&data) if data.Process != "chrome" && data.Process != "chrom" { c.JSON(http.StatusBadRequest, errors.New("You can't kill the process"+data.Process)) return } command, err := findBrowser(data.Process) if err != nil { c.JSON(http.StatusInternalServerError, err.Error()) return } if data.Action == "kill" || data.Action == "restart" { _, err := killBrowser(data.Process) if err != nil { c.JSON(http.StatusInternalServerError, err.Error()) return } } if data.Action == "restart" { _, err := startBrowser(command, data.URL) if err != nil { c.JSON(http.StatusInternalServerError, err.Error()) return } } }
package main import ( "log" "net/http" "github.com/gin-gonic/gin" ) func killBrowserHandler(c *gin.Context) { var data struct { Action string `json:"action"` Process string `json:"process"` URL string `json:"url"` } c.BindJSON(&data) command, err := findBrowser(data.Process) log.Println(command) if err != nil { c.JSON(http.StatusInternalServerError, err.Error()) } if data.Action == "kill" || data.Action == "restart" { _, err := killBrowser(data.Process) if err != nil { c.JSON(http.StatusInternalServerError, err.Error()) } } if data.Action == "restart" { _, err := startBrowser(command, data.URL) if err != nil { c.JSON(http.StatusInternalServerError, err.Error()) } } }
Fix Event.dispatch to return True if execution is to proceed
# event system EVENT_CALLBACKS = {} def add_listener(event, callback, priority = 5): if event not in EVENT_CALLBACKS: EVENT_CALLBACKS[event] = [] if (priority, callback) not in EVENT_CALLBACKS[event]: EVENT_CALLBACKS[event].append((priority, callback)) EVENT_CALLBACKS[event].sort(key = lambda x: x[0]) def remove_listener(event, callback, priority = 5): if event in EVENT_CALLBACKS and (priority, callback) in EVENT_CALLBACKS[event]: EVENT_CALLBACKS[event].remove((priority, callback)) class Event: def __init__(self, name, data): self.stop_processing = False self.prevent_default = False self.name = name self.data = data def dispatch(self, *args): if self.name not in EVENT_CALLBACKS: return True for item in list(EVENT_CALLBACKS[self.name]): item[1](self, *args) if self.stop_processing: break return not self.prevent_default # vim: set expandtab:sw=4:ts=4:
# event system EVENT_CALLBACKS = {} def add_listener(event, callback, priority = 5): if event not in EVENT_CALLBACKS: EVENT_CALLBACKS[event] = [] if (priority, callback) not in EVENT_CALLBACKS[event]: EVENT_CALLBACKS[event].append((priority, callback)) EVENT_CALLBACKS[event].sort(key = lambda x: x[0]) def remove_listener(event, callback, priority = 5): if event in EVENT_CALLBACKS and (priority, callback) in EVENT_CALLBACKS[event]: EVENT_CALLBACKS[event].remove((priority, callback)) class Event: def __init__(self, name, data): self.stop_processing = False self.prevent_default = False self.name = name self.data = data def dispatch(self, *args): if self.name not in EVENT_CALLBACKS: return for item in list(EVENT_CALLBACKS[self.name]): item[1](self, *args) if self.stop_processing: break return not self.prevent_default # vim: set expandtab:sw=4:ts=4:
Set defaults for tempo, division, sequence
'use strict'; var EventEmitter = require('events').EventEmitter; var inherits = require('util').inherits; var NanoTimer = require('nanotimer'); function StepSequencer(tempo, division, sequence) { this.tempo = tempo || 120; this.division = division || 4; this.sequence = sequence || []; this.step = 0; this.timer = new NanoTimer(); this.timeout = Math.floor((60 / (tempo * division)) * 10e8) + 'n'; EventEmitter.call(this); } inherits(StepSequencer, EventEmitter); StepSequencer.prototype._advance = function () { this.emit('' + this.step, this.sequence[this.step]); this.step = (this.step + 1); if (this.step === this.sequence.length) this.step = 0; } StepSequencer.prototype.play = function () { var self = this; self.step = 0; self.timer.setInterval(function () { self._advance.call(self); }, '', self.timeout); }; StepSequencer.prototype.resume = function () { var self = this; self.timer.setInterval(function () { self._advance.call(self); }, '', self.timeout); }; StepSequencer.prototype.stop = function () { this.timer.clearInterval(); }; module.exports = StepSequencer;
'use strict'; var EventEmitter = require('events').EventEmitter; var inherits = require('util').inherits; var NanoTimer = require('nanotimer'); function StepSequencer(tempo, division, sequence) { this.tempo = tempo; this.division = division; this.sequence = sequence; this.step = 0; this.timer = new NanoTimer(); this.timeout = Math.floor((60 / (tempo * division)) * 10e8) + 'n'; EventEmitter.call(this); } inherits(StepSequencer, EventEmitter); StepSequencer.prototype._advance = function () { this.emit('' + this.step, this.sequence[this.step]); this.step = (this.step + 1); if (this.step === this.sequence.length) this.step = 0; } StepSequencer.prototype.play = function () { var self = this; self.step = 0; self.timer.setInterval(function () { self._advance.call(self); }, '', self.timeout); }; StepSequencer.prototype.resume = function () { var self = this; self.timer.setInterval(function () { self._advance.call(self); }, '', self.timeout); }; StepSequencer.prototype.stop = function () { this.timer.clearInterval(); }; module.exports = StepSequencer;
Fix another incorrect test setup
import nodeFetch from 'node-fetch' import app from '../server' describe('server', () => { function fetch (path, init) { return nodeFetch(`http://localhost:3000${path}`, init) } let server beforeAll(done => { server = app.listen(3000, done) }) afterAll(done => { server.close(done) }) describe('GET /', () => { it('responds with success', () => { return expect(fetch('/')).resolves.toHaveProperty('status', 200) }) }) describe('GET /index.json', () => { it('responds with features', () => { return fetch('/index.json', { headers: { 'Content-Type': /json/ } }).then(response => { expect(response.status).toBe(200) return expect(response.json()).resolves.not.toHaveLength(0) }) }) }) describe('GET /404', () => { it('responds with a 404 error', () => { return expect(fetch('/404')).resolves.toHaveProperty('status', 404) }) }) })
import nodeFetch from 'node-fetch' import app from '../server' describe('server', () => { function fetch (path, init) { return nodeFetch(`http://localhost:3000${path}`, init) } let server beforeAll(done => { server = app.listen(3000, done) }) afterAll(done => server.close(done)) describe('GET /', () => { it('responds with success', () => { return expect(fetch('/')).resolves.toHaveProperty('status', 200) }) }) describe('GET /index.json', () => { it('responds with features', () => { return fetch('/index.json', { headers: { 'Content-Type': /json/ } }).then(response => { expect(response.status).toBe(200) return expect(response.json()).resolves.not.toHaveLength(0) }) }) }) describe('GET /404', () => { it('responds with a 404 error', () => { return expect(fetch('/404')).resolves.toHaveProperty('status', 404) }) }) })
Add correct 'from' email address on SendEmail function. Related #178
'use strict'; const handelbars = require('handlebars'); const fs = require('fs'); const path = require('path'); const nodemailer = require('nodemailer'); require('env2')(`${__dirname}/../.env`); // create reusable transporter object using the default SMTP transport const transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: process.env.EMAIL, pass: process.env.PASS } }); function sendMail(emailAddress, emailContent, cb){ const emailTemplate = fs.readFileSync(path.join(__dirname, 'templates', 'views', 'email.hbs'), 'utf8'); const template = handelbars.compile(emailTemplate); const emailBody = template(emailContent); const mailOptions = { from: '"CAMHS 😀" <welcome.to.cahms@gmail.com>', subject: 'Getting to know you Questionnaire', text: 'Questionnaire', html: emailBody, to: emailAddress }; transporter.sendMail(mailOptions, (error, info) => { if (error) { return cb(error); } return cb(null, `Message ${info.messageId} sent: ${info.response}`); }); } module.exports = sendMail;
'use strict'; const handelbars = require('handlebars'); const fs = require('fs'); const path = require('path'); const nodemailer = require('nodemailer'); require('env2')(`${__dirname}/../.env`); // create reusable transporter object using the default SMTP transport const transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: process.env.EMAIL, pass: process.env.PASS } }); function sendMail(emailAddress, emailContent, cb){ const emailTemplate = fs.readFileSync(path.join(__dirname, 'templates', 'views', 'email.hbs'), 'utf8'); const template = handelbars.compile(emailTemplate); const emailBody = template(emailContent); const mailOptions = { from: '"CAMHS 😀" <welcome.to.cahms@hotmail.co.uk>', subject: 'Getting to know you Questionnaire', text: 'Questionnaire', html: emailBody, to: emailAddress }; transporter.sendMail(mailOptions, (error, info) => { if (error) { return cb(error); } return cb(null, `Message ${info.messageId} sent: ${info.response}`); }); } module.exports = sendMail;
Add test for degenerate line fitter task.
package hu.kazocsaba.math.geometry.fitting; import hu.kazocsaba.math.geometry.DegenerateCaseException; import hu.kazocsaba.math.matrix.Vector2; import java.util.List; import hu.kazocsaba.math.geometry.Line2; import hu.kazocsaba.math.matrix.MatrixFactory; import hu.kazocsaba.math.matrix.immutable.ImmutableMatrixFactory; import java.util.ArrayList; import java.util.Collections; import java.util.Random; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Kazó Csaba */ public class LineFitterTest { private static final double EPS=1e-8; @Test public void testFit() { Line2 refLine=Line2.createFromDir(ImmutableMatrixFactory.createVector(3, 4), ImmutableMatrixFactory.createVector(-5, 2)); Random rnd=new Random(726); List<Vector2> points=new ArrayList<Vector2>(50); for (int i=0; i<50; i++) points.add(refLine.getPointAt(rnd.nextDouble())); Line2 fitLine=LineFitter.fit2(points); assertEquals(1, Math.abs(refLine.getUnitDir().dot(fitLine.getUnitDir())), EPS); assertEquals(0, refLine.distance(fitLine.getPoint()), EPS); } @Test(expected=DegenerateCaseException.class) public void testDegenerate() { LineFitter.fit2(Collections.nCopies(10, MatrixFactory.createVector(2, -4))); } }
package hu.kazocsaba.math.geometry.fitting; import hu.kazocsaba.math.matrix.Vector2; import java.util.List; import hu.kazocsaba.math.geometry.Line2; import hu.kazocsaba.math.matrix.immutable.ImmutableMatrixFactory; import java.util.ArrayList; import java.util.Random; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Kazó Csaba */ public class LineFitterTest { private static final double EPS=1e-8; @Test public void testFit() { Line2 refLine=Line2.createFromDir(ImmutableMatrixFactory.createVector(3, 4), ImmutableMatrixFactory.createVector(-5, 2)); Random rnd=new Random(726); List<Vector2> points=new ArrayList<Vector2>(50); for (int i=0; i<50; i++) points.add(refLine.getPointAt(rnd.nextDouble())); Line2 fitLine=LineFitter.fit2(points); assertEquals(1, Math.abs(refLine.getUnitDir().dot(fitLine.getUnitDir())), EPS); assertEquals(0, refLine.distance(fitLine.getPoint()), EPS); } }
Upgrade libchromium for the accelerator fix.
#!/usr/bin/env python import platform import sys NODE_VERSION = 'v0.11.13' BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = 'bb664e4665851fe923ce904e620ba43d8d010ba5' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }[sys.platform] DIST_ARCH = { '32bit': 'ia32', '64bit': 'x64', }[ARCH] TARGET_PLATFORM = { 'cygwin': 'win32', 'darwin': 'darwin', 'linux2': 'linux', 'win32': 'win32', }[sys.platform]
#!/usr/bin/env python import platform import sys NODE_VERSION = 'v0.11.13' BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = '197fe67fee1e4d867c76264065b2eb80b9dbd3a0' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }[sys.platform] DIST_ARCH = { '32bit': 'ia32', '64bit': 'x64', }[ARCH] TARGET_PLATFORM = { 'cygwin': 'win32', 'darwin': 'darwin', 'linux2': 'linux', 'win32': 'win32', }[sys.platform]
BB-7975: Add to configuration select with segment lists - cs fix
<?php namespace Oro\Bundle\SegmentBundle\Tests\Functional\Entity\Repository; use Doctrine\Bundle\DoctrineBundle\Registry; use Oro\Bundle\SegmentBundle\Entity\Repository\SegmentRepository; use Oro\Bundle\SegmentBundle\Tests\Functional\DataFixtures\LoadSegmentData; use Oro\Bundle\TestFrameworkBundle\Test\WebTestCase; class SegmentSnapshotRepositoryTest extends WebTestCase { protected function setUp() { $this->initClient(); $this->loadFixtures([LoadSegmentData::class]); } public function testFindByEntity() { /** @var Registry $registry */ $registry = $this->getContainer()->get('doctrine'); /** @var SegmentRepository $segmentRepository */ $segmentRepository = $registry->getRepository('OroSegmentBundle:Segment'); $result = $segmentRepository->findByEntity('Oro\Bundle\TestFrameworkBundle\Entity\WorkflowAwareEntity'); $this->assertCount(50, $result); foreach ($result as $segment) { $this->assertStringStartsWith('segment_', $segment); } } }
<?php namespace Oro\Bundle\SegmentBundle\Tests\Functional\Entity\Repository; use Doctrine\Bundle\DoctrineBundle\Registry; use Oro\Bundle\SegmentBundle\Entity\Repository\SegmentRepository; use Oro\Bundle\SegmentBundle\Tests\Functional\DataFixtures\LoadSegmentData; use Oro\Bundle\TestFrameworkBundle\Test\WebTestCase; class SegmentSnapshotRepositoryTest extends WebTestCase { protected function setUp() { $this->initClient(); $this->loadFixtures([LoadSegmentData::class]); } public function testFindByEntity() { /** @var Registry $registry */ $registry = $this->getContainer()->get('doctrine'); /** @var SegmentRepository $segmentRepository */ $segmentRepository = $registry->getRepository('OroSegmentBundle:Segment'); $result = $segmentRepository->findByEntity('Oro\Bundle\TestFrameworkBundle\Entity\WorkflowAwareEntity'); $this->assertCount(50, $result); foreach ($result as $segment) { $this->assertStringStartsWith('segment_', $segment); } } }
Remove extra wrapper for nav state
const {PUSH, POP, REPLACE} = require('../constants/navigation'); module.exports = function navigate(state, {type, payload}) { if (!state) { return {}; } const stack = state.stack; const index = state.index; switch (type) { case PUSH: return Object.assign({}, state, { stack: stack.push(payload), index: 0, }); case POP: if (stack.count() === 1) { return state; } return Object.assign({}, state, { stack: stack.shift(), index: 0, }); case REPLACE: if (!stack.count()) { return state; } return Object.assign({}, state, { stack: stack.splice(index, 1, payload), index: index, }); default: return state; } };
const {PUSH, POP, REPLACE} = require('../constants/navigation'); module.exports = function navigate(state, {type, payload}) { if (!state) { return {}; } const stack = state.__navRedux.stack; const index = state.__navRedux.index; switch (type) { case PUSH: return Object.assign({}, state, { __navRedux: { stack: stack.push(payload), index: 0, }, }); case POP: if (stack.count() === 1) { return state; } return Object.assign({}, state, { __navRedux: { stack: stack.shift(), index: 0, }, }); case REPLACE: if (!stack.count()) { return state; } return Object.assign({}, state, { stack: stack.splice(index, 1, payload), index: index, }); default: return state; } };
Clean up the MySQL database connector.
<?php namespace Laravel\Database\Connectors; use PDO; class MySQL extends Connector { /** * Establish a PDO database connection for a given database configuration. * * @param array $config * @return PDO */ public function connect($config) { extract($config); // Format the initial MySQL PDO connection string. These options are required // for every MySQL connection that is established. The connection strings // have the following convention: "mysql:host=hostname;dbname=database" $dsn = sprintf('%s:host=%s;dbname=%s', $driver, $host, $database); // Check for any optional MySQL PDO options. These options are not required // to establish a PDO connection; however, may be needed in certain server // or hosting environments used by the developer. foreach (array('port', 'unix_socket') as $key => $value) { if (isset($config[$key])) { $dsn .= ";{$key}={$value}"; } } $connection = new PDO($dsn, $username, $password, $this->options($config)); if (isset($config['charset'])) { $connection->prepare("SET NAMES '{$charset}'")->execute(); } return $connection; } }
<?php namespace Laravel\Database\Connectors; use PDO; class MySQL extends Connector { /** * Establish a PDO database connection for a given database configuration. * * @param array $config * @return PDO */ public function connect($config) { $connection = new PDO($this->dsn($config), $config['username'], $config['password'], $this->options($config)); if (isset($config['charset'])) { $connection->prepare("SET NAMES '{$config['charset']}'")->execute(); } return $connection; } /** * Format the DSN connection string for a MySQL connection. * * @param array $config * @return string */ protected function dsn($config) { // Format the initial MySQL PDO connection string. These options are required // for every MySQL connection that is established. The connection strings // have the following convention: "mysql:host=hostname;dbname=database" $dsn = sprintf('%s:host=%s;dbname=%s', $config['driver'], $config['host'], $config['database']); // Check for any optional MySQL PDO options. These options are not required // to establish a PDO connection; however, may be needed in certain server // or hosting environments used by the developer. foreach (array('port', 'unix_socket') as $key => $value) { if (isset($config[$key])) $dsn .= ";{$key}={$value}"; } return $dsn; } }
Store current twist in a global variable
#!/usr/bin/env python import rospy from gazebo_msgs.msg import ModelStates from geometry_msgs.msg import Twist from constants import DELTA_T, STEPS from controller import create_controller from plotter import Plotter def get_pose(message): global current_pose, current_twist current_pose = message.pose[2] current_twist = message.twist[2] def compute_control_actions(): global i controller.compute_control_actions(current_pose, i) plotter.add_point(current_pose) twist = Twist() twist.linear.x = controller.v_n twist.angular.z = controller.w_n twist_publisher.publish(twist) i += 1 if __name__ == '__main__': rospy.init_node('control') current_pose = None current_twist = None subscriber = rospy.Subscriber('gazebo/model_states', ModelStates, get_pose) twist_publisher = rospy.Publisher('computed_control_actions', Twist, queue_size=1) while current_pose is None or current_twist is None: pass i = 0 plotter = Plotter() controller = create_controller() rate = rospy.Rate(int(1 / DELTA_T)) while not rospy.is_shutdown() and i < STEPS: compute_control_actions() rate.sleep() plotter.plot_results() rospy.spin()
#!/usr/bin/env python import rospy from gazebo_msgs.msg import ModelStates from geometry_msgs.msg import Twist from constants import DELTA_T, STEPS from controller import create_controller from plotter import Plotter def get_pose(message): global current_pose current_pose = message.pose[2] def compute_control_actions(): global i controller.compute_control_actions(current_pose, i) plotter.add_point(current_pose) twist = Twist() twist.linear.x = controller.v_n twist.angular.z = controller.w_n twist_publisher.publish(twist) i += 1 if __name__ == '__main__': rospy.init_node('control') current_pose = None subscriber = rospy.Subscriber('gazebo/model_states', ModelStates, get_pose) twist_publisher = rospy.Publisher('computed_control_actions', Twist, queue_size=1) while current_pose is None: pass i = 0 plotter = Plotter() controller = create_controller() rate = rospy.Rate(int(1 / DELTA_T)) while not rospy.is_shutdown() and i < STEPS: compute_control_actions() rate.sleep() plotter.plot_results() rospy.spin()
Implement interface & Adding Authorizable Trait.
<?php namespace App\Models; use App\Bases\Model; use Illuminate\Auth\Authenticatable; use Illuminate\Auth\Passwords\CanResetPassword; use Illuminate\Foundation\Auth\Access\Authorizable; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract; use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract; /** * Class User * @package App\Models */ class User extends Model implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract { /* ------------------------------------------------------------------------------------------------ | Traits | ------------------------------------------------------------------------------------------------ */ use Authenticatable, Authorizable, CanResetPassword; /* ------------------------------------------------------------------------------------------------ | Properties | ------------------------------------------------------------------------------------------------ */ /** * The database table used by the model. * * @var string */ protected $table = 'users'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = ['name', 'email', 'password']; /** * The attributes excluded from the model's JSON form. * * @var array */ protected $hidden = ['password', 'remember_token']; }
<?php namespace App\Models; use App\Bases\Model; use Illuminate\Auth\Authenticatable; use Illuminate\Auth\Passwords\CanResetPassword; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract; /** * Class User * @package App\Models */ class User extends Model implements AuthenticatableContract, CanResetPasswordContract { /* ------------------------------------------------------------------------------------------------ | Traits | ------------------------------------------------------------------------------------------------ */ use Authenticatable, CanResetPassword; /* ------------------------------------------------------------------------------------------------ | Properties | ------------------------------------------------------------------------------------------------ */ /** * The database table used by the model. * * @var string */ protected $table = 'users'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = ['name', 'email', 'password']; /** * The attributes excluded from the model's JSON form. * * @var array */ protected $hidden = ['password', 'remember_token']; }
Fix traversal to include pseudos
'use strict'; var uniq = require('lodash.uniq') var CssSelectorParser = require('css-selector-parser').CssSelectorParser var cssSelector = new CssSelectorParser() cssSelector.registerSelectorPseudos('not') cssSelector.registerNestingOperators('>', '+', '~'); cssSelector.registerAttrEqualityMods('^', '$', '*', '~'); module.exports = getCssSelectorClasses /** * Return all the classes in a CSS selector. * * @param {String} selector A CSS selector * @return {String[]} An array of every class present in the CSS selector */ function getCssSelectorClasses(selector) { var list = [] var ast = cssSelector.parse(selector) visitRules(ast, function(ruleSet) { if (ruleSet.classNames) { list = list.concat(ruleSet.classNames) } }) return uniq(list) } function visitRules(node, fn) { if (node.rule) { visitRules(node.rule, fn) } if (node.selectors) { node.selectors.forEach(function(node) { visitRules(node, fn) }) } if (node.pseudos) { node.pseudos.forEach(function(pseudo) { if (pseudo.valueType === 'selector') { visitRules(pseudo.value, fn) } }) } if (node.type === 'rule') { fn(node) } }
'use strict'; var uniq = require('lodash.uniq') var CssSelectorParser = require('css-selector-parser').CssSelectorParser var cssSelector = new CssSelectorParser() cssSelector.registerSelectorPseudos('not') cssSelector.registerNestingOperators('>', '+', '~'); cssSelector.registerAttrEqualityMods('^', '$', '*', '~'); module.exports = getCssSelectorClasses /** * Return all the classes in a CSS selector. * * @param {String} selector A CSS selector * @return {String[]} An array of every class present in the CSS selector */ function getCssSelectorClasses(selector) { var list = [] var ast = cssSelector.parse(selector) visitRules(ast, function(ruleSet) { if (ruleSet.classNames) { list = list.concat(ruleSet.classNames) } }) return uniq(list) } function visitRules(node, fn) { if (node.rule) { visitRules(node.rule, fn) } if (node.selectors) { node.selectors.forEach(function(node) { visitRules(node, fn) }) } if (node.type === 'rule') { fn(node) } }
Test str repr of exception
# Testing use of cpl_errs import pytest import rasterio from rasterio.errors import RasterioIOError def test_io_error(tmpdir): with pytest.raises(RasterioIOError) as exc_info: rasterio.open(str(tmpdir.join('foo.tif'))) msg = str(exc_info.value) assert msg.startswith("'{0}'".format(tmpdir.join('foo.tif'))) assert ("does not exist in the file system, and is not recognised as a " "supported dataset name.") in msg def test_io_error_env(tmpdir): with rasterio.drivers() as env: drivers_start = env.drivers() with pytest.raises(RasterioIOError): rasterio.open(str(tmpdir.join('foo.tif'))) assert env.drivers() == drivers_start def test_bogus_band_error(): with rasterio.open('tests/data/RGB.byte.tif') as src: assert src._has_band(4) is False
# Testing use of cpl_errs import pytest import rasterio from rasterio.errors import RasterioIOError def test_io_error(tmpdir): with pytest.raises(RasterioIOError) as exc_info: rasterio.open(str(tmpdir.join('foo.tif'))) msg = exc_info.value.message assert msg.startswith("'{0}'".format(tmpdir.join('foo.tif'))) assert ("does not exist in the file system, and is not recognised as a " "supported dataset name.") in msg def test_io_error_env(tmpdir): with rasterio.drivers() as env: drivers_start = env.drivers() with pytest.raises(RasterioIOError): rasterio.open(str(tmpdir.join('foo.tif'))) assert env.drivers() == drivers_start def test_bogus_band_error(): with rasterio.open('tests/data/RGB.byte.tif') as src: assert src._has_band(4) is False
Refactor test cases for ModelFactory
/* * Test cases for ModelFactory * @lastmodifiedBy ChengFuLin(chengfulin0806@gmail.com) * @lastmodifiedDate 2015-08-14 */ var factoryModel = require('../../lib/dujs/modelfactory'); var should = require('should'); describe('ModelFactory', function () { "use strict"; describe('public methods', function () { describe('create', function () { it('should support to create empty Model', function () { var model = factoryModel.create(); should.not.exist(model._testonly_._graph); should.exist(model._testonly_._relatedScopes); model._testonly_._relatedScopes.length.should.eql(0); should.exist(model._testonly_._dupairs); model._testonly_._dupairs.size.should.eql(0); }); }); }); });
/** * Created by ChengFuLin on 2015/6/10. */ var factoryAnalyzedCFG = require('../../lib/dujs').factoryAnalyzedCFG, should = require('should'); describe('ModelFactory', function () { "use strict"; describe('Factory Method', function () { it('should support to create empty Model', function () { var analyzedCFG = factoryAnalyzedCFG.create(); should.not.exist(analyzedCFG._testonly_._graph); should.exist(analyzedCFG._testonly_._relatedScopes); analyzedCFG._testonly_._relatedScopes.length.should.eql(0); should.exist(analyzedCFG._testonly_._dupairs); analyzedCFG._testonly_._dupairs.size.should.eql(0); }); }); });
fix: Make normalize urls to not remove trailing slash
const cheerio = require('cheerio') const normalizeUrl = require('normalize-url') const request = require('../request') const normalizeOptions = {removeTrailingSlash: false} module.exports = async function findFeed ({ url }) { const normalizedUrl = normalizeUrl(url, normalizeOptions) let response = null try { response = await request(normalizedUrl) } catch (error) { console.log(error) return [] } if (/application\/(rss|atom)/.test(response.contentType)) { return [{link: normalizedUrl}] } const dom = cheerio.load(response.text) const $linkTags = dom('link[rel="alternate"][type="application/rss+xml"]') .add('link[rel="alternate"][type="application/atom+xml"]') return $linkTags.map((index, $linkTag) => { const link = normalizeUrl($linkTag.attribs.href, normalizeOptions) return { link: /^\//.test(link) ? url + link : link } }).toArray() }
const cheerio = require('cheerio') const normalizeUrl = require('normalize-url') const request = require('../request') module.exports = async function findFeed ({ url }) { const normalizedUrl = normalizeUrl(url) let response = null try { response = await request(normalizedUrl) } catch (error) { console.log(error) return [] } if (/application\/(rss|atom)/.test(response.contentType)) { return [{link: normalizedUrl}] } const dom = cheerio.load(response.text) const $linkTags = dom('link[rel="alternate"][type="application/rss+xml"]') .add('link[rel="alternate"][type="application/atom+xml"]') return $linkTags.map((index, $linkTag) => { const link = normalizeUrl($linkTag.attribs.href) return { link: /^\//.test(link) ? url + link : link } }).toArray() }
Drop the package registration for L5
<?php namespace Jenssegers\Agent; use Illuminate\Support\ServiceProvider; class AgentServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { // } /** * Register the service provider. * * @return void */ public function register() { $this->app['agent'] = $this->app->share(function($app) { return new Agent; }); } }
<?php namespace Jenssegers\Agent; use Illuminate\Support\ServiceProvider; class AgentServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { $this->package('jenssegers/agent'); } /** * Register the service provider. * * @return void */ public function register() { $this->app['agent'] = $this->app->share(function($app) { return new Agent; }); } }
Add a polyfil for `process.arch` on node 0.4.x.
var ffi = require('node-ffi') , core = require('./core') , types = require('./types') , Pointer = ffi.Pointer , SIZE_MAP = ffi.Bindings.TYPE_SIZE_MAP , FUNC_MAP = ffi.TYPE_TO_POINTER_METHOD_MAP // We include a polyfil for `process.arch` on node 0.4.x if (!process.arch) { process.arch = ffi.Bindings.POINTER_SIZE == 8 ? 'x64' : 'ia32' } /** * Returns a new Pointer that points to this pointer. * Equivalent to the "address of" operator: * type* = &ptr */ Pointer.prototype.ref = function ref () { var ptr = new Pointer(SIZE_MAP.pointer) ptr.putPointer(this) ptr._type = '^' + this._type return ptr } /** * Dereferences the pointer. Includes wrapping up id instances when necessary. * Equivalent to the "value at" operator: * type = *ptr */ Pointer.prototype.deref = function deref () { var t = this._type if (t[0] !== '^') throw new Error('cannot dereference non-pointer') // since we're dereferencing, remove the leading ^ char t = t.substring(1) var ffiType = types.map(t) , val = this['get' + FUNC_MAP[ffiType] ]() val._type = t return core.wrapValue(val, t) }
var ffi = require('node-ffi') , core = require('./core') , types = require('./types') , Pointer = ffi.Pointer , SIZE_MAP = ffi.Bindings.TYPE_SIZE_MAP , FUNC_MAP = ffi.TYPE_TO_POINTER_METHOD_MAP /** * Returns a new Pointer that points to this pointer. * Equivalent to the "address of" operator: * type* = &ptr */ Pointer.prototype.ref = function ref () { var ptr = new Pointer(SIZE_MAP.pointer) ptr.putPointer(this) ptr._type = '^' + this._type return ptr } /** * Dereferences the pointer. Includes wrapping up id instances when necessary. * Equivalent to the "value at" operator: * type = *ptr */ Pointer.prototype.deref = function deref () { var t = this._type if (t[0] !== '^') throw new Error('cannot dereference non-pointer') // since we're dereferencing, remove the leading ^ char t = t.substring(1) var ffiType = types.map(t) , val = this['get' + FUNC_MAP[ffiType] ]() val._type = t return core.wrapValue(val, t) }
Add trove classifiers for language support
from distutils.core import setup setup( name = 'pycolors2', py_modules = ['colors',], version = '0.0.3', author = 'Chris Gilmer', author_email = 'chris.gilmer@gmail.com', maintainer = 'Chris Gilmer', maintainer_email = 'chris.gilmer@gmail.com', url = 'http://github.com/chrisgilmerproj/pycolors2', license = 'MIT license', description = """ Tool to color code python output """, long_description = open('README.markdown').read(), requires = [], classifiers = ( 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: System', 'Topic :: Terminals', 'Topic :: Utilities', ), )
from distutils.core import setup setup( name = 'pycolors2', py_modules = ['colors',], version = '0.0.3', author = 'Chris Gilmer', author_email = 'chris.gilmer@gmail.com', maintainer = 'Chris Gilmer', maintainer_email = 'chris.gilmer@gmail.com', url = 'http://github.com/chrisgilmerproj/pycolors2', license = 'MIT license', description = """ Tool to color code python output """, long_description = open('README.markdown').read(), requires = [], classifiers = ( 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: System', 'Topic :: Terminals', 'Topic :: Utilities', ), )
Use process.std{out,err}.write instead of console.{log,error}
'use strict'; const chokidar = require('chokidar'); const kexec = require('kexec'); const childProcess = require('child_process'); chokidar.watch('yarn.lock').on('change', () => { console.log('yarn.lock has been updated!'); console.log('reinstalling dependencies'); console.log(); const proc = childProcess.spawn('yarn', ['--verbose', '--non-interactive']); proc.stdout.on('data', data => { process.stdout.write(data); }); proc.stderr.on('data', data => { process.stderr.write(data); }); proc.on('close', code => { console.log(`yarn process exited with code ${code}`); kexec('yarn', ['start']); }); });
'use strict'; const chokidar = require('chokidar'); const kexec = require('kexec'); const childProcess = require('child_process'); chokidar.watch('yarn.lock').on('change', () => { console.log('yarn.lock has been updated!'); console.log('reinstalling dependencies'); console.log(); const proc = childProcess.spawn('yarn', ['--verbose', '--non-interactive']); proc.stdout.on('data', data => { console.log(data); }); proc.stderr.on('data', data => { console.error(data); }); proc.on('close', code => { console.log(`yarn process exited with code ${code}`); kexec('yarn', ['start']); }); });