text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Use env variable to API key during testing
module.exports = (grunt) => { // Grunt configuration grunt.initConfig({ ghostinspector: { options: { apiKey: process.env.GHOST_INSPECTOR_API_KEY }, test1: { suites: ['53cf58c0350c6c41029a11be'] }, test2: { tests: ['53cf58fc350c6c41029a11bf', '53cf59e0350c6c41029a11c0'] }, test3: { tests: ['53cf58fc350c6c41029a11bf'], options: { startUrl: 'https://www.google.com.br' } } } }) // Load grunt modules grunt.loadTasks('tasks') }
module.exports = (grunt) => { // Grunt configuration grunt.initConfig({ ghostinspector: { options: { apiKey: 'ff586dcaaa9b781163dbae48a230ea1947f894ff' }, test1: { suites: ['53cf58c0350c6c41029a11be'] }, test2: { tests: ['53cf58fc350c6c41029a11bf', '53cf59e0350c6c41029a11c0'] }, test3: { tests: ['53cf58fc350c6c41029a11bf'], options: { startUrl: 'https://www.google.com.br' } } } }) // Load grunt modules grunt.loadTasks('tasks') }
Put text for radio elements into label tags
<?php namespace vxPHP\Form\FormElement\FormElementWithOptions; use vxPHP\Form\FormElement\FormElementWithOptions\FormElementFragment; /** * a single option belonging to a group of <input type="option"> elements * sharing the same name * * @author Gregor Kofler * @version 0.4.1 2015-11-14 */ class RadioOptionElement extends FormElementFragment { /** * initialize option with value, label and parent RadioElement * * @param string $value * @param string $label * @param RadioElement $formElement */ public function __construct($value, $label, RadioElement $formElement = NULL) { parent::__construct($value, NULL, $label, $formElement); } /** * render element; when $force is FALSE a cached element rendering is re-used * * @param string $force */ public function render($force = FALSE) { if(empty($this->html) || $force) { $this->html = sprintf( '<input name="%s" type="radio" value="%s"%s><label>%s</label>', $this->parentElement->getName(), $this->getValue(), $this->selected ? " checked='checked'" : '', $this->getLabel() ); } return $this->html; } }
<?php namespace vxPHP\Form\FormElement\FormElementWithOptions; use vxPHP\Form\FormElement\FormElementWithOptions\FormElementFragment; /** * a single option belonging to a group of <input type="option"> elements * sharing the same name * * @author Gregor Kofler * @version 0.4.0 2015-01-24 */ class RadioOptionElement extends FormElementFragment { /** * initialize option with value, label and parent RadioElement * * @param string $value * @param string $label * @param RadioElement $formElement */ public function __construct($value, $label, RadioElement $formElement = NULL) { parent::__construct($value, NULL, $label, $formElement); } /** * render element; when $force is FALSE a cached element rendering is re-used * * @param string $force */ public function render($force = FALSE) { if(empty($this->html) || $force) { $checked = $this->selected ? " checked='checked'" : ''; $this->html = "<input name='{$this->parentElement->getName()}' type='radio' value='{$this->getValue()}'$checked>{$this->getLabel()}"; } return $this->html; } }
Add data to user dashboard
@extends('layouts.default') @section('content') <h1>User Dashboard</h1> <h3>Support Tickets</h3> <p> Open Tickets: {{ count($data['openTickets']) }} / In Progress Tickets: {{ count($data['inProgressTickets']) }} </p> <h3>Projects</h3> <p> Open Projects: {{ count($data['openProjects']) }} / In Progress Projects: {{ count($data['inProgressProjects']) }} </p> <h3>Invoices:</h3> <p> Open Invoices: {{ count($data['openInvoices']) }} / Total Open Amount: {{ $data['openInvoicesAmount'] }} </p> <p> Overdue Invoices: {{ count($data['overdueInvoices']) }} / Total Overdue Amount: {{ $data['overdueInvoicesAmount'] }} </p> @stop
@extends('layouts.default') @section('content') <h1>User Dashboard</h1> <h3>Support Tickets</h3> Open Tickets: {{ count($data['openTickets']) }} / In Progress Tickets: {{ count($data['inProgressTickets']) }} <br /> {{--<h3>Projects</h3>--}} {{--Open Projects: {{ count($data['openProjects']) }} /--}} {{--In Progress Projects: {{ count($data['inProgressProjects']) }} <br />--}} {{--<h3>Invoices:</h3>--}} {{--Open Invoices: {{ count($data['openInvoices']) }} /--}} {{--Total Open Amount: {{ $data['openInvoicesAmount'] }}<br />--}} {{--Overdue Invoices: {{ count($data['overdueInvoices']) }} /--}} {{--Total Overdue Amount: {{ $data['overdueInvoicesAmount'] }}<br />--}} @stop
Fix destroy DB hash if user logout
<?php /** * Created by PhpStorm. * User: jam * Date: 11.1.15 * Time: 20:34 */ namespace Trejjam\Authorization; use Nette, Trejjam; class User extends Nette\Security\User { /** * @var UserStorage */ protected $storage; protected $reloadChangedUser; public function __construct(UserStorage $storage, Nette\Security\IAuthenticator $authenticator = NULL, Nette\Security\IAuthorizator $authorizator = NULL) { parent::__construct($storage, $authenticator, $authorizator); $this->storage = $storage; } public function setParams($reloadChangedUser) { $this->reloadChangedUser = $reloadChangedUser; if ($reloadChangedUser) { $this->checkIdentityAction(); } } public function logout($clearIdentity = FALSE) { $this->storage->setAction('destroyed'); parent::logout($clearIdentity); } protected function checkIdentityAction() { if ($this->storage->isAuthenticated()) { $action = $this->storage->getAction(); if (is_null($action)) { parent::logout(); } switch ($action) { case 'reload': $this->login($this->getId(), NULL); break; case 'logout': $this->logout(); break; case 'destroyed': $this->logout(); break; } } } }
<?php /** * Created by PhpStorm. * User: jam * Date: 11.1.15 * Time: 20:34 */ namespace Trejjam\Authorization; use Nette, Trejjam; class User extends Nette\Security\User { /** * @var UserStorage */ protected $storage; protected $reloadChangedUser; public function __construct(UserStorage $storage, Nette\Security\IAuthenticator $authenticator = NULL, Nette\Security\IAuthorizator $authorizator = NULL) { parent::__construct($storage, $authenticator, $authorizator); $this->storage = $storage; } public function setParams($reloadChangedUser) { $this->reloadChangedUser = $reloadChangedUser; if ($reloadChangedUser) { $this->checkIdentityAction(); } } protected function checkIdentityAction() { if ($this->storage->isAuthenticated()) { $action = $this->storage->getAction(); if (is_null($action)) { $this->logout(); } switch ($action) { case 'reload': $this->storage->setAction('destroyed'); $this->login($this->getId(), NULL); break; case 'logout': $this->storage->setAction('destroyed'); $this->logout(); break; case 'destroyed': $this->logout(); break; } } } }
Add minimum versions to required dependencies. Add PEAR2_Console_CommandLine as a required dep. git-svn-id: 71b65f7ff3646a85e1ba76c778efde6466075005@299668 c90b9560-bf6c-de11-be94-00142212c4b1
<?php $package->dependencies['required']->php = '5.3.1RC1'; $package->dependencies['required']->package['pear2.php.net/PEAR2_Autoload']->min('0.2.0'); $package->dependencies['required']->package['pear2.php.net/PEAR2_Exception']->min('0.2.0'); $package->dependencies['required']->package['pear2.php.net/PEAR2_MultiErrors']->min('0.2.0'); $package->dependencies['required']->package['pear2.php.net/PEAR2_HTTP_Request']->min('0.2.0'); $package->dependencies['required']->package['pear2.php.net/PEAR2_Console_CommandLine']->min('0.1.0'); $compatible->dependencies['required']->php = '5.3.1RC1'; $compatible->dependencies['required']->package['pear2.php.net/PEAR2_Autoload']->min('0.2.0'); $compatible->dependencies['required']->package['pear2.php.net/PEAR2_Exception']->min('0.2.0'); $compatible->dependencies['required']->package['pear2.php.net/PEAR2_MultiErrors']->min('0.2.0'); $compatible->dependencies['required']->package['pear2.php.net/PEAR2_HTTP_Request']->min('0.2.0'); $compatible->dependencies['required']->package['pear2.php.net/PEAR2_Console_CommandLine']->min('0.1.0'); unset($package->files['tests/*']);
<?php $package->dependencies['required']->php = '5.3.1RC1'; $package->dependencies['required']->package['pear2.php.net/PEAR2_Autoload']->save(); $package->dependencies['required']->package['pear2.php.net/PEAR2_Exception']->save(); $package->dependencies['required']->package['pear2.php.net/PEAR2_MultiErrors']->save(); $package->dependencies['required']->package['pear2.php.net/PEAR2_HTTP_Request']->save(); $compatible->dependencies['required']->php = '5.3.1RC1'; $compatible->dependencies['required']->package['pear2.php.net/PEAR2_Autoload']->save(); $compatible->dependencies['required']->package['pear2.php.net/PEAR2_Exception']->save(); $compatible->dependencies['required']->package['pear2.php.net/PEAR2_MultiErrors']->save(); $compatible->dependencies['required']->package['pear2.php.net/PEAR2_HTTP_Request']->save(); unset($package->files['tests/*']);
Remove instagram temporarily until all instagram app permissions are resolved
/** index.js * @file: /config/index.js * @description: Handles passport authentication * @parameters: Object(app), Object(passport) * @exports: Passport authentication */ var ObjectID = require('mongodb').ObjectID var passport = require('passport') module.exports = function (app, resources) { var FacebookStrategy = require('./facebook')(resources) //var InstagramStrategy = require('./instagram')(resources) /* Facebook */ passport.use(FacebookStrategy) /* Instagram (for admin) */ //passport.use(InstagramStrategy) passport.serializeUser(function (req, user, done) { done(null, user.id) }) // TODO error handling etc passport.deserializeUser(function (req, id, done) { var usersdb = resources.collections.users usersdb.find({_id: new ObjectID(id)}, ['_id', 'name', 'fb_photo', 'vegosvar_photo', 'active_photo', 'info']).toArray(function (error, result) { done(error, result[0]) }) }) }
/** index.js * @file: /config/index.js * @description: Handles passport authentication * @parameters: Object(app), Object(passport) * @exports: Passport authentication */ var ObjectID = require('mongodb').ObjectID var passport = require('passport') module.exports = function (app, resources) { var FacebookStrategy = require('./facebook')(resources) var InstagramStrategy = require('./instagram')(resources) /* Facebook */ passport.use(FacebookStrategy) /* Instagram (for admin) */ passport.use(InstagramStrategy) passport.serializeUser(function (req, user, done) { done(null, user.id) }) // TODO error handling etc passport.deserializeUser(function (req, id, done) { var usersdb = resources.collections.users usersdb.find({_id: new ObjectID(id)}, ['_id', 'name', 'fb_photo', 'vegosvar_photo', 'active_photo', 'info']).toArray(function (error, result) { done(error, result[0]) }) }) }
Fix bug in dropdowns, where they didn’t disappear correctly
'use strict'; // Toogle asset images - zome in and out $(function() { var Snackbar = window.Snackbar; Snackbar.init(); var AssetPage = window.AssetPage; AssetPage.init(); // We only want zooming on asset's primary images. $('.asset .zoomable').click(function() { var $thisRow = $(this).closest('.image-row'); if ($thisRow.hasClass('col-md-6')) { $thisRow.removeClass('col-md-6').addClass('col-md-12'); $thisRow.next('div').addClass('col-md-offset-3') .removeClass('pull-right'); } else { $thisRow.removeClass('col-md-12').addClass('col-md-6'); $thisRow.next('div').removeClass('col-md-offset-3') .addClass('pull-right'); } }); var hideAllDropdowns = function() { $('.dropdown').removeClass('dropdown--active'); $('body').off('click', hideAllDropdowns); }; $('.dropdown__selected').on('click', function() { var $this = $(this); $('body').off('click', hideAllDropdowns); $('.dropdown').removeClass('dropdown--active'); var $dropdown = $this.closest('.dropdown'); if ($dropdown.hasClass('dropdown--active') === false) { $dropdown.addClass('dropdown--active'); setTimeout(function() { $('body').on('click', hideAllDropdowns); }, 1); } }); });
'use strict'; // Toogle asset images - zome in and out $(function() { var Snackbar = window.Snackbar; Snackbar.init(); var AssetPage = window.AssetPage; AssetPage.init(); // We only want zooming on asset's primary images. $('.asset .zoomable').click(function() { var $thisRow = $(this).closest('.image-row'); if ($thisRow.hasClass('col-md-6')) { $thisRow.removeClass('col-md-6').addClass('col-md-12'); $thisRow.next('div').addClass('col-md-offset-3') .removeClass('pull-right'); } else { $thisRow.removeClass('col-md-12').addClass('col-md-6'); $thisRow.next('div').removeClass('col-md-offset-3') .addClass('pull-right'); } }); var hideAllDropdowns = function() { $('.dropdown').removeClass('dropdown--active'); $('body').off('click', hideAllDropdowns); }; $('.dropdown__selected').on('click', function() { var $this = $(this); var $dropdown = $this.closest('.dropdown'); if ($dropdown.hasClass('dropdown--active') === false) { $dropdown.addClass('dropdown--active'); setTimeout(function() { $('body').off('click', hideAllDropdowns).on('click', hideAllDropdowns); }, 1); } }); });
Add tests for inspection reports and cover report templates.
from django.test import TestCase from model_mommy import mommy from ..models import ( PracticeType, Speciality, Qualification, PractitionerQualification, PractitionerContact, PractitionerFacility, Practitioner, ServiceCategory, Option, Service, FacilityService, ServiceOption, ServiceRating, FacilityApproval, InspectionReport, CoverTemplateReport ) class TestModels(TestCase): def test_save(self): models = [ PracticeType, Speciality, Qualification, PractitionerQualification, PractitionerContact, PractitionerFacility, Practitioner, ServiceCategory, Option, Service, FacilityService, ServiceOption, ServiceRating, FacilityApproval, InspectionReport, CoverTemplateReport ] for model_cls in models: obj = mommy.make(model_cls) self.assertNotEquals(0, len(model_cls.objects.all())) # a naive way to test unicodes for coverage purposes only try: self.assertIsInstance(obj.__unicode__(), str) except AssertionError: self.assertIsInstance(obj.__unicode__(), unicode)
from django.test import TestCase from model_mommy import mommy from ..models import ( PracticeType, Speciality, Qualification, PractitionerQualification, PractitionerContact, PractitionerFacility, Practitioner, ServiceCategory, Option, Service, FacilityService, ServiceOption, ServiceRating, FacilityApproval ) class TestModels(TestCase): def test_save(self): models = [ PracticeType, Speciality, Qualification, PractitionerQualification, PractitionerContact, PractitionerFacility, Practitioner, ServiceCategory, Option, Service, FacilityService, ServiceOption, ServiceRating, FacilityApproval ] for model_cls in models: obj = mommy.make(model_cls) self.assertNotEquals(0, len(model_cls.objects.all())) # a naive way to test unicodes for coverage purposes only try: self.assertIsInstance(obj.__unicode__(), str) except AssertionError: self.assertIsInstance(obj.__unicode__(), unicode)
Make the panel icon sensitive to keyboard and mouse
// -*- mode: js; js-indent-level: 4; indent-tabs-mode: nil -*- const Lang = imports.lang; const St = imports.gi.St; const Main = imports.ui.main; const PanelMenu = imports.ui.panelMenu; let _button = null; const FontResizerButton = new Lang.Class({ Name: 'FontResizerButton', Extends: PanelMenu.Button, _init: function() { this.parent(0.0, "Font Resizer Button"); this.setSensitive(true); // Panel menu icon this._icon = new St.Icon({ icon_name: 'zoom-in', style_class: 'system-status-icon' }); this.actor.add_child(this._icon); } }); function init() { } function enable() { _button = new FontResizerButton(); Main.panel.addToStatusArea('font-resizer-button', _button); } function disable() { _button.destroy(); }
// -*- mode: js; js-indent-level: 4; indent-tabs-mode: nil -*- const Lang = imports.lang; const St = imports.gi.St; const Main = imports.ui.main; const PanelMenu = imports.ui.panelMenu; let _button = null; const FontResizerButton = new Lang.Class({ Name: 'FontResizerButton', Extends: PanelMenu.Button, _init: function() { this.parent(0.0, "Font Resizer Button"); this._icon = new St.Icon({ icon_name: 'zoom-in', style_class: 'system-status-icon' }); this.actor.add_child(this._icon); } }); function init() { } function enable() { _button = new FontResizerButton(); Main.panel.addToStatusArea('font-resizer-button', _button); } function disable() { _button.destroy(); }
Implemented: Test for failure case in TransactionDatabaseFactoryLocator. For the fun of it ...
<?php namespace Qafoo\ChangeTrack\FISCalculator; class TransactionDatabaseFactoryLocatorTest extends \PHPUnit_Framework_TestCase { public function testMapTypes() { $factoryA = $this->getMock('Qafoo\\ChangeTrack\\FISCalculator\\TransactionDatabaseFactory'); $factoryB = $this->getMock('Qafoo\\ChangeTrack\\FISCalculator\\TransactionDatabaseFactory'); $locator = new TransactionDatabaseFactoryLocator( array( 'A' => $factoryA, 'B' => $factoryB, ) ); $this->assertSame($factoryB, $locator->getFactoryByType('B')); } public function testMapFailure() { $locator = new TransactionDatabaseFactoryLocator(array()); $this->setExpectedException('\\RuntimeException'); $locator->getFactoryByType('A'); } }
<?php namespace Qafoo\ChangeTrack\FISCalculator; class TransactionDatabaseFactoryLocatorTest extends \PHPUnit_Framework_TestCase { public function testMapTypes() { $factoryA = $this->getMock('Qafoo\\ChangeTrack\\FISCalculator\\TransactionDatabaseFactory'); $factoryB = $this->getMock('Qafoo\\ChangeTrack\\FISCalculator\\TransactionDatabaseFactory'); $locator = new TransactionDatabaseFactoryLocator( array( 'A' => $factoryA, 'B' => $factoryB, ) ); $this->assertSame($factoryB, $locator->getFactoryByType('B')); } }
Simplify test data for easier comparison.
# coding=utf-8 from cStringIO import StringIO from django.test import TestCase from geokey_dataimports.helpers.model_helpers import import_from_csv class ImportFromCSVTest(TestCase): """Tests to check that characters can be imported from CSV files. Notes that these tests are probably not possible or relevant under Python 3. """ def test_import_csv_basic_chars(self): """Basic ASCII characters can be imported.""" input_dict = {u'abc': u'123', u'cde': u'456', u'efg': u'789'} mock_csv = StringIO("abc,cde,efg\n123,456,789") features = [] import_from_csv(features=features, fields=[], file_obj=mock_csv) for k, v in input_dict.items(): self.assertEquals(v, features[0]['properties'][k]) def test_import_csv_non_ascii_chars(self): """Non-ASCII unicode characters can be imported.""" input_dict = {u'à': u'¡', u'£': u'Ç'} mock_csv = StringIO("à,£\n¡,Ç") features = [] import_from_csv(features=features, fields=[], file_obj=mock_csv) for k, v in input_dict.items(): self.assertEquals(v, features[0]['properties'][k])
# coding=utf-8 from io import BytesIO from django.test import TestCase from geokey_dataimports.helpers.model_helpers import import_from_csv class ImportFromCSVTest(TestCase): """Tests to check that characters can be imported from CSV files. Notes that these tests are probably not possible or relevant under Python 3. """ def test_import_csv_basic_chars(self): """Basic ASCII characters can be imported.""" mock_csv = BytesIO("abc,cde,efg\n123,456,789") features = [] import_from_csv(features=features, fields=[], file=mock_csv) print(features) self.assertEquals(features[0]['properties'], {'cde': '456', 'abc': '123', 'efg': '789'}) def test_import_csv_non_ascii_chars(self): """Non-ASCII unicode characters can be imported.""" mock_csv = BytesIO("abc,àde,e£g\n¡23,45Ç,Æ8é") features = [] import_from_csv(features=features, fields=[], file=mock_csv) print(features) self.assertEquals(features[0]['properties'], {'àde': '45Ç', 'abc': '¡23', 'e£g': 'Æ8é'})
Remove Volumes reducer from root level
import {JSONReducer as constraints} from './serviceForm/Constraints'; import {JSONReducer as container} from './serviceForm/Container'; import {JSONReducer as env} from './serviceForm/EnvironmentVariables'; import {JSONReducer as fetch} from './serviceForm/Artifacts'; import {JSONReducer as healthChecks} from './serviceForm/HealthChecks'; import {JSONReducer as labels} from './serviceForm/Labels'; import {JSONReducer as portDefinitions} from './serviceForm/PortDefinitions'; import {JSONReducer as residency} from './serviceForm/Residency'; import {JSONReducer as ipAddress} from './serviceForm/IpAddress'; import { simpleFloatReducer, simpleIntReducer, simpleReducer } from '../../../../../src/js/utils/ReducerUtil'; import ValidatorUtil from '../../../../../src/js/utils/ValidatorUtil'; module.exports = { id: simpleReducer('id'), instances: simpleIntReducer('instances'), container() { const newState = container.apply(this, arguments); if (ValidatorUtil.isEmpty(newState)) { return null; } return newState; }, cpus: simpleFloatReducer('cpus'), mem: simpleIntReducer('mem'), disk: simpleIntReducer('disk'), gpus: simpleIntReducer('gpus'), cmd: simpleReducer('cmd'), env, labels, healthChecks, constraints, fetch, portDefinitions, residency, ipAddress };
import {JSONReducer as constraints} from './serviceForm/Constraints'; import {JSONReducer as container} from './serviceForm/Container'; import {JSONReducer as env} from './serviceForm/EnvironmentVariables'; import {JSONReducer as fetch} from './serviceForm/Artifacts'; import {JSONReducer as healthChecks} from './serviceForm/HealthChecks'; import {JSONReducer as labels} from './serviceForm/Labels'; import {JSONReducer as portDefinitions} from './serviceForm/PortDefinitions'; import {JSONReducer as residency} from './serviceForm/Residency'; import {JSONReducer as volumes} from './serviceForm/Volumes'; import {JSONReducer as ipAddress} from './serviceForm/IpAddress'; import { simpleFloatReducer, simpleIntReducer, simpleReducer } from '../../../../../src/js/utils/ReducerUtil'; import ValidatorUtil from '../../../../../src/js/utils/ValidatorUtil'; module.exports = { id: simpleReducer('id'), instances: simpleIntReducer('instances'), container() { const newState = container.apply(this, arguments); if (ValidatorUtil.isEmpty(newState)) { return null; } return newState; }, cpus: simpleFloatReducer('cpus'), mem: simpleIntReducer('mem'), disk: simpleIntReducer('disk'), gpus: simpleIntReducer('gpus'), cmd: simpleReducer('cmd'), env, labels, healthChecks, constraints, fetch, portDefinitions, residency, volumes, ipAddress };
Update test for user API
package com.yahoo.vespa.hosted.controller.restapi.user; import com.yahoo.vespa.hosted.controller.restapi.ContainerControllerTester; import com.yahoo.vespa.hosted.controller.restapi.ControllerContainerTest; import org.junit.Test; /** * @author jonmv */ public class UserApiTest extends ControllerContainerTest { private static final String responseFiles = "src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/responses/"; @Test public void testUserApi() { ContainerControllerTester tester = new ContainerControllerTester(container, responseFiles); tester.assertResponse(authenticatedRequest("http://localhost:8080/user/v1/"), "{\"error-code\":\"NOT_FOUND\",\"message\":\"No 'GET' handler at '/user/v1/'\"}", 404); } }
package com.yahoo.vespa.hosted.controller.restapi.user; import com.yahoo.vespa.hosted.controller.restapi.ContainerControllerTester; import com.yahoo.vespa.hosted.controller.restapi.ControllerContainerTest; import org.junit.Test; /** * @author jonmv */ public class UserApiTest extends ControllerContainerTest { private static final String responseFiles = "src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/responses/"; @Test public void testUserApi() { ContainerControllerTester tester = new ContainerControllerTester(container, responseFiles); tester.assertResponse(authenticatedRequest("http://localhost:8080/user/v1/"), "{\n \"code\" : 403,\n \"message\" : \"Access denied\"\n" + "}", 403); } }
MINOR: Change to check for specific return codes.
<?php /* Copyright 2010 Olle Johansson. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. */ /** * VirusChecker scanner plugin to check for viruses using F-Prot scanner.. * @author Olle@Johansson.com */ class VCScanner_FProtScan implements VCScanner { /** * Runs clamscan on the given file. */ public function scan($filename) { $output = array(); $lastline = exec('fpscan -v 0 ' . escapeshellarg($filename), $output, $retval); $output = implode('', $output); #print "retval: $retval\nlastline: $lastline\noutput: $output\n"; if (($retval !== 1 && $retval !== 2 && $retval !== 3) || empty($lastline) || strpos($lastline, '[Found') === false) { return 0; } else { return 1; } } }
<?php /* Copyright 2010 Olle Johansson. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. */ /** * VirusChecker scanner plugin to check for viruses using F-Prot scanner.. * @author Olle@Johansson.com */ class VCScanner_FProtScan implements VCScanner { /** * Runs clamscan on the given file. */ public function scan($filename) { $output = array(); $lastline = exec('fpscan -v 0 ' . escapeshellarg($filename), $output, $retval); $output = implode('', $output); #print "retval: $retval\nlastline: $lastline\noutput: $output\n"; if ($retval === 0 || empty($lastline) || strpos($lastline, '[Found') === false) { return 0; } else { return 1; } } }
Increase the timewindow check of ART tests in cachecontroller
from core.cachecontroller.BaseURLTasksProvider import BaseURLTasksProvider import queue, threading from datetime import datetime, timedelta import logging class ArtPackages(BaseURLTasksProvider): BASIC_PRIORITY = 1 N_DAYS_WINDOW = 14 lock = threading.RLock() logger = logging.getLogger(__name__ + ' ArtPackages') def getpayload(self): self.logger.info("getpayload started") urlsQueue = queue.PriorityQueue(-1) urlsQueue.put((self.BASIC_PRIORITY, '/art/updatejoblist/?ntag_to=' + datetime.now().strftime('%Y-%m-%d') + '&ntag_from=' + (datetime.now() - timedelta(days=self.N_DAYS_WINDOW)).strftime('%Y-%m-%d'))) return urlsQueue
from core.cachecontroller.BaseURLTasksProvider import BaseURLTasksProvider import queue, threading from datetime import datetime, timedelta import logging class ArtPackages(BaseURLTasksProvider): BASIC_PRIORITY = 1 lock = threading.RLock() logger = logging.getLogger(__name__ + ' ArtPackages') def getpayload(self): self.logger.info("getpayload started") urlsQueue = queue.PriorityQueue(-1) urlsQueue.put((self.BASIC_PRIORITY, '/art/updatejoblist/?ntag_to=' + datetime.now().strftime('%Y-%m-%d') + '&ntag_from=' + (datetime.now() - timedelta(days=7)).strftime('%Y-%m-%d'))) return urlsQueue
Add a sample code for execution in terminal.
package main import ( "testing" "fmt" ) type squareTest struct { in, out int } var squareTests = []squareTest{ squareTest{1, 1}, squareTest{2, 4}, squareTest{5, 25}, squareTest{-2, 4}, } // テスト. func TestSqure( t *testing.T) { for _, st := range squareTests { v := Square(st.in) if v != st.out { t.Errorf("Square(%d) = %d, want %d.", st.in, v, st.out) } } } // $ go test // ベンチマーク. func BenchmarkSquare(b *testing.B) { for i := 0; i < b.N; i++ { Square(10) } } // $ go test -bench . // $ go test -bench . -benchmem # メモリ使用量やalloc回数も取得. // Example系. func ExampleSquare() { v := Square(11) fmt.Println(v) // Output: 121 } // $ go test
package main import ( "testing" "fmt" ) type squareTest struct { in, out int } var squareTests = []squareTest{ squareTest{1, 1}, squareTest{2, 4}, squareTest{5, 25}, squareTest{-2, 4}, } // テスト. func TestSqure( t *testing.T) { for _, st := range squareTests { v := Square(st.in) if v != st.out { t.Errorf("Square(%d) = %d, want %d.", st.in, v, st.out) } } } // ベンチマーク. func BenchmarkSquare(b *testing.B) { for i := 0; i < b.N; i++ { Square(10) } } // Example系. func ExampleSquare() { v := Square(11) fmt.Println(v) // Output: 121 }
Fix NPE on missing mods - still need to actually handle missing mods properly on client
package cpw.mods.fml.common.network; import java.util.List; import net.minecraft.src.NetHandler; import net.minecraft.src.NetworkManager; public class ModMissingPacket extends FMLPacket { public ModMissingPacket() { super(Type.MOD_MISSING); } @Override public byte[] generatePacket(Object... data) { // TODO List<String> missing = (List<String>) data[0]; List<String> badVersion = (List<String>) data[1]; return new byte[0]; } @Override public FMLPacket consumePacket(byte[] data) { // TODO return this; } @Override public void execute(NetworkManager network, FMLNetworkHandler handler, NetHandler netHandler, String userName) { // TODO } }
package cpw.mods.fml.common.network; import net.minecraft.src.NetHandler; import net.minecraft.src.NetworkManager; public class ModMissingPacket extends FMLPacket { public ModMissingPacket() { super(Type.MOD_MISSING); } @Override public byte[] generatePacket(Object... data) { // TODO Auto-generated method stub return null; } @Override public FMLPacket consumePacket(byte[] data) { // TODO Auto-generated method stub return null; } @Override public void execute(NetworkManager network, FMLNetworkHandler handler, NetHandler netHandler, String userName) { // TODO Auto-generated method stub } }
Remove dead code and add test for startbyte != 0 Some dead code was hanging around in dns-query-test; kill it. Also add a test to ensure that deserializing a DnsQuery from a ByteArray respects the given byte offset into this array.
'use strict'; var test = require('tape'); var dnsQuery = require('../../../app/scripts/dnssd/dns-query'); var byteArray = require('../../../app/scripts/dnssd/byte-array'); test('create a query', function(t) { var name = 'www.example.com'; var queryType = 3; var queryClass = 4; var result = new dnsQuery.DnsQuery(name, queryType, queryClass); t.equal(result.domainName, name); t.equal(result.queryType, queryType); t.equal(result.queryClass, queryClass); t.end(); }); test('serializes and deserializes correctly', function(t) { var domainName = '_semcache._http.local'; var queryType = 1; var queryClass = 2; var expected = new dnsQuery.DnsQuery(domainName, queryType, queryClass); var serialized = expected.serialize(); var actual = dnsQuery.createQueryFromByteArray(serialized); t.deepEqual(actual, expected); t.end(); }); test('createQueryFromByteArray succeeds when startByte != 0', function(t) { var expected = new dnsQuery.DnsQuery('mydomain.local', 1, 2); var serialized = expected.serialize(); var byteArr = new byteArray.ByteArray(); // Add 5 meaningless bytes. var offset = 5; for (var i = 0; i < offset; i++) { byteArr.push(i, 1); } byteArr.append(serialized); var actual = dnsQuery.createQueryFromByteArray(byteArr, offset); t.deepEqual(actual, expected); t.end(); });
'use strict'; var test = require('tape'); var dnsQuery = require('../../../app/scripts/dnssd/dns-query'); test('create a query', function(t) { var name = 'www.example.com'; var queryType = 3; var queryClass = 4; // // Corresponds to 155.33.17.68 // var ipAddress = 0x9b211144; var result = new dnsQuery.DnsQuery(name, queryType, queryClass); t.equal(result.domainName, name); t.equal(result.queryType, queryType); t.equal(result.queryClass, queryClass); t.end(); }); test('serializes and deserializes correctly', function(t) { var domainName = '_semcache._http.local'; var queryType = 1; var queryClass = 2; var expected = new dnsQuery.DnsQuery(domainName, queryType, queryClass); var serialized = expected.serialize(); var actual = dnsQuery.createQueryFromByteArray(serialized); t.deepEqual(actual, expected); t.end(); });
Remove redundant anonymous function parameter
<?php namespace SlotMachine; use Silex\Application; use Silex\ServiceProviderInterface; /** * This class is created specifically for the Silex micro-framework. * To use this Silex service provider, add the following: * * $app->register(new SlotMachine\SlotMachineServiceProvider(), array( * 'slotmachine.config' => 'path/to/slotmachine.config.php', * )); * * @package slotmachine * @author Adam Elsodaney <adam@archfizz.co.uk> */ class SlotMachineServiceProvider implements ServiceProviderInterface { /** * The SlotMachine\Page class is accessed as a service by Silex and the * configuration array is passed through as a service parameter. * * @todo Allow other parameters to be set by the service provider * @param Application $app * @return Page */ public function register(Application $app) { $app['slotmachine'] = $app->share(function () use ($app) { $config = $app['slotmachine.config'] ? $app['slotmachine.config'] : array(); return new Page($config); }); } /** * @param Application $app */ public function boot(Application $app) { } }
<?php namespace SlotMachine; use Silex\Application; use Silex\ServiceProviderInterface; /** * This class is created specifically for the Silex micro-framework. * To use this Silex service provider, add the following: * * $app->register(new SlotMachine\SlotMachineServiceProvider(), array( * 'slotmachine.config' => 'path/to/slotmachine.config.php', * )); * * @package slotmachine * @author Adam Elsodaney <adam@archfizz.co.uk> */ class SlotMachineServiceProvider implements ServiceProviderInterface { /** * The SlotMachine\Page class is accessed as a service by Silex and the * configuration array is passed through as a service parameter. * * @todo Allow other parameters to be set by the service provider * @param Application $app * @return Page */ public function register(Application $app) { $app['slotmachine'] = $app->share(function ($name) use ($app) { $defaultConfig = $app['slotmachine.config'] ? $app['slotmachine.config'] : array(); return new Page($defaultConfig); }); } /** * @param Application $app */ public function boot(Application $app) { } }
Simplify importer paths after dockerization
import os # --- importer input directory of DPAE and ETABLISSEMENT exports INPUT_SOURCE_FOLDER = '/srv/lbb/data' # --- job 1/8 & 2/8 : check_etablissements & extract_etablissements JENKINS_ETAB_PROPERTIES_FILENAME = os.path.join(os.environ["WORKSPACE"], "properties.jenkins") MINIMUM_OFFICES_TO_BE_EXTRACTED_PER_DEPARTEMENT = 10000 # --- job 3/8 & 4/8 : check_dpae & extract_dpae JENKINS_DPAE_PROPERTIES_FILENAME = os.path.join(os.environ["WORKSPACE"], "properties_dpae.jenkins") MAXIMUM_ZIPCODE_ERRORS = 100 MAXIMUM_INVALID_ROWS = 100 # --- job 5/8 : compute_scores SCORE_COEFFICIENT_OF_VARIATION_MAX = 2.0 RMSE_MAX = 1500 # On 2017.03.15 departement 52 reached RMSE=1141 HIGH_SCORE_COMPANIES_DIFF_MAX = 70 # --- job 6/8 : validate_scores MINIMUM_OFFICES_PER_DEPARTEMENT_FOR_DPAE = 500 MINIMUM_OFFICES_PER_DEPARTEMENT_FOR_ALTERNANCE = 0 # --- job 8/8 : populate_flags
import os # --- importer input directory of DPAE and ETABLISSEMENT exports INPUT_SOURCE_FOLDER = '/srv/lbb/data' # --- job 1/8 & 2/8 : check_etablissements & extract_etablissements JENKINS_ETAB_PROPERTIES_FILENAME = os.path.join(os.environ["WORKSPACE"], "properties.jenkins") MINIMUM_OFFICES_TO_BE_EXTRACTED_PER_DEPARTEMENT = 10000 # --- job 3/8 & 4/8 : check_dpae & extract_dpae JENKINS_DPAE_PROPERTIES_FILENAME = os.path.join(os.environ["WORKSPACE"], "properties_dpae.jenkins") MAXIMUM_ZIPCODE_ERRORS = 100 MAXIMUM_INVALID_ROWS = 100 # --- job 5/8 : compute_scores SCORE_COEFFICIENT_OF_VARIATION_MAX = 2.0 RMSE_MAX = 1500 # On 2017.03.15 departement 52 reached RMSE=1141 HIGH_SCORE_COMPANIES_DIFF_MAX = 70 # --- job 6/8 : validate_scores MINIMUM_OFFICES_PER_DEPARTEMENT_FOR_DPAE = 500 MINIMUM_OFFICES_PER_DEPARTEMENT_FOR_ALTERNANCE = 0 # --- job 8/8 : populate_flags BACKUP_OUTPUT_FOLDER = '/srv/lbb/backups/outputs' BACKUP_FOLDER = '/srv/lbb/backups'
Send back data to callback
var autotrace = require('autotrace'); var gm = require('gm').subClass({imageMagick: true}); var fs = require('fs'); module.exports.composeImage = function (drawing, photo, callback) { var rand = Math.floor(Math.random()*1000); var width = 1875; var height = 1275; gm(input) .resize(width, height).write('./temp/' + rand + '.png', function(err) { if (err) callback(err); gm().command('composite') .in('-gravity', 'center') .in('-background', 'none') .in('./temp/' + rand + '.png') .in(photo) .write('./postcards/' + rand + '.jpg', function(err) { if (err) callback(err); fs.readFile('./postcards/' + rand + '.jpg', function(err, data) { if (err) callback(err); callback(null, data); }); }); }); }
var autotrace = require('autotrace'); var gm = require('gm').subClass({imageMagick: true}); var fs = require('fs'); module.exports.composeImage = function (drawing, photo, callback) { var width = 1875; var height = 1275; gm(input) .resize(width, height).write('./temp1.png', function(err) { if (err) callback(err); gm().command('composite') .in('-gravity', 'center') .in('-background', 'none') .in('./temp1.png') .in(photo) .write('out2.jpg', function(err) { if (err) callback(err); }); }); } var input = './input.png'; var photo = 'matts.jpg';
Add a RunsWith for JUnit4
/* * Copyright (c) 2011 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.truth.delegation; import static com.google.common.truth.delegation.FooSubject.FOO; import static org.truth0.Truth.ASSERT; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * A test that's more or less intended to show how one uses an extended verb. * */ @RunWith(JUnit4.class) public class DelegationTest { @Test public void customTypeProposition() { ASSERT.about(FOO).that(new Foo(5)).matches(new Foo(2 + 3)); } @Test public void customTypePropositionWithFailure() { try { ASSERT.about(FOO).that(new Foo(5)).matches(new Foo(4)); ASSERT.fail("Should have thrown."); } catch (AssertionError e) { ASSERT.that(e.getMessage()).contains("Not true that"); ASSERT.that(e.getMessage()).contains("matches"); } } }
/* * Copyright (c) 2011 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.truth.delegation; import static com.google.common.truth.delegation.FooSubject.FOO; import static org.truth0.Truth.ASSERT; import org.junit.Test; /** * A test that's more or less intended to show how one uses an extended verb. * */ public class DelegationTest { @Test public void customTypeProposition() { ASSERT.about(FOO).that(new Foo(5)).matches(new Foo(2 + 3)); } @Test public void customTypePropositionWithFailure() { try { ASSERT.about(FOO).that(new Foo(5)).matches(new Foo(4)); ASSERT.fail("Should have thrown."); } catch (AssertionError e) { ASSERT.that(e.getMessage()).contains("Not true that"); ASSERT.that(e.getMessage()).contains("matches"); } } }
Switch date formatting for digital takeup number view
define([ 'extensions/views/single-stat' ], function (SingleStatView) { var DigitalTakeupNumberView = SingleStatView.extend({ changeOnSelected: true, getValue: function () { return this.formatPercentage(this.collection.at(0).get('fraction')); }, getLabel: function () { var numPeriods = this.collection.at(0).get('values').length; return [ 'last', numPeriods, this.pluralise(this.collection.query.get('period'), numPeriods) ].join(' '); }, getValueSelected: function (selection) { return this.formatPercentage(selection.selectedModel.get('fraction')); }, getLabelSelected: function (selection) { var model = selection.selectedModel; return this.formatPeriod(selection.selectedModel, 'month'); } }); return DigitalTakeupNumberView; });
define([ 'extensions/views/single-stat' ], function (SingleStatView) { var DigitalTakeupNumberView = SingleStatView.extend({ changeOnSelected: true, getValue: function () { return this.formatPercentage(this.collection.at(0).get('fraction')); }, getLabel: function () { var numWeeks = this.collection.at(0).get('values').length; return [ 'last', numWeeks, this.pluralise('week', numWeeks) ].join(' '); }, getValueSelected: function (selection) { return this.formatPercentage(selection.selectedModel.get('fraction')); }, getLabelSelected: function (selection) { var model = selection.selectedModel; var start = model.get('_start_at'); var end = moment(model.get('_end_at')).subtract(1, 'days'); var startLabel = start.format(start.month() === end.month() ? 'D' : 'D MMM'); var endLabel = end.format('D MMM YYYY'); return startLabel + ' to ' + endLabel; } }); return DigitalTakeupNumberView; });
Clean up the computation of my age by switching to Java 8 API's.
package uk.co.todddavies.website.closure; import com.google.common.collect.ImmutableMap; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.template.soy.jbcsrc.api.SoySauce; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.time.LocalDate; import java.time.Period; @Singleton final class MinimalistHomeServlet extends HttpServlet { private static final String TEMPLATE_NAME = "todddavies.website.minimalisthome"; private static final LocalDate BIRTH_DATE = LocalDate.of(1995, 06, 04); private final SoySauce soySauce; @Inject private MinimalistHomeServlet(SoySauce soySauce) { this.soySauce = soySauce; } @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { int yearsOld = Period.between(BIRTH_DATE, LocalDate.now()).getYears(); resp.getWriter().print( soySauce .renderTemplate(TEMPLATE_NAME) .setData(ImmutableMap.of("age", yearsOld)) .renderHtml().get().getContent()); } }
package uk.co.todddavies.website.closure; import com.google.common.collect.ImmutableMap; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.template.soy.jbcsrc.api.SoySauce; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Singleton final class MinimalistHomeServlet extends HttpServlet { private static final String TEMPLATE_NAME = "todddavies.website.minimalisthome"; private static final long BIRTH_MILLIS = 802224000000L; private static final long YEAR_MILLIS = 31556952000L; private static final ImmutableMap<String, String> HOME_DATA = ImmutableMap.of( "age", String.valueOf((System.currentTimeMillis() - BIRTH_MILLIS) / YEAR_MILLIS)); private final SoySauce soySauce; @Inject private MinimalistHomeServlet(SoySauce soySauce) { this.soySauce = soySauce; } @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.getWriter().print(soySauce.renderTemplate(TEMPLATE_NAME).setData(HOME_DATA).renderHtml().get().getContent()); } }
Add `status` column; some nullables; typos
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateRecruitingCampaignTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('recruiting_campaigns', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->enum('status', ['new', 'in_progress', 'completed']); $table->unsignedInteger('notification_template_id')->nullable(); $table->unsignedInteger('created_by'); $table->timestamps(); $table->foreign('created_by')->references('id')->on('users'); $table->foreign('notification_template_id')->references('id')->on('notification_templates'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('recruiting_campaigns'); } }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateRecruitingCampaignTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('recruiting_campaign', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->integer('notification_template_id'); $table->integer('created_by'); $table->timestamps(); $table->foreign('created_by')->references('id')->on('users'); $table->foreign('notification_template_id')->references('id')->on('notification_templates'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('recruiting_campaign'); } }
Remove an extra layer of pointer indirection in the trigram map Reduces memory usage and makes learning faster. benchmark old ns/op new ns/op delta BenchmarkLearn-4 23213 20426 -12.01% BenchmarkReply-4 15738 14160 -10.03% BenchmarkLearnParallel-4 22922 21090 -7.99% BenchmarkReplyParallel-4 4594 4566 -0.61% BenchmarkOverhead-4 8171 7955 -2.64% BenchmarkToksetAdd-4 2136 2127 -0.42% benchmark old MB/s new MB/s speedup BenchmarkLearn-4 7.97 9.06 1.14x benchmark old allocs new allocs delta BenchmarkLearn-4 61 40 -34.43% BenchmarkReply-4 8 8 +0.00% BenchmarkLearnParallel-4 61 36 -40.98% BenchmarkReplyParallel-4 9 9 +0.00% BenchmarkOverhead-4 1 1 +0.00% benchmark old bytes new bytes delta BenchmarkLearn-4 2758 2593 -5.98% BenchmarkReply-4 609 608 -0.16% BenchmarkLearnParallel-4 2760 2238 -18.91% BenchmarkReplyParallel-4 621 621 +0.00% BenchmarkOverhead-4 32 32 +0.00%
package fate type bigrams map[token]*tokset func (b bigrams) Observe(tok0 token, tok1 token) { ctx, ok := b[tok0] if !ok { ctx = &tokset{} b[tok0] = ctx } ctx.Add(tok1) } type fwdrev struct { fwd tokset rev tokset } type trigrams map[bigram]*fwdrev func (t trigrams) Observe(tok0, tok1, tok2, tok3 token) (had2 bool) { ctx := bigram{tok1, tok2} chain, had2 := t[ctx] if !had2 { chain = &fwdrev{} t[ctx] = chain } chain.fwd.Add(tok3) chain.rev.Add(tok0) return had2 } func (t trigrams) Fwd(ctx bigram) *tokset { return &(t[ctx].fwd) } func (t trigrams) Rev(ctx bigram) *tokset { return &(t[ctx].rev) }
package fate type bigrams map[token]*tokset func (b bigrams) Observe(tok0 token, tok1 token) { ctx, ok := b[tok0] if !ok { ctx = &tokset{} b[tok0] = ctx } ctx.Add(tok1) } type fwdrev struct { fwd *tokset rev *tokset } type trigrams map[bigram]*fwdrev func (t trigrams) Observe(tok0, tok1, tok2, tok3 token) (had2 bool) { ctx := bigram{tok1, tok2} chain, had2 := t[ctx] if !had2 { chain = &fwdrev{&tokset{}, &tokset{}} t[ctx] = chain } chain.fwd.Add(tok3) chain.rev.Add(tok0) return had2 } func (t trigrams) Fwd(ctx bigram) *tokset { return t[ctx].fwd } func (t trigrams) Rev(ctx bigram) *tokset { return t[ctx].rev }
Use 0 as the context key
// Package callinfo stores custom values into the Context // (related to the RPC source) package callinfo import ( "html/template" "golang.org/x/net/context" ) // CallInfo is the extra data stored in the Context type CallInfo interface { // RemoteAddr is the remote address information for this rpc call. RemoteAddr() string // Username is associated with this rpc call, if any. Username() string // Text is a text version of this connection, as specifically as possible. Text() string // HTML represents this rpc call connection in a web-friendly way. HTML() template.HTML } // internal type and value type key int var callInfoKey key = 0 // NewContext adds the provided CallInfo to the context func NewContext(ctx context.Context, ci CallInfo) context.Context { return context.WithValue(ctx, callInfoKey, ci) } // FromContext returns the CallInfo value stored in ctx, if any. func FromContext(ctx context.Context) (CallInfo, bool) { ci, ok := ctx.Value(callInfoKey).(CallInfo) return ci, ok }
// Package callinfo stores custom values into the Context // (related to the RPC source) package callinfo import ( "html/template" "golang.org/x/net/context" ) // CallInfo is the extra data stored in the Context type CallInfo interface { // RemoteAddr is the remote address information for this rpc call. RemoteAddr() string // Username is associated with this rpc call, if any. Username() string // Text is a text version of this connection, as specifically as possible. Text() string // HTML represents this rpc call connection in a web-friendly way. HTML() template.HTML } // internal type and value type key string var callInfoKey key = "vt.CallInfo" // NewContext adds the provided CallInfo to the context func NewContext(ctx context.Context, ci CallInfo) context.Context { return context.WithValue(ctx, callInfoKey, ci) } // FromContext returns the CallInfo value stored in ctx, if any. func FromContext(ctx context.Context) (CallInfo, bool) { ci, ok := ctx.Value(callInfoKey).(CallInfo) return ci, ok }
Add url namespaces and app_names to apiv1
""" Copyright [2009-2014] EMBL-European Bioinformatics Institute 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. """ from django.views.generic import TemplateView from django.conf.urls import patterns, url, include from rest_framework import routers from apiv1 import views router = routers.DefaultRouter() router.register(r'rna', views.RnaViewSet) router.register(r'accession', views.AccessionViewSet) urlpatterns = patterns('', url(r'^current/', include(router.urls)), url(r'^current/', include('rest_framework.urls', namespace='current_api', app_name='current_api')), url(r'^v1/', include(router.urls)), url(r'^v1/', include('rest_framework.urls', namespace='api_v1', app_name='api_v1')), )
""" Copyright [2009-2014] EMBL-European Bioinformatics Institute 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. """ from django.views.generic import TemplateView from django.conf.urls import patterns, url, include from rest_framework import routers from apiv1 import views router = routers.DefaultRouter() router.register(r'rna', views.RnaViewSet) router.register(r'accession', views.AccessionViewSet) urlpatterns = patterns('', url(r'^v1/', include(router.urls)), url(r'^v1/', include('rest_framework.urls', namespace='rest_framework_v1')), url(r'^current/', include(router.urls)), url(r'^current/', include('rest_framework.urls', namespace='rest_framework_v1')), )
Add constant for hints generated during offline matching
package won.matcher.service.common.event; import won.matcher.service.common.mailbox.PriorityAtomEventMailbox; /** * Indicates how this event was generated and associates that cause with a fixed * priority. Used in the {@link PriorityAtomEventMailbox}; lower priority values * means more important. */ public enum Cause { PUSHED(0), // we received a push about this Atom from a WoN node. React fast! MATCHED(3), // we found this Atom as a match to another one. React timely. SCHEDULED_FOR_REMATCH(5), // we decided it's time to re-match for this Atom. Should be handled before // events generated in crawling CRAWLED(10), // we found this Atom during crawling. Handle when we have nothing else to do MATCHED_OFFLINE(15), // this cause should only be used for HintEvents generated by offline matchers, // (not for AtomEvents). ; private int priority; private Cause(int prio) { this.priority = prio; } public int getPriority() { return priority; } public static int LOWEST_PRIORTY = Integer.MAX_VALUE; }
package won.matcher.service.common.event; import won.matcher.service.common.mailbox.PriorityAtomEventMailbox; /** * Indicates how this event was generated and associates that cause with a fixed * priority. Used in the {@link PriorityAtomEventMailbox}; lower priority values * means more important. */ public enum Cause { PUSHED(0), // we received a push about this Atom from a WoN node. React fast! MATCHED(3), // we found this Atom as a match to another one. React timely. SCHEDULED_FOR_REMATCH(5), // we decided it's time to re-match for this Atom. Should be handled before // events generated in crawling CRAWLED(10), // we found this Atom during crawling. Handle when we have nothing else to do ; private int priority; private Cause(int prio) { this.priority = prio; } public int getPriority() { return priority; } public static int LOWEST_PRIORTY = Integer.MAX_VALUE; }
Update rendering for new renderText method
function PlayState(playerPos) { "use strict"; var self = this; var charSprite = new Sprite("img/char_S0.png", function() { var charColl = new CollisionBody(charSprite.size); self.char = new Entity(playerPos, charColl, charSprite); }); } // Subclass the GameState class. PlayState.prototype = GameState.prototype; PlayState.prototype.update = function (deltaTime) { "use strict"; } PlayState.prototype.render = function (screen) { "use strict"; this.char.render(screen); screen.renderText("Hello World!", new Vector2(5, 20)); screen.renderText("This is OpenJGL Speaking.", new Vector2(5, 40), 16, "#55F", "oblique small-caps bold IndieFlower Lobster Serif"); } PlayState.prototype.willAppear = function () { "use strict"; Log.info("A Play State will soon appear.", this); } PlayState.prototype.willDisappear = function () { "use strict"; Log.info("A Play State will soon disappear.", this); } PlayState.prototype.toString = function () { "use strict"; return "PlayState"; }
function PlayState(playerPos) { "use strict"; var self = this; var charSprite = new Sprite("img/char_S0.png", function() { var charColl = new CollisionBody(charSprite.size); self.char = new Entity(playerPos, charColl, charSprite); }); } // Subclass the GameState class. PlayState.prototype = GameState.prototype; PlayState.prototype.update = function (deltaTime) { "use strict"; } PlayState.prototype.render = function (screen) { "use strict"; this.char.render(screen); screen.renderText("Hello World!", new Vector2(5, 20)); screen.renderText("This is OpenJGL Speaking.", new Vector2(5, 40), "#55F", "oblique small-caps bold 16px IndieFlower Lobster Serif"); } PlayState.prototype.willAppear = function () { "use strict"; Log.info("A Play State will soon appear.", this); } PlayState.prototype.willDisappear = function () { "use strict"; Log.info("A Play State will soon disappear.", this); } PlayState.prototype.toString = function () { "use strict"; return "PlayState"; }
Set listenHost to localhost if empty; fixes test on Windows
package caddytls import ( "crypto/tls" "fmt" "log" "net/http" "net/http/httputil" "net/url" "strings" ) const challengeBasePath = "/.well-known/acme-challenge" // HTTPChallengeHandler proxies challenge requests to ACME client if the // request path starts with challengeBasePath. It returns true if it // handled the request and no more needs to be done; it returns false // if this call was a no-op and the request still needs handling. func HTTPChallengeHandler(w http.ResponseWriter, r *http.Request, listenHost, altPort string) bool { if !strings.HasPrefix(r.URL.Path, challengeBasePath) { return false } if !namesObtaining.Has(r.Host) { return false } scheme := "http" if r.TLS != nil { scheme = "https" } if listenHost == "" { listenHost = "localhost" } upstream, err := url.Parse(fmt.Sprintf("%s://%s:%s", scheme, listenHost, altPort)) if err != nil { w.WriteHeader(http.StatusInternalServerError) log.Printf("[ERROR] ACME proxy handler: %v", err) return true } proxy := httputil.NewSingleHostReverseProxy(upstream) proxy.Transport = &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } proxy.ServeHTTP(w, r) return true }
package caddytls import ( "crypto/tls" "fmt" "log" "net/http" "net/http/httputil" "net/url" "strings" ) const challengeBasePath = "/.well-known/acme-challenge" // HTTPChallengeHandler proxies challenge requests to ACME client if the // request path starts with challengeBasePath. It returns true if it // handled the request and no more needs to be done; it returns false // if this call was a no-op and the request still needs handling. func HTTPChallengeHandler(w http.ResponseWriter, r *http.Request, listenHost, altPort string) bool { if !strings.HasPrefix(r.URL.Path, challengeBasePath) { return false } if !namesObtaining.Has(r.Host) { return false } scheme := "http" if r.TLS != nil { scheme = "https" } upstream, err := url.Parse(fmt.Sprintf("%s://%s:%s", scheme, listenHost, altPort)) if err != nil { w.WriteHeader(http.StatusInternalServerError) log.Printf("[ERROR] ACME proxy handler: %v", err) return true } proxy := httputil.NewSingleHostReverseProxy(upstream) proxy.Transport = &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } proxy.ServeHTTP(w, r) return true }
Remove deoptimized calls based on profiling
'use strict'; var PIXI = window.PIXI, Point = require('../data/point'), Rect = require('../data/rect'); function Frame(position, url, options) { this.pos = position; this.dir = options.direction || new Point(1, 1); this.offset = options.offset || new Point(0, 0); var base = PIXI.BaseTexture.fromImage(url, false, PIXI.scaleModes.NEAREST), slice = options.crop || new Rect(0, 0, base.width, base.height), tex = new PIXI.Texture(base, slice); this.sprite = new PIXI.Sprite(tex); this.render(); } Frame.prototype.render = function() { var gPos = this.sprite.position, gScale = this.sprite.scale; gPos.x = this.pos.x + this.offset.x; gPos.y = this.pos.y + this.offset.y; gScale.x = this.dir.x; gScale.y = this.dir.y; /* * Flipping will result in the sprite appearing to jump (flips on the 0, * rather than mid-sprite), so subtract the sprite's size from its position * if it's flipped. */ if(gScale.x < 0) gPos.x -= this.sprite.width; if(gScale.y < 0) gPos.y -= this.sprite.height; }; module.exports = Frame;
'use strict'; var PIXI = window.PIXI, Point = require('../data/point'), Rect = require('../data/rect'); function Frame(position, url, options) { this.pos = position; this.dir = options.direction || new Point(1, 1); this.offset = options.offset || new Point(0, 0); var base = PIXI.BaseTexture.fromImage(url, false, PIXI.scaleModes.NEAREST), slice = options.crop || new Rect(0, 0, base.width, base.height), tex = new PIXI.Texture(base, slice); this.sprite = new PIXI.Sprite(tex); this.render(); } Frame.prototype.render = function() { var gPos = this.sprite.position, gScale = this.sprite.scale; gPos.x = Math.round(this.pos.x + this.offset.x); gPos.y = Math.round(this.pos.y + this.offset.y); gScale.x = this.dir.x; gScale.y = this.dir.y; /* * Flipping will result in the sprite appearing to jump (flips on the 0, * rather than mid-sprite), so subtract the sprite's size from its position * if it's flipped. */ if(gScale.x < 0) gPos.x -= this.sprite.width; if(gScale.y < 0) gPos.y -= this.sprite.height; }; module.exports = Frame;
Update the PyPI version to 0.2.12
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except: return '' setup( name='todoist-python', version='0.2.12', packages=['todoist', 'todoist.managers'], author='Doist Team', author_email='info@todoist.com', license='BSD', description='todoist-python - The official Todoist Python API library', long_description = read('README.md'), install_requires=[ 'requests', ], # see here for complete list of classifiers # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=( 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', ), )
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except: return '' setup( name='todoist-python', version='0.2.11', packages=['todoist', 'todoist.managers'], author='Doist Team', author_email='info@todoist.com', license='BSD', description='todoist-python - The official Todoist Python API library', long_description = read('README.md'), install_requires=[ 'requests', ], # see here for complete list of classifiers # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=( 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', ), )
Add check for silent authentication For issue #225
/** * @title Slack Notification on User Signup * @overview Slack notification on user signup. * @gallery true * @category webhook * * This rule sends a message to a slack channel on every user signup. * */ function slackNotificationOnUserSignup(user, context, callback) { // short-circuit if the user signed up already or is using a refresh token if ( context.stats.loginsCount > 1 || context.protocol === 'oauth2-refresh-token' ) { return callback(null, user, context); } // check this isn't a checkSession call if (context.request.query.prompt !== 'none'){ // get your slack's hook url from: https://slack.com/services/10525858050 const SLACK_HOOK = configuration.SLACK_HOOK_URL; const slack = require('slack-notify')(SLACK_HOOK); const message = 'New User: ' + (user.name || user.email) + ' (' + user.email + ')'; const channel = '#some_channel'; slack.success({ text: message, channel: channel }); // don’t wait for the Slack API call to finish, return right away (the request will continue on the sandbox)` callback(null, user, context); } else { callback(null, user, context); } }
/** * @title Slack Notification on User Signup * @overview Slack notification on user signup. * @gallery true * @category webhook * * This rule sends a message to a slack channel on every user signup. * */ function slackNotificationOnUserSignup(user, context, callback) { // short-circuit if the user signed up already or is using a refresh token if ( context.stats.loginsCount > 1 || context.protocol === 'oauth2-refresh-token' ) { return callback(null, user, context); } // get your slack's hook url from: https://slack.com/services/10525858050 const SLACK_HOOK = configuration.SLACK_HOOK_URL; const slack = require('slack-notify')(SLACK_HOOK); const message = 'New User: ' + (user.name || user.email) + ' (' + user.email + ')'; const channel = '#some_channel'; slack.success({ text: message, channel: channel }); // don’t wait for the Slack API call to finish, return right away (the request will continue on the sandbox)` callback(null, user, context); }
Add doc for CORS component
const Config = use('config'); const CORSController = { path: 'cors', permissions: {}, OPTIONS : [ function () { // @path: .* // @summary: Handle CORS OPTIONS request this.response.headers['Access-Control-Allow-Methods'] = Config.cors.methods.toString(); this.response.headers['Access-Control-Allow-Headers'] = Config.cors.headers.toString(); this.response.headers['Access-Control-Allow-Credentials'] = Config.cors.credentials.toString(); this.response.headers['Access-Control-Allow-Max-Age'] = Config.cors.maxAge.toString(); } ] }; module.exports = CORSController;
const Config = use('config'); const CORSController = { path: 'cors', permissions: {}, OPTIONS : [ function () { // @path: .* this.response.headers['Access-Control-Allow-Methods'] = Config.cors.methods.toString(); this.response.headers['Access-Control-Allow-Headers'] = Config.cors.headers.toString(); this.response.headers['Access-Control-Allow-Credentials'] = Config.cors.credentials.toString(); this.response.headers['Access-Control-Allow-Max-Age'] = Config.cors.maxAge.toString(); } ] }; module.exports = CORSController;
Put script before first label
'use strict'; var assign = require('es5-ext/object/assign') , mixin = require('es5-ext/object/mixin') , d = require('d') , autoBind = require('d/auto-bind') , DOMRadio = require('dbjs-dom/input/enum').Radio , RadioBtnGroup = require('./_inline-button-group') , createOption = DOMRadio.prototype.createOption , reload = DOMRadio.prototype.reload , Radio; module.exports = Radio = function (document, type/*, options*/) { var options = Object(arguments[2]); this.controlsOptions = Object(options.controls); DOMRadio.call(this, document, type, options); }; Radio.prototype = Object.create(DOMRadio.prototype); mixin(Radio.prototype, RadioBtnGroup.prototype); Object.defineProperties(Radio.prototype, assign({ constructor: d(Radio), createOption: d(function (name) { var dom = createOption.call(this, name); this.listItems[name] = dom = dom.firstChild; return dom; }) }, autoBind({ reload: d(function () { reload.apply(this, arguments); this.dom.insertBefore(this.classHandlerScript, this.dom.firstChild); }) })));
'use strict'; var assign = require('es5-ext/object/assign') , mixin = require('es5-ext/object/mixin') , d = require('d') , autoBind = require('d/auto-bind') , DOMRadio = require('dbjs-dom/input/enum').Radio , RadioBtnGroup = require('./_inline-button-group') , createOption = DOMRadio.prototype.createOption , reload = DOMRadio.prototype.reload , Radio; module.exports = Radio = function (document, type/*, options*/) { var options = Object(arguments[2]); this.controlsOptions = Object(options.controls); DOMRadio.call(this, document, type, options); }; Radio.prototype = Object.create(DOMRadio.prototype); mixin(Radio.prototype, RadioBtnGroup.prototype); Object.defineProperties(Radio.prototype, assign({ constructor: d(Radio), createOption: d(function (name) { var dom = createOption.call(this, name); this.listItems[name] = dom = dom.firstChild; return dom; }) }, autoBind({ reload: d(function () { reload.apply(this, arguments); this.dom.appendChild(this.classHandlerScript); }) })));
Use root user to connect
#!/usr/bin/env python # # igcollect - Mysql Status # # Copyright (c) 2016, InnoGames GmbH # import time import socket import MySQLdb hostname = socket.gethostname().replace(".", "_") now = str(int(time.time())) db = MySQLdb.connect(user = 'root', host = 'localhost', read_default_file='/etc/mysql/my.cnf') cur = db.cursor() # Check for global status cur.execute("show global status") for row in cur.fetchall(): if row[1].isdigit(): print "servers.{0}.software.mysql.status.{1} {2} {3}".format(hostname, row[0], row[1], now) cur.execute("show variables") for row in cur.fetchall(): if row[1].isdigit(): print "servers.{0}.software.mysql.variables.{1} {2} {3}".format(hostname, row[0], row[1], now)
#!/usr/bin/env python # # igcollect - Mysql Status # # Copyright (c) 2016, InnoGames GmbH # import time import socket import MySQLdb hostname = socket.gethostname().replace(".", "_") now = str(int(time.time())) db = MySQLdb.connect(host = 'localhost', read_default_file='/etc/mysql/my.cnf') cur = db.cursor() # Check for global status cur.execute("show global status") for row in cur.fetchall(): if row[1].isdigit(): print "servers.{0}.software.mysql.status.{1} {2} {3}".format(hostname, row[0], row[1], now) cur.execute("show variables") for row in cur.fetchall(): if row[1].isdigit(): print "servers.{0}.software.mysql.variables.{1} {2} {3}".format(hostname, row[0], row[1], now)
Fix issue sending photo command with video
// This module is responsible for capturing videos const config = require('config'); const PiCamera = require('pi-camera'); const myCamera = new PiCamera({ mode: 'video', output: process.argv[2], width: config.get('camera.videoWidth'), height: config.get('camera.videoHeight'), timeout: config.get('camera.videoTimeout'), nopreview: true, }); process.on('message', (message) => { if (message.cmd === 'set') { myCamera.config = Object.assign(myCamera.config, message.set); } else if (message.cmd === 'capture') { myCamera.record() .then((result) => process.send({ response: 'success', result, error: null, })) .catch((error) => process.send({ response: 'failure', error, })); } });
// This module is responsible for capturing videos const config = require('config'); const PiCamera = require('pi-camera'); const myCamera = new PiCamera({ mode: 'video', output: process.argv[2], width: config.get('camera.videoWidth'), height: config.get('camera.videoHeight'), timeout: config.get('camera.videoTimeout'), timestamp: true, nopreview: true, }); process.on('message', (message) => { if (message.cmd === 'set') { myCamera.config = Object.assign(myCamera.config, message.set); } else if (message.cmd === 'capture') { myCamera.record() .then((result) => process.send({ response: 'success', result, error: null, })) .catch((error) => process.send({ response: 'failure', error, })); } });
Add preventDefault call to final setup page
<?php ?> <form action="#" role="form" id="finishSettingsForm"> <h3 class="form-title">Setup Complete!</h3> <span id="helpBlock" class="help-block help-message"></span> <p> Looks like you're almost done! As a final step, run the following commands from the terminal: <br/><code>sudo service airtime-playout start</code> <br/><code>sudo service airtime-liquidsoap start</code> <br/><code>sudo service airtime-media-monitor start</code> </p> <p> Click "Done!" to bring up the Airtime configuration checklist; if your configuration is all green, you're ready to get started with your personal Airtime station! </p> <p> If you need to re-run the web installer, just remove <code>/etc/airtime/airtime.conf</code>. </p> <div> <input type="submit" formtarget="finishSettingsForm" class="btn btn-primary btn-next" value="Done!"/> </div> </form> <script> $("#finishSettingsForm").submit(function(e) { e.preventDefault(); window.location.assign("/?config"); }); </script>
<?php ?> <form action="#" role="form" id="finishSettingsForm"> <h3 class="form-title">Setup Complete!</h3> <span id="helpBlock" class="help-block help-message"></span> <p> Looks like you're almost done! As a final step, run the following commands from the terminal: <br/><code>sudo service airtime-playout start</code> <br/><code>sudo service airtime-liquidsoap start</code> <br/><code>sudo service airtime-media-monitor start</code> </p> <p> Click "Done!" to bring up the Airtime configuration checklist; if your configuration is all green, you're ready to get started with your personal Airtime station! </p> <p> If you need to re-run the web installer, just remove <code>/etc/airtime/airtime.conf</code>. </p> <div> <input type="submit" formtarget="finishSettingsForm" class="btn btn-primary btn-next" value="Done!"/> </div> </form> <script> $("#finishSettingsForm").submit(function(e) { window.location.assign("/?config"); }); </script>
Include defaultValue in getPageStartTime function. Change-Id: Ib25db9f76263ffcb907f1c04edb90e1c2c65e4cf
const {hasAdRequestPath, isImplTag} = require('./resource-classification'); const {URL} = require('url'); /** * Returns end time of tag load (s) relative to system boot. * @param {LH.Artifacts.NetworkRequest[]} networkRecords * @return {number} */ function getTagEndTime(networkRecords) { const tagRecord = networkRecords.find( (record) => isImplTag(new URL(record.url))); return tagRecord ? tagRecord.endTime : -1; } /** * Returns start time of first ad request (s) relative to system boot. * @param {LH.Artifacts.NetworkRequest[]} networkRecords * @return {number} */ function getAdStartTime(networkRecords) { const firstAdRecord = networkRecords.find( (record) => hasAdRequestPath(new URL(record.url))); return firstAdRecord ? firstAdRecord.startTime : -1; } /** * Returns start time of page load (s) relative to system boot. * @param {LH.Artifacts.NetworkRequest[]} networkRecords * @param {number=} defaultValue * @return {number} */ function getPageStartTime(networkRecords, defaultValue = -1) { const fistSuccessRecord = networkRecords.find( (record) => record.statusCode == 200); return fistSuccessRecord ? fistSuccessRecord.startTime : defaultValue; } module.exports = { getTagEndTime, getAdStartTime, getPageStartTime, };
const {hasAdRequestPath, isImplTag} = require('./resource-classification'); const {URL} = require('url'); /** * Returns end time of tag load (s) relative to system boot. * @param {LH.Artifacts.NetworkRequest[]} networkRecords * @return {number} */ function getTagEndTime(networkRecords) { const tagRecord = networkRecords.find( (record) => isImplTag(new URL(record.url))); return tagRecord ? tagRecord.endTime : -1; } /** * Returns start time of first ad request (s) relative to system boot. * @param {LH.Artifacts.NetworkRequest[]} networkRecords * @return {number} */ function getAdStartTime(networkRecords) { const firstAdRecord = networkRecords.find( (record) => hasAdRequestPath(new URL(record.url))); return firstAdRecord ? firstAdRecord.startTime : -1; } /** * Returns start time of page load (s) relative to system boot. * @param {LH.Artifacts.NetworkRequest[]} networkRecords * @return {number} */ function getPageStartTime(networkRecords) { const fistSuccessRecord = networkRecords.find( (record) => record.statusCode == 200); return fistSuccessRecord ? fistSuccessRecord.startTime : -1; } module.exports = { getTagEndTime, getAdStartTime, getPageStartTime, };
Fix typo in error message variable
from __future__ import absolute_import from __future__ import unicode_literals from .webhooks import WebHook from werkzeug.exceptions import BadRequest, NotImplemented EVENTS = { 'Push Hook': 'push', 'Tag Push Hook': 'tag_push', 'Issue Hook': 'issue', 'Note Hook': 'note', 'Merge Request Hook': 'merge_request' } class GitlabWebHook(WebHook): def event(self, request): gitlab_header = request.headers.get('X-Gitlab-Event', None) if not gitlab_header: raise BadRequest('Gitlab requests must provide a X-Gitlab-Event header') event = EVENTS.get(gitlab_header, None) if not event: raise NotImplemented('Header not understood %s' % gitlab_header) if event == 'note': if 'commit' in request.json: event = 'commit_comment' elif 'merge_request' in request.json: event = 'merge_request_comment' elif 'issue' in request.json: event = 'issue_comment' elif 'snippet' in request.json: event = 'snippet_comment' return event
from __future__ import absolute_import from __future__ import unicode_literals from .webhooks import WebHook from werkzeug.exceptions import BadRequest, NotImplemented EVENTS = { 'Push Hook': 'push', 'Tag Push Hook': 'tag_push', 'Issue Hook': 'issue', 'Note Hook': 'note', 'Merge Request Hook': 'merge_request' } class GitlabWebHook(WebHook): def event(self, request): gitlab_header = request.headers.get('X-Gitlab-Event', None) if not gitlab_header: raise BadRequest('Gitlab requests must provide a X-Gitlab-Event header') event = EVENTS.get(gitlab_header, None) if not event: raise NotImplemented('Header not understood %s' % githab_header) if event == 'note': if 'commit' in request.json: event = 'commit_comment' elif 'merge_request' in request.json: event = 'merge_request_comment' elif 'issue' in request.json: event = 'issue_comment' elif 'snippet' in request.json: event = 'snippet_comment' return event
Fix outdated cache after saving tracking codes
<?php defined('C5_EXECUTE') or die("Access Denied."); class Concrete5_Controller_Dashboard_System_Seo_TrackingCodes extends DashboardBaseController { public function view() { $this->set('tracking_code', Config::get('SITE_TRACKING_CODE')); $tracking_code_position = Config::get('SITE_TRACKING_CODE_POSITION'); if (!$tracking_code_position) { $tracking_code_position = 'bottom'; } $this->set('tracking_code_position', $tracking_code_position); if ($this->isPost()) { if ($this->token->validate('update_tracking_code')) { Config::save('SITE_TRACKING_CODE', $this->post('tracking_code')); Config::save('SITE_TRACKING_CODE_POSITION', $this->post('tracking_code_position')); Cache::flush(); $this->redirect('/dashboard/system/seo/tracking_codes', 'saved'); } else { $this->error->add($this->token->getErrorMessage()); } } } public function saved() { $this->set('message', implode(PHP_EOL, array( t('Tracking code settings updated successfully.'), t('Cached files removed.') ))); $this->view(); } }
<?php defined('C5_EXECUTE') or die("Access Denied."); class Concrete5_Controller_Dashboard_System_Seo_TrackingCodes extends DashboardBaseController { public function view() { $this->set('tracking_code', Config::get('SITE_TRACKING_CODE')); $tracking_code_position = Config::get('SITE_TRACKING_CODE_POSITION'); if (!$tracking_code_position) { $tracking_code_position = 'bottom'; } $this->set('tracking_code_position', $tracking_code_position); if ($this->isPost()) { if ($this->token->validate('update_tracking_code')) { Config::save('SITE_TRACKING_CODE', $this->post('tracking_code')); Config::save('SITE_TRACKING_CODE_POSITION', $this->post('tracking_code_position')); $this->redirect('/dashboard/system/seo/tracking_codes', 'saved'); } else { $this->error->add($this->token->getErrorMessage()); } } } public function saved() { $this->set('message', t('Tracking code settings updated successfully.')); $this->view(); } }
Use all-caps env var name Makes HTTP_PROXY consistent with PORT or TRAVIS_BUILD_NUMBER elsewhere in the application. Are parsed case insensitive by Node anyway.
'use strict' var proxy = { proxyType: 'autodetect' } if (process.env.HTTP_PROXY !== undefined && process.env.HTTP_PROXY !== null) { proxy = { proxyType: 'manual', httpProxy: process.env.HTTP_PROXY } } exports.config = { directConnect: true, allScriptsTimeout: 80000, specs: [ 'test/e2e/*.js' ], capabilities: { browserName: 'chrome', proxy: proxy }, baseUrl: 'http://localhost:3000', framework: 'jasmine2', jasmineNodeOpts: { showColors: true, defaultTimeoutInterval: 90000 }, onPrepare: function () { var jasmineReporters = require('jasmine-reporters') jasmine.getEnv().addReporter(new jasmineReporters.JUnitXmlReporter({ consolidateAll: true, savePath: 'build/reports/e2e_results' })) // Get cookie consent popup out of the way browser.get('/#') browser.manage().addCookie({ name: 'cookieconsent_status', value: 'dismiss' }) } } if (process.env.TRAVIS_BUILD_NUMBER) { exports.config.capabilities.chromeOptions = { args: ['--headless', '--disable-gpu', '--window-size=800,600'] } }
'use strict' var proxy = { proxyType: 'autodetect' } if (process.env.http_proxy !== undefined && process.env.http_proxy !== null) { proxy = { proxyType: 'manual', httpProxy: process.env.http_proxy } } exports.config = { directConnect: true, allScriptsTimeout: 80000, specs: [ 'test/e2e/*.js' ], capabilities: { browserName: 'chrome', proxy: proxy }, baseUrl: 'http://localhost:3000', framework: 'jasmine2', jasmineNodeOpts: { showColors: true, defaultTimeoutInterval: 90000 }, onPrepare: function () { var jasmineReporters = require('jasmine-reporters') jasmine.getEnv().addReporter(new jasmineReporters.JUnitXmlReporter({ consolidateAll: true, savePath: 'build/reports/e2e_results' })) // Get cookie consent popup out of the way browser.get('/#') browser.manage().addCookie({ name: 'cookieconsent_status', value: 'dismiss' }) } } if (process.env.TRAVIS_BUILD_NUMBER) { exports.config.capabilities.chromeOptions = { args: ['--headless', '--disable-gpu', '--window-size=800,600'] } }
Add special task id to test source
# -*- coding: utf-8 -*- import json import app WORK_BEGIN_TASK = 72824136 WORK_END_TASK = 73847457 def test(): body = { "event_name": "item:completed", "event_data": { "id": WORK_END_TASK, "content": u'TINA テスト', "labels": [652234], "project_id": 156051149 } } with open('../.tinaconfig') as f: config = json.load(f) app.exec_todoist(config, body) def test_reminder_fired(): body = { "event_name": "reminder:fired", "event_data": { "item_id": 85474444, "id": 33482384 } } with open('../.tinaconfig') as f: config = json.load(f) app.exec_todoist(config, body) test()
# -*- coding: utf-8 -*- import json import app WORK_END_TASK = 73847457 def test(): body = { "event_name": "item:completed", "event_data": { "id": 85570464, "content": u'TINA テスト', "labels": [652234], "project_id": 156051149 } } with open('../.tinaconfig') as f: config = json.load(f) app.exec_todoist(config, body) def test_reminder_fired(): body = { "event_name": "reminder:fired", "event_data": { "item_id": 85474444, "id": 33482384 } } with open('../.tinaconfig') as f: config = json.load(f) app.exec_todoist(config, body) test()
Return array of retrieved values to support multiple tokens per user
<?php namespace NotificationChannels\ExpoPushNotifications\Repositories; use ExponentPhpSDK\ExpoRepository; use NotificationChannels\ExpoPushNotifications\Models\Interest; class ExpoDatabaseDriver implements ExpoRepository { /** * Stores an Expo token with a given identifier * * @param $key * @param $value * * @return bool */ public function store($key, $value): bool { $interest = Interest::firstOrCreate([ 'key' => $key, 'value' => $value ]); return $interest instanceof Interest; } /** * Retrieves an Expo token with a given identifier * * @param string $key * * @return string|null */ public function retrieve(string $key) { return Interest::where('key', $key)->pluck('value')->toArray(); } /** * Removes an Expo token with a given identifier * * @param string $key * * @return bool */ public function forget(string $key): bool { return Interest::where('key', $key)->delete(); } }
<?php namespace NotificationChannels\ExpoPushNotifications\Repositories; use ExponentPhpSDK\ExpoRepository; use NotificationChannels\ExpoPushNotifications\Models\Interest; class ExpoDatabaseDriver implements ExpoRepository { /** * Stores an Expo token with a given identifier * * @param $key * @param $value * * @return bool */ public function store($key, $value): bool { $interest = Interest::firstOrCreate([ 'key' => $key, 'value' => $value ]); return $interest instanceof Interest; } /** * Retrieves an Expo token with a given identifier * * @param string $key * * @return string|null */ public function retrieve(string $key) { $interest = Interest::where('key', $key)->first(); if($interest instanceof Interest) { return (string) $interest->value; } return null; } /** * Removes an Expo token with a given identifier * * @param string $key * * @return bool */ public function forget(string $key): bool { return Interest::where('key', $key)->delete(); } }
Remove rename since gulp.dest will copy files on its own
'use-strict'; ////////////////////////////// // Requires ////////////////////////////// var gulp = require('gulp'); var svgSprite = require('gulp-svg-sprite'); // SVG Config var config = { mode: { symbol: { // symbol mode to build the SVG dest: 'sprite', // destination foldeer sprite: 'sprite.svg', //sprite name example: true // Build sample page } } }; gulp.task('sprite-page', function() { return gulp.src('svg/**/*.svg') .pipe(svgSprite(config)) .pipe(gulp.dest('.')); }); gulp.task('sprite-shortcut', function() { return gulp.src('sprite/sprite.svg') .pipe(gulp.dest('.')); }); gulp.task('default', ['sprite-page', 'sprite-shortcut']);
'use-strict'; ////////////////////////////// // Requires ////////////////////////////// var gulp = require('gulp'); var svgSprite = require('gulp-svg-sprite'); var rename = require('gulp-rename'); // SVG Config var config = { mode: { symbol: { // symbol mode to build the SVG dest: 'sprite', // destination foldeer sprite: 'sprite.svg', //sprite name example: true // Build sample page } } }; gulp.task('sprite-page', function() { return gulp.src('svg/**/*.svg') .pipe(svgSprite(config)) .pipe(gulp.dest('.')); }); gulp.task('sprite-shortcut', function() { return gulp.src('sprite/sprite.svg') .pipe(rename('sprite.svg')) .pipe(gulp.dest('.')); }); gulp.task('default', ['sprite-page', 'sprite-shortcut']);
Add more details about issue being fixed
#!/usr/bin/env python # -*- coding: utf-8 -*- # Fix some iso3 IDs that are wrong in ne_10m_admin_0_countries_lakes.shp, # ne_10m_admin_1_states_provinces_lakes.shp seems ok though. # # Not all the SU_A3 IDs match those used in the ISO_A3 standard. This script replaces non-matching IDs # with corresponding ISO_A3 values. For more details seeissue #12 https://github.com/yaph/d3-geomap/issues/12. import json import os file_dest = os.path.abspath( os.path.join(os.path.dirname(__file__), '../data/countries.json')) replacements = { 'KOS': 'XKX', # Kosovo 'PN1': 'PNG', # Papua New Guniea 'PR1': 'PRT', # Portugal 'SDS': 'SSD', # S. Sudan 'SAH': 'ESH', # W. Sahara } with open(file_dest, 'r') as f: topo = json.load(f) countries = topo['objects']['units']['geometries'] for country in countries: cid = country['properties']['iso3'] country['properties']['iso3'] = replacements.get(cid, cid) with open(file_dest, 'w') as f: json.dump(topo, f, separators=(',', ':')) # save bytes to keep file small
#!/usr/bin/env python # -*- coding: utf-8 -*- # Fix some iso3 IDs that are wrong in ne_10m_admin_0_countries_lakes.shp, # ne_10m_admin_1_states_provinces_lakes.shp seems ok though. import json import os file_dest = os.path.abspath( os.path.join(os.path.dirname(__file__), '../data/countries.json')) replacements = { 'KOS': 'XKX', # Kosovo 'PN1': 'PNG', # Papua New Guniea 'PR1': 'PRT', # Portugal 'SDS': 'SSD', # S. Sudan 'SAH': 'ESH', # W. Sahara } with open(file_dest, 'r') as f: topo = json.load(f) countries = topo['objects']['units']['geometries'] for country in countries: cid = country['properties']['iso3'] country['properties']['iso3'] = replacements.get(cid, cid) with open(file_dest, 'w') as f: json.dump(topo, f, separators=(',', ':')) # save bytes to keep file small
Add Preview to list of possible MSVC versions. Needed to test a Preview version of MSVC and adding it to the list here makes it a bit easier and the list more complete. Change-Id: I419636722303816f0cd961408229fcef0773e8e0 Reviewed-on: https://skia-review.googlesource.com/c/skia/+/286496 Reviewed-by: Mike Klein <14574f09dfa9b4e14759b88c3426a495a0e627b0@google.com> Commit-Queue: Ben Wagner <53965154ffeecc4a10886eab9259e95965f2979a@google.com>
#!/usr/bin/env python # Copyright 2019 Google Inc. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import sys import subprocess ''' Look for the first match in the format C:\\Program Files (x86)\\Microsoft Visual Studio\\${RELEASE}\\${VERSION}\\VC ''' def find_msvc(): if sys.platform.startswith('win'): default_dir = r'C:\Program Files (x86)\Microsoft Visual Studio' for release in ['2019', '2017']: for version in ['Enterprise', 'Professional', 'Community', 'BuildTools', 'Preview']: path = os.path.join(default_dir, release, version, 'VC') if os.path.isdir(path): return path # Fall back to vswhere.exe to determine non-standard installation paths # Fixed location, https://github.com/Microsoft/vswhere/wiki/Installing vswhere = os.path.join(os.getenv('ProgramFiles(x86)'), 'Microsoft Visual Studio', 'Installer', 'vswhere.exe') command = (vswhere + ' -prerelease -legacy -products * -sort -utf8 ' '-property installationPath') paths = subprocess.check_output(command).decode('utf-8').splitlines() if paths: return paths[0] + '\\VC' return None if __name__ == '__main__': result = find_msvc() if result: sys.stdout.write(result + '\n')
#!/usr/bin/env python # Copyright 2019 Google Inc. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import sys import subprocess ''' Look for the first match in the format C:\\Program Files (x86)\\Microsoft Visual Studio\\${RELEASE}\\${VERSION}\\VC ''' def find_msvc(): if sys.platform.startswith('win'): default_dir = r'C:\Program Files (x86)\Microsoft Visual Studio' for release in ['2019', '2017']: for version in ['Enterprise', 'Professional', 'Community', 'BuildTools']: path = os.path.join(default_dir, release, version, 'VC') if os.path.isdir(path): return path # Fall back to vswhere.exe to determine non-standard installation paths # Fixed location, https://github.com/Microsoft/vswhere/wiki/Installing vswhere = os.path.join(os.getenv('ProgramFiles(x86)'), 'Microsoft Visual Studio', 'Installer', 'vswhere.exe') command = (vswhere + ' -prerelease -legacy -products * -sort -utf8 ' '-property installationPath') paths = subprocess.check_output(command).decode('utf-8').splitlines() if paths: return paths[0] + '\\VC' return None if __name__ == '__main__': result = find_msvc() if result: sys.stdout.write(result + '\n')
Change session variable to username
<?php /** * Created by PhpStorm. * User: Catalin * Date: 27-May-17 * Time: 13:11 */ $stid = oci_parse($connection, 'SELECT last_name, first_name, email FROM tutor WHERE username = :username'); $t_username = $_SESSION["username"]; oci_bind_by_name($stid, ':username', $t_username); oci_execute($stid); $row = oci_fetch_array($stid, OCI_BOTH); echo '<tr class="profil_tr">' . '<td class="profil_td">Nume</td>' . '<td class="profil_td">' . $row[1] . '</td></tr>'; echo '<tr class="profil_tr">' . '<td class="profil_td">Prenume</td>' . '<td class="profil_td">' . $row[0] . '</td></tr>'; echo '<tr class="profil_tr">' . '<td class="profil_td">E-mail</td>' . '<td class="profil_td">' . $row[2] . '</td></tr>'; oci_free_statement($stid); $_SESSION["user"] = $t_username; $_SESSION["pname"] = $row[1]; $_SESSION["surname"] = $row[0]; $_SESSION["email"] = $row[2]; oci_close($connection);
<?php /** * Created by PhpStorm. * User: Catalin * Date: 27-May-17 * Time: 13:11 */ $stid = oci_parse($connection, 'SELECT last_name, first_name, email FROM tutor WHERE username = :username'); $t_username = $_SESSION["t_username"]; oci_bind_by_name($stid, ':username', $t_username); oci_execute($stid); $row = oci_fetch_array($stid, OCI_BOTH); echo '<tr class="profil_tr">' . '<td class="profil_td">Nume</td>' . '<td class="profil_td">' . $row[1] . '</td></tr>'; echo '<tr class="profil_tr">' . '<td class="profil_td">Prenume</td>' . '<td class="profil_td">' . $row[0] . '</td></tr>'; echo '<tr class="profil_tr">' . '<td class="profil_td">E-mail</td>' . '<td class="profil_td">' . $row[2] . '</td></tr>'; oci_free_statement($stid); $_SESSION["user"] = $t_username; $_SESSION["pname"] = $row[1]; $_SESSION["surname"] = $row[0]; $_SESSION["email"] = $row[2]; oci_close($connection);
Add shapefile library, used for shapefile-based fixtures.
import os.path from setuptools import find_packages from setuptools import setup version_path = os.path.join(os.path.dirname(__file__), 'VERSION') with open(version_path) as fh: version = fh.read().strip() setup(name='vector-datasource', version=version, description="", long_description="""\ """, classifiers=[], keywords='', author='', author_email='', url='', license='MIT', packages=find_packages(exclude=['ez_setup', 'examples', 'test']), include_package_data=True, zip_safe=False, install_requires=[ 'ASTFormatter', 'mapbox-vector-tile', 'ModestMaps >= 1.3.0', 'pycountry', 'pyshp', 'simplejson', 'StreetNames', 'tilequeue', 'kdtree', 'webcolors', ], test_suite='test', tests_require=[ ], entry_points=""" # -*- Entry points: -*- """, )
import os.path from setuptools import find_packages from setuptools import setup version_path = os.path.join(os.path.dirname(__file__), 'VERSION') with open(version_path) as fh: version = fh.read().strip() setup(name='vector-datasource', version=version, description="", long_description="""\ """, classifiers=[], keywords='', author='', author_email='', url='', license='MIT', packages=find_packages(exclude=['ez_setup', 'examples', 'test']), include_package_data=True, zip_safe=False, install_requires=[ 'ASTFormatter', 'mapbox-vector-tile', 'ModestMaps >= 1.3.0', 'pycountry', 'simplejson', 'StreetNames', 'tilequeue', 'kdtree', 'webcolors', ], test_suite='test', tests_require=[ ], entry_points=""" # -*- Entry points: -*- """, )
Add graphql to extrenal-libs list for webpack, fixing duplication causing Apollo internal errors
const esbuild = require("esbuild"); esbuild.buildSync({ entryPoints: ['./src/platform/current/server/serverStartup.ts'], bundle: true, outfile: './build/server/js/bundle2.js', platform: "node", sourcemap: true, define: { "process.env.NODE_ENV": "\"development\"", "webpackIsServer": true, }, external: [ "akismet-api", "mongodb", "canvas", "express", "mz", "pg", "pg-promise", "mathjax-node", "jsdom", "@sentry/node", "node-fetch", "later", "turndown", "apollo-server", "apollo-server-express", "graphql", ], }) esbuild.buildSync({ entryPoints: ['./src/client.js'], bundle: true, target: "es6", sourcemap: true, outfile: "./build/client/js/bundle.js", define: { "process.env.NODE_ENV": "\"development\"", "webpackIsServer": false, "global": "window", }, });
const esbuild = require("esbuild"); esbuild.buildSync({ entryPoints: ['./src/platform/current/server/serverStartup.ts'], bundle: true, outfile: './build/server/js/bundle2.js', platform: "node", sourcemap: true, define: { "process.env.NODE_ENV": "\"development\"", "webpackIsServer": true, }, external: [ "akismet-api", "mongodb", "canvas", "express", "mz", "pg", "pg-promise", "mathjax-node", "jsdom", "@sentry/node", "node-fetch", "later", "turndown", "apollo-server", "apollo-server-express", ], }) esbuild.buildSync({ entryPoints: ['./src/client.js'], bundle: true, target: "es6", sourcemap: true, outfile: "./build/client/js/bundle.js", define: { "process.env.NODE_ENV": "\"development\"", "webpackIsServer": false, "global": "window", }, });
Make grunt build only for your platform
var os = require('os'); module.exports = function(grunt) { var isWindows = os.platform().indexOf('win') !== -1; var platform = isWindows ? 'win' : 'osx'; grunt.initConfig({ nodewebkit: { options: { version: 'v0.12.0', files: './app/*', downloadUrl: 'http://dl.nwjs.io/', macIcns: './render/icon.icns', mac: function(a){ return {mac: "nwjs-v0.12.0-osx-x64.zip"} }, macPlist: {mac_bundle_id: 'messenger.app.com'}, embed_nw: false, keep_nw: true, platforms: [platform], }, src: './app/**/*' // Your node-webkit app }, }); grunt.loadNpmTasks('grunt-node-webkit-builder'); grunt.registerTask('default', ['nodewebkit']); };
module.exports = function(grunt) { grunt.initConfig({ nodewebkit: { options: { version: 'v0.12.0', files: './app/*', downloadUrl: 'http://dl.nwjs.io/', macIcns: './render/icon.icns', mac: function(a){ return {mac: "nwjs-v0.12.0-osx-x64.zip"} }, macPlist: {mac_bundle_id: 'messenger.app.com'}, embed_nw: false, keep_nw: true, platforms: ['osx', 'win'] }, src: './app/**/*' // Your node-webkit app }, }); grunt.loadNpmTasks('grunt-node-webkit-builder'); grunt.registerTask('default', ['nodewebkit']); };
Decrease accepted file size to 128MB
from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit from .models import FileSubmission, VideoSubmission class VideoSubmissionForm(forms.ModelForm): class Meta: model = VideoSubmission fields = ['video_url'] def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.add_input(Submit('submit', 'Submit')) super(VideoSubmissionForm, self).__init__(*args, **kwargs) class FileSubmissionForm(forms.ModelForm): class Meta: model = FileSubmission fields = ['submission', 'comments'] def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.add_input(Submit('submit', 'Submit')) super(FileSubmissionForm, self).__init__(*args, **kwargs) def clean_submission(self): submission = self.cleaned_data.get('submission', False) if submission: if submission._size > 129 * 1024**2: raise forms.ValidationError("Submission file too large ( > 128 MB )") return submission else: raise forms.ValidationError("Couldn't read uploaded zip.")
from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit from .models import FileSubmission, VideoSubmission class VideoSubmissionForm(forms.ModelForm): class Meta: model = VideoSubmission fields = ['video_url'] def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.add_input(Submit('submit', 'Submit')) super(VideoSubmissionForm, self).__init__(*args, **kwargs) class FileSubmissionForm(forms.ModelForm): class Meta: model = FileSubmission fields = ['submission', 'comments'] def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.add_input(Submit('submit', 'Submit')) super(FileSubmissionForm, self).__init__(*args, **kwargs) def clean_submission(self): submission = self.cleaned_data.get('submission', False) if submission: if submission._size > 1024**3: raise forms.ValidationError("Submission file too large ( > 1 GB )") return submission else: raise forms.ValidationError("Couldn't read uploaded zip.")
Reduce the holdoff distance for invaders
package uk.co.alynn.games.ld30.world; public final class Constants { public static final float SPEED = 300.0f; public static final float SPEED_ROTATION_ADJ = 3.0f; public static final float WRAP_BUFFER = 30.0f; public static final float SPEED_BULLET = 600.0f; public static final float ASTEROID_SPEED = 60.0f; public static final float SECONDS_PER_TICK = 1.0f; public static final float BIND_LIMIT = 5.0f; public static final float PLANET_BIND_RADIUS = 200.0f; public static final float SPEED_INVADER = 50.0f; public static final float INVADER_HOLDOFF = 180.0f; public static final float INVADER_HOLDOFF_TIME = 4.0f; public static final float DEATH_HOLDOFF_TIME = 2.0f; }
package uk.co.alynn.games.ld30.world; public final class Constants { public static final float SPEED = 300.0f; public static final float SPEED_ROTATION_ADJ = 3.0f; public static final float WRAP_BUFFER = 30.0f; public static final float SPEED_BULLET = 600.0f; public static final float ASTEROID_SPEED = 60.0f; public static final float SECONDS_PER_TICK = 1.0f; public static final float BIND_LIMIT = 5.0f; public static final float PLANET_BIND_RADIUS = 200.0f; public static final float SPEED_INVADER = 50.0f; public static final float INVADER_HOLDOFF = 250.0f; public static final float INVADER_HOLDOFF_TIME = 4.0f; public static final float DEATH_HOLDOFF_TIME = 2.0f; }
Use window as global by default, fall back to eval
import collectionHandlers from './collections' // eslint-disable-next-line const globalObj = typeof window === 'object' ? window : Function('return this')(); // built-in object can not be wrapped by Proxies // their methods expect the object instance as the 'this' instead of the Proxy wrapper // complex objects are wrapped with a Proxy of instrumented methods // which switch the proxy to the raw object and to add reactive wiring const handlers = new Map([ [Map, collectionHandlers], [Set, collectionHandlers], [WeakMap, collectionHandlers], [WeakSet, collectionHandlers], [Object, false], [Array, false], [Int8Array, false], [Uint8Array, false], [Uint8ClampedArray, false], [Int16Array, false], [Uint16Array, false], [Int32Array, false], [Uint32Array, false], [Float32Array, false], [Float64Array, false] ]) export function shouldInstrument ({ constructor }) { const isBuiltIn = typeof constructor === 'function' && constructor.name in globalObj && globalObj[constructor.name] === constructor return !isBuiltIn || handlers.has(constructor) } export function getHandlers (obj) { return handlers.get(obj.constructor) }
import collectionHandlers from './collections' // eslint-disable-next-line const globalObj = Function("return this")(); // built-in object can not be wrapped by Proxies // their methods expect the object instance as the 'this' instead of the Proxy wrapper // complex objects are wrapped with a Proxy of instrumented methods // which switch the proxy to the raw object and to add reactive wiring const handlers = new Map([ [Map, collectionHandlers], [Set, collectionHandlers], [WeakMap, collectionHandlers], [WeakSet, collectionHandlers], [Object, false], [Array, false], [Int8Array, false], [Uint8Array, false], [Uint8ClampedArray, false], [Int16Array, false], [Uint16Array, false], [Int32Array, false], [Uint32Array, false], [Float32Array, false], [Float64Array, false] ]) export function shouldInstrument ({ constructor }) { const isBuiltIn = typeof constructor === 'function' && constructor.name in globalObj && globalObj[constructor.name] === constructor return !isBuiltIn || handlers.has(constructor) } export function getHandlers (obj) { return handlers.get(obj.constructor) }
Add missing global var. ACTIVECOLLAB_JOBS_CONSUMER_SCRIPT_TIME
<?php /** * Bootstrap command line application */ date_default_timezone_set('UTC'); defined('APP_PATH') or define('APP_PATH', dirname(dirname(__DIR__))); define('ACTIVECOLLAB_JOBS_CONSUMER_SCRIPT_TIME', microtime(true)); require APP_PATH . '/vendor/autoload.php'; use Symfony\Component\Console\Application; $application = new Application('ID', '1.0');//TODO select version foreach (new DirectoryIterator(APP_PATH . '/src/Commands') as $file) { if ($file->isFile() && $file->getExtension() == 'php') { $class_name = ('\\ActiveCollab\\JobQueue\\Commands\\' . $file->getBasename('.php')); if (!(new ReflectionClass($class_name))->isAbstract()) { $command = new $class_name; $application->add($command); } } } $application->run();
<?php /** * Bootstrap command line application */ date_default_timezone_set('UTC'); defined('APP_PATH') or define('APP_PATH', dirname(dirname(__DIR__))); require APP_PATH . '/vendor/autoload.php'; use Symfony\Component\Console\Application; $application = new Application('ID', '1.0');//TODO select version foreach (new DirectoryIterator(APP_PATH . '/src/Commands') as $file) { if ($file->isFile() && $file->getExtension() == 'php') { $class_name = ('\\ActiveCollab\\JobQueue\\Commands\\' . $file->getBasename('.php')); if (!(new ReflectionClass($class_name))->isAbstract()) { $command = new $class_name; $application->add($command); } } } $application->run();
Handle optional value in step.data
import json from changes.api.serializer import Serializer, register from changes.models import Plan, Step @register(Plan) class PlanSerializer(Serializer): def serialize(self, instance, attrs): return { 'id': instance.id.hex, 'name': instance.label, 'steps': list(instance.steps), 'dateCreated': instance.date_created, 'dateModified': instance.date_modified, } @register(Step) class StepSerializer(Serializer): def serialize(self, instance, attrs): implementation = instance.get_implementation() return { 'id': instance.id.hex, 'implementation': instance.implementation, 'order': instance.order, 'name': implementation.get_label() if implementation else '', 'data': json.dumps(dict(instance.data or {})), 'dateCreated': instance.date_created, }
import json from changes.api.serializer import Serializer, register from changes.models import Plan, Step @register(Plan) class PlanSerializer(Serializer): def serialize(self, instance, attrs): return { 'id': instance.id.hex, 'name': instance.label, 'steps': list(instance.steps), 'dateCreated': instance.date_created, 'dateModified': instance.date_modified, } @register(Step) class StepSerializer(Serializer): def serialize(self, instance, attrs): implementation = instance.get_implementation() return { 'id': instance.id.hex, 'implementation': instance.implementation, 'order': instance.order, 'name': implementation.get_label() if implementation else '', 'data': json.dumps(dict(instance.data)), 'dateCreated': instance.date_created, }
Fix a bug with menu inheritance
<?php declare(strict_types=1); namespace LAG\AdminBundle\Event\Listener\Menu; use LAG\AdminBundle\Admin\Helper\AdminHelperInterface; use LAG\AdminBundle\Event\Events\Configuration\MenuConfigurationEvent; class MenuConfigurationListener { private array $menusConfiguration; private AdminHelperInterface $helper; public function __construct(array $menusConfiguration, AdminHelperInterface $helper) { $this->helper = $helper; $this->menusConfiguration = $menusConfiguration; } public function __invoke(MenuConfigurationEvent $event): void { $menuConfiguration = $event->getMenuConfiguration(); $inherits = $menuConfiguration['inherits'] ?? false; $menuConfiguration = $menuConfigurationFromAction[$event->getMenuName()] ?? []; $menuConfiguration = array_merge($this->menusConfiguration[$event->getMenuName()] ?? [], $menuConfiguration); if ($this->helper->hasAdmin()) { $admin = $this->helper->getAdmin(); $menuConfigurationFromAction = $admin->getAction()->getConfiguration()->getMenus(); if ($inherits) { $menuConfiguration = array_merge($menuConfiguration, $menuConfigurationFromAction[$event->getMenuName()]); } } $event->setMenuConfiguration($menuConfiguration); } }
<?php declare(strict_types=1); namespace LAG\AdminBundle\Event\Listener\Menu; use LAG\AdminBundle\Admin\Helper\AdminHelperInterface; use LAG\AdminBundle\Event\Events\Configuration\MenuConfigurationEvent; class MenuConfigurationListener { private array $menusConfiguration; private AdminHelperInterface $helper; public function __construct(array $menusConfiguration, AdminHelperInterface $helper) { $this->helper = $helper; $this->menusConfiguration = $menusConfiguration; } public function __invoke(MenuConfigurationEvent $event): void { if (!$this->helper->hasAdmin()) { return; } $admin = $this->helper->getAdmin(); $menuConfiguration = $event->getMenuConfiguration(); $menuConfigurationFromAction = $admin->getAction()->getConfiguration()->getMenus(); $inherits = $menuConfiguration['inherits'] ?? false; $menuConfiguration = $menuConfigurationFromAction[$event->getMenuName()] ?? []; if ($inherits) { $menuConfiguration = array_merge($this->menusConfiguration[$event->getMenuName()] ?? [], $menuConfiguration); $menuConfiguration = array_merge($menuConfiguration, $menuConfigurationFromAction[$event->getMenuName()]); } $event->setMenuConfiguration($menuConfiguration); } }
Remove non-used method in image package
package image import ( "github.com/thoas/gostorages" "mime" "path" "strings" ) type ImageFile struct { Source []byte Processed []byte Key string Headers map[string]string Filepath string Storage gostorages.Storage } func (i *ImageFile) Content() []byte { if i.Processed != nil { return i.Processed } return i.Source } func (i *ImageFile) URL() string { return i.Storage.URL(i.Filepath) } func (i *ImageFile) Path() string { return i.Storage.Path(i.Filepath) } func (i *ImageFile) Save() error { return i.Storage.Save(i.Filepath, gostorages.NewContentFile(i.Content())) } func (i *ImageFile) Format() string { return Extensions[i.ContentType()] } func (i *ImageFile) ContentType() string { return mime.TypeByExtension(i.FilenameExt()) } func (i *ImageFile) Filename() string { return i.Filepath[strings.LastIndex(i.Filepath, "/")+1:] } func (i *ImageFile) FilenameExt() string { return path.Ext(i.Filename()) }
package image import ( "github.com/thoas/gostorages" "math" "mime" "path" "strings" ) type ImageFile struct { Source []byte Processed []byte Key string Headers map[string]string Filepath string Storage gostorages.Storage } func (i *ImageFile) Content() []byte { if i.Processed != nil { return i.Processed } return i.Source } func (i *ImageFile) URL() string { return i.Storage.URL(i.Filepath) } func (i *ImageFile) Path() string { return i.Storage.Path(i.Filepath) } func (i *ImageFile) Save() error { return i.Storage.Save(i.Filepath, gostorages.NewContentFile(i.Content())) } func (i *ImageFile) Format() string { return Extensions[i.ContentType()] } func (i *ImageFile) ContentType() string { return mime.TypeByExtension(i.FilenameExt()) } func (i *ImageFile) Filename() string { return i.Filepath[strings.LastIndex(i.Filepath, "/")+1:] } func (i *ImageFile) FilenameExt() string { return path.Ext(i.Filename()) } func scalingFactor(srcWidth int, srcHeight int, destWidth int, destHeight int) float64 { return math.Max(float64(destWidth)/float64(srcWidth), float64(destHeight)/float64(srcHeight)) }
Correct use of findOne here
Router.configure({ layoutTemplate: 'layout', loadingTemplate: 'loading', notFoundTemplate: 'notFound', waitOn: function() { return Meteor.subscribe('posts'); } }); Router.route('/', {name: 'postsList'}); Router.route('/posts/:slug', { name: 'postPage', data: function() { return Posts.findOne({ slug: this.params.slug }); } }); Router.route('/submit', {name: 'postSubmit'}); var requireLogin = function() { if (! Meteor.user()) { if (Meteor.loggingIn()) { this.render(this.loadingTemplate); } else { this.render('accessDenied'); } } else { this.next(); } } Router.onBeforeAction('dataNotFound', {only: 'postPage'}); Router.onBeforeAction(requireLogin, {only: 'postSubmit'});
Router.configure({ layoutTemplate: 'layout', loadingTemplate: 'loading', notFoundTemplate: 'notFound', waitOn: function() { return Meteor.subscribe('posts'); } }); Router.route('/', {name: 'postsList'}); Router.route('/posts/:slug', { name: 'postPage', data: function() { return Posts.find({ slug: this.params.slug }).fetch()[0]; } }); Router.route('/submit', {name: 'postSubmit'}); var requireLogin = function() { if (! Meteor.user()) { if (Meteor.loggingIn()) { this.render(this.loadingTemplate); } else { this.render('accessDenied'); } } else { this.next(); } } Router.onBeforeAction('dataNotFound', {only: 'postPage'}); Router.onBeforeAction(requireLogin, {only: 'postSubmit'});
Handle Meteor's stripping out methods from the fs core API.
var fs = require('fs'); var run = require('./runner'); var defaults = { opensslPath : '/usr/bin/openssl', padding : 'pkcs' }; function verifyOptions (options) { if (fs.existsSync !== undefined && !fs.existsSync(options.opensslPath)) { throw new Error(options.opensslPath + ': No such file or directory'); } if (options.padding !== 'pkcs' && options.padding !== 'raw') { throw new Error('Unsupported padding: ' + options.padding); } } function operation (data, key, callback, options) { var options = options || {}; for (var attr in defaults) { if (!options[attr]) options[attr] = defaults[attr]; } options.operation = operation.caller.name; try { verifyOptions(options); run(options, data, key, callback); } catch (err) { return callback(err); } } exports.encrypt = function encrypt (data, key, callback, options) { operation(data, key, callback, options); }; exports.decrypt = function decrypt (data, key, callback, options) { operation(data, key, callback, options); }; exports.sign = function sign (data, key, callback, options) { operation(data, key, callback, options); }; exports.verify = function verify (data, key, callback, options) { operation(data, key, callback, options); };
var fs = require('fs'); var run = require('./runner'); var defaults = { opensslPath : '/usr/bin/openssl', padding : 'pkcs' }; function verifyOptions (options) { if (!fs.existsSync(options.opensslPath)) { throw new Error(options.opensslPath + ': No such file or directory'); } if (options.padding !== 'pkcs' && options.padding !== 'raw') { throw new Error('Unsupported padding: ' + options.padding); } } function operation (data, key, callback, options) { var options = options || {}; for (var attr in defaults) { if (!options[attr]) options[attr] = defaults[attr]; } options.operation = operation.caller.name; try { verifyOptions(options); run(options, data, key, callback); } catch (err) { return callback(err); } } exports.encrypt = function encrypt (data, key, callback, options) { operation(data, key, callback, options); }; exports.decrypt = function decrypt (data, key, callback, options) { operation(data, key, callback, options); }; exports.sign = function sign (data, key, callback, options) { operation(data, key, callback, options); }; exports.verify = function verify (data, key, callback, options) { operation(data, key, callback, options); };
Fix bug with areas without textures
import Three from 'three'; export default function createArea(vertices, color, textureName) { let shape = new Three.Shape(); shape.moveTo(vertices[0].x, vertices[0].y); for (let i = 1; i < vertices.length; i++) { shape.lineTo(vertices[i].x, vertices[i].y); } if (textureName && textureName !== 'none') { color = 0xffffff; } let areaMaterial = new Three.MeshPhongMaterial({ side: Three.DoubleSide, color: color }); switch (textureName) { case 'parquet': areaMaterial.map = Three.ImageUtils.loadTexture('./libs/textures/parquet.jpg'); areaMaterial.needsUpdate = true; areaMaterial.map.wrapS = Three.RepeatWrapping; areaMaterial.map.wrapT = Three.RepeatWrapping; areaMaterial.map.repeat.set(.01, .01); break; case 'none': default: } let area = new Three.Mesh(new Three.ShapeGeometry(shape), areaMaterial); area.rotation.x -= Math.PI / 2; return area; }
import Three from 'three'; export default function createArea(vertices, color, textureName) { let shape = new Three.Shape(); shape.moveTo(vertices[0].x, vertices[0].y); for (let i = 1; i < vertices.length; i++) { shape.lineTo(vertices[i].x, vertices[i].y); } let areaMaterial = new Three.MeshPhongMaterial({ side: Three.DoubleSide, }); switch (textureName) { case 'parquet': areaMaterial.map = Three.ImageUtils.loadTexture('./libs/textures/parquet.jpg'); areaMaterial.needsUpdate = true; areaMaterial.map.wrapS = Three.RepeatWrapping; areaMaterial.map.wrapT = Three.RepeatWrapping; areaMaterial.map.repeat.set(.01, .01); break; case 'none': default: areaMaterial.color = color; } let area = new Three.Mesh(new Three.ShapeGeometry(shape), areaMaterial); area.rotation.x -= Math.PI / 2; return area; }
Fix up gjshint errors in output manager
'use strict'; var OutputManager = (function() { var outputs = []; var active = []; var display = undefined; var addOutput = function(o) { outputs.push(o); }; var activateOutput = function(o) { active.push(o); }; var deactivateOutput = function(o) { var i = active.indexOf(o); active.splice(i, 1); showActiveOutputs(); }; var updateActiveOutputs = function(speed, direction) { for (var o in active) { o.update(speed, direction); } }; var showActiveOutputs = function() { display.children().each(function(i) { this.detach(); }); for (var o in active) { } }; return { get outputList() { return outputs; }, setDisplayDiv: function(d) { display = d; }, add: addOutput, activate: activateOutput, deactivate: deactivateOutput, show: undefined, update: updateActiveOutputs }; })();
'use strict'; var OutputManager = (function () { var outputs = []; var active = []; var display = undefined; var addOutput = function(o) { outputs.push(o); }; var activateOutput = function(o) { active.push(o); }; var deactivateOutput = function(o) { var i = active.indexOf(o); active.splice(i, 1); showActiveOutputs(); }; var updateActiveOutputs = function(speed, direction) { for(var o in active) { o.update(speed, direction); } }; var showActiveOutputs = function() { display.children().each(function(i) { this.detach(); }); for(var o in active) { } }; return { setDisplayDiv: function (d) { display = d; }, add: addOutput, activate: activateOutput, deactivate: deactivateOutput, show: undefined, get outputList: { return outputs; } update: updateActiveOutputs }; })();
Use format() instead of %
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import template from django.utils.html import mark_safe register = template.Library() from django.conf import settings import os, re rx = re.compile(r"^(.*)\.(.*?)$") @register.simple_tag def version(path): full_path = os.path.join(settings.STATIC_ROOT, path) if not settings.DEBUG: # Get file modification time. os.stat_float_times(False) mtime = os.path.getmtime(full_path) # raises OSError if file does not exist path = rx.sub(r"\1.{}.\2".format(mtime), path) return os.path.join(settings.STATIC_URL, path) @register.filter def highlight(text, word): return mark_safe(text.replace(word, "<span class='highlight'>%s</span>" % word))
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import template from django.utils.html import mark_safe register = template.Library() from django.conf import settings import os, re rx = re.compile(r"^(.*)\.(.*?)$") @register.simple_tag def version(path): full_path = os.path.join(settings.STATIC_ROOT, path) if not settings.DEBUG: # Get file modification time. os.stat_float_times(False) mtime = os.path.getmtime(full_path) # raises OSError if file does not exist path = rx.sub(r"\1.%d.\2" % mtime, path) return os.path.join(settings.STATIC_URL, path) @register.filter def highlight(text, word): return mark_safe(text.replace(word, "<span class='highlight'>%s</span>" % word))
Tweak import statement to satisfy presubmit checks. Review URL: http://codereview.chromium.org/8292004 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@105578 0039d316-1c4b-4281-b951-d872f2087c98
#!/usr/bin/env python # Copyright (c) 2011 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. """Dumps a list of known slaves, along with their OS and master.""" import os import sys path = os.path.join(os.path.dirname(__file__), os.path.pardir) sys.path.append(path) from common import chromium_utils slaves = [] for master in chromium_utils.ListMasters(): masterbase = os.path.basename(master) master_slaves = {} execfile(os.path.join(master, 'slaves.cfg'), master_slaves) for slave in master_slaves.get('slaves', []): slave['master'] = masterbase slaves.extend(master_slaves.get('slaves', [])) for slave in sorted(slaves, cmp=None, key=lambda x : x.get('hostname', '')): slavename = slave.get('hostname') if not slavename: continue osname = slave.get('os', '?') print '%-30s %-35s %-10s' % (slavename, slave.get('master', '?'), osname)
#!/usr/bin/env python import os import sys path = os.path.join(os.path.dirname(__file__), os.path.pardir, 'common') sys.path.append(path) import chromium_utils slaves = [] for master in chromium_utils.ListMasters(): masterbase = os.path.basename(master) master_slaves = {} execfile(os.path.join(master, 'slaves.cfg'), master_slaves) for slave in master_slaves.get('slaves', []): slave['master'] = masterbase slaves.extend(master_slaves.get('slaves', [])) for slave in sorted(slaves, cmp=None, key=lambda x : x.get('hostname', '')): slavename = slave.get('hostname') if not slavename: continue osname = slave.get('os', '?') print '%-30s %-35s %-10s' % (slavename, slave.get('master', '?'), osname)
Include cacert.pem as part of the package
# -*- coding: utf-8 -*- from setuptools import setup setup( name='pusher', version='1.2.0', description='A Python library to interract with the Pusher API', url='https://github.com/pusher/pusher-http-python', author='Pusher', author_email='support@pusher.com', classifiers=[ "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Topic :: Internet :: WWW/HTTP", ], keywords='pusher rest realtime websockets service', license='MIT', packages=[ 'pusher' ], install_requires=['six', 'requests>=2.3.0', 'urllib3', 'pyopenssl', 'ndg-httpsclient', 'pyasn1'], tests_require=['nose', 'mock', 'HTTPretty'], extras_require={ 'aiohttp': ["aiohttp>=0.9.0"], 'tornado': ['tornado>=4.0.0'] }, package_data={ 'pusher': ['cacert.pem'] }, test_suite='pusher_tests', )
# -*- coding: utf-8 -*- from setuptools import setup setup( name='pusher', version='1.2.0', description='A Python library to interract with the Pusher API', url='https://github.com/pusher/pusher-http-python', author='Pusher', author_email='support@pusher.com', classifiers=[ "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Topic :: Internet :: WWW/HTTP", ], keywords='pusher rest realtime websockets service', license='MIT', packages=[ 'pusher' ], install_requires=['six', 'requests>=2.3.0', 'urllib3', 'pyopenssl', 'ndg-httpsclient', 'pyasn1'], tests_require=['nose', 'mock', 'HTTPretty'], extras_require={ 'aiohttp': ["aiohttp>=0.9.0"], 'tornado': ['tornado>=4.0.0'] }, test_suite='pusher_tests', )
Remove temparary HDF5 cache workaround.
# -*- coding: utf-8 -*- """ @author: Aaron Ponti """ import os import logging import re from ch.systemsx.cisd.openbis.common.hdf5 import HDF5Container from Processor import Processor def process(transaction): """Dropbox entry point. @param transaction, the transaction object """ # Get path to containing folder # __file__ does not work (reliably) in Jython dbPath = "../core-plugins/microscopy/1/dss/drop-boxes/MicroscopyDropbox" # Path to the logs subfolder logPath = os.path.join(dbPath, "logs") # Make sure the logs subforder exist if not os.path.exists(logPath): os.makedirs(logPath) # Path for the log file logFile = os.path.join(logPath, "registration_log.txt") # Set up logging logger = logging.getLogger('MicroscopyDropbox') logger.setLevel(logging.DEBUG) fh = logging.FileHandler(logFile) fh.setLevel(logging.DEBUG) format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' formatter = logging.Formatter(format) fh.setFormatter(formatter) logger.addHandler(fh) # Create a Processor processor = Processor(transaction, logger) # Run processor.run()
# -*- coding: utf-8 -*- """ @author: Aaron Ponti """ import os import logging import re from ch.systemsx.cisd.openbis.common.hdf5 import HDF5Container from Processor import Processor def process(transaction): """Dropbox entry point. @param transaction, the transaction object """ # Disabling HDF5 caching HDF5Container.disableCaching() # Get path to containing folder # __file__ does not work (reliably) in Jython dbPath = "../core-plugins/microscopy/1/dss/drop-boxes/MicroscopyDropbox" # Path to the logs subfolder logPath = os.path.join(dbPath, "logs") # Make sure the logs subforder exist if not os.path.exists(logPath): os.makedirs(logPath) # Path for the log file logFile = os.path.join(logPath, "registration_log.txt") # Set up logging logger = logging.getLogger('MicroscopyDropbox') logger.setLevel(logging.DEBUG) fh = logging.FileHandler(logFile) fh.setLevel(logging.DEBUG) format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' formatter = logging.Formatter(format) fh.setFormatter(formatter) logger.addHandler(fh) # Create a Processor processor = Processor(transaction, logger) # Run processor.run()
Fix complaints from CS fixer
<?php namespace Korobi\WebBundle\Test\Unit; use Korobi\WebBundle\IRC\Parser\LogParser; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; use Symfony\Component\Translation\TranslatorInterface; class LogParserTest extends WebTestCase { public function testTransformActorEscaping() { $sut = new LogParser(new DummyTranslator()); $result = $sut->transformActor("<strong>HTML</strong><marquee>yay</marquee>"); $this->assertNotContains("<", $result, "Left angle bracket must not be in result."); $this->assertNotContains(">", $result, "Right angle bracket must not be in result."); } } class DummyTranslator implements TranslatorInterface { public function trans($id, array $parameters = [], $domain = null, $locale = null) { return "Cat."; } public function transChoice($id, $number, array $parameters = [], $domain = null, $locale = null) { return "Cat."; } public function setLocale($locale) { return; } public function getLocale() { return "Cat."; } }
<?php namespace Korobi\WebBundle\Test\Unit; use Korobi\WebBundle\Document\Chat; use Korobi\WebBundle\IRC\Parser\IRCTextParser; use Korobi\WebBundle\IRC\Parser\LogParser; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; use Symfony\Component\Translation\TranslatorInterface; class LogParserTest extends WebTestCase { public function testTransformActorEscaping() { $sut = new LogParser(new DummyTranslator()); $result = $sut->transformActor("<strong>HTML</strong><marquee>yay</marquee>"); $this->assertNotContains("<", $result, "Left angle bracket must not be in result."); $this->assertNotContains(">", $result, "Right angle bracket must not be in result."); } } class DummyTranslator implements TranslatorInterface { public function trans($id, array $parameters = array(), $domain = null, $locale = null) { return "Cat."; } public function transChoice($id, $number, array $parameters = array(), $domain = null, $locale = null) { return "Cat."; } public function setLocale($locale) { return; } public function getLocale() { return "Cat."; } }
Add csrf token in MyRequests class
import requests class MyRequests(object): """ Simple class to make requests with or withour cookies etc. This way we can have the same request methods both in io and core """ def __init__(self, uri, data=None, cookie=None, timeout=None, csrf=None): self.headers = {'Cookie': cookie, 'Csrf-Token': csrf} self.timeout = timeout self.uri = uri self.data = data def post(self): response = requests.post(self.uri, data=self.data, headers=self.headers, timeout=self.timeout) return response def get(self): response = requests.get(self.uri, data=self.data, headers=self.headers, timeout=self.timeout) return response def put(self): response = requests.put(self.uri, data=self.data, headers=self.headers, timeout=self.timeout) return response def delete(self): response = requests.delete(self.uri, data=self.data, headers=self.headers, timeout=self.timeout) return response
import requests class MyRequests(object): """ Simple class to make requests with or withour cookies etc. This way we can have the same request methods both in io and core """ def __init__(self, uri, data=None, cookie=None, timeout=None): self.headers = {'Cookie': cookie} self.timeout = timeout self.uri = uri self.data = data def post(self): response = requests.post(self.uri, data=self.data, headers=self.headers, timeout=self.timeout) return response def get(self): response = requests.get(self.uri, data=self.data, headers=self.headers, timeout=self.timeout) return response def put(self): response = requests.put(self.uri, data=self.data, headers=self.headers, timeout=self.timeout) return response def delete(self): response = requests.delete(self.uri, data=self.data, headers=self.headers, timeout=self.timeout) return response
Add a __repr__ for CodeSearchResult
# -*- coding: utf-8 -*- from github3.models import GitHubCore from github3.repos import Repository class CodeSearchResult(GitHubCore): def __init__(self, data, session=None): super(CodeSearchResult, self).__init__(data, session) self._api = data.get('url') #: Filename the match occurs in self.name = data.get('name') #: Path in the repository to the file self.path = data.get('path') #: SHA in which the code can be found self.sha = data.get('sha') #: URL to the Git blob endpoint self.git_url = data.get('git_url') #: URL to the HTML view of the blob self.html_url = data.get('html_url') #: Repository the code snippet belongs to self.repository = Repository(data.get('repository', {}), self) #: Score of the result self.score = data.get('score') #: Text matches self.text_matches = data.get('text_matches', []) def __repr__(self): return '<CodeSearchResult [{0}]>'.format(self.path)
# -*- coding: utf-8 -*- from github3.models import GitHubCore from github3.repos import Repository class CodeSearchResult(GitHubCore): def __init__(self, data, session=None): super(CodeSearchResult, self).__init__(data, session) self._api = data.get('url') #: Filename the match occurs in self.name = data.get('name') #: Path in the repository to the file self.path = data.get('path') #: SHA in which the code can be found self.sha = data.get('sha') #: URL to the Git blob endpoint self.git_url = data.get('git_url') #: URL to the HTML view of the blob self.html_url = data.get('html_url') #: Repository the code snippet belongs to self.repository = Repository(data.get('repository', {}), self) #: Score of the result self.score = data.get('score') #: Text matches self.text_matches = data.get('text_matches', [])
Add support for Follow in its own column
package cues import ( "errors" "strings" ) type CueTemplate struct { Mapping map[string]int } //end CueTemplate func (tmpl CueTemplate) Create(headers []string) (CueTemplate, error) { var err error tmpl.Mapping = make(map[string]int) //iterate headers for i := range headers { //check name match header := headers[i] switch { case strings.ToLower(header) == "cue": tmpl.Mapping["cue"] = i case strings.ToLower(header) == "description": tmpl.Mapping["text"] = i case strings.ToLower(header) == "page", strings.ToLower(header) == "pg": tmpl.Mapping["page"] = i case strings.ToLower(header) == "time": tmpl.Mapping["time"] = i case strings.ToLower(header) == "link": tmpl.Mapping["link"] = i case strings.ToLower(header) == "flags": tmpl.Mapping["flags"] = i case strings.ToLower(header) == "follow": tmpl.Mapping["follow"] = i } //end switch } //end iterate headers for} if _, ok := tmpl.Mapping["cue"]; !ok { err = errors.New("No cue header specified") } return tmpl, err }
package cues import ( "errors" "strings" ) type CueTemplate struct { Mapping map[string]int } //end CueTemplate func (tmpl CueTemplate) Create(headers []string) (CueTemplate, error) { var err error tmpl.Mapping = make(map[string]int) //iterate headers for i := range headers { //check name match header := headers[i] switch { case strings.ToLower(header) == "cue": tmpl.Mapping["cue"] = i case strings.ToLower(header) == "description": tmpl.Mapping["text"] = i case strings.ToLower(header) == "page", strings.ToLower(header) == "pg": tmpl.Mapping["page"] = i case strings.ToLower(header) == "time": tmpl.Mapping["time"] = i case strings.ToLower(header) == "link": tmpl.Mapping["link"] = i case strings.ToLower(header) == "flags": tmpl.Mapping["flags"] = i } //end switch } //end iterate headers for} if _, ok := tmpl.Mapping["cue"]; !ok { err = errors.New("No cue header specified") } return tmpl, err }
Add created_at to what we get for a workflow
import apiClient from 'panoptes-client/lib/api-client'; import { config } from 'constants/config'; import * as type from 'constants/actions'; function workflowsRequested() { return { type: type.WORKFLOWS_REQUESTED }; } function workflowsReceived(json) { return { type: type.WORKFLOWS_RECEIVED, json }; } export function fetchWorkflows() { const fields = 'active,classifications_count,completeness,' + 'display_name,finished_at,retirement,subjects_count,created_at'; let page = 1; return dispatch => { dispatch(workflowsRequested()); apiClient.type('workflows').get({ project_id: config.projectId, fields, page }) .then(json => { dispatch(workflowsReceived(json)); for (page = 2; page <= json[0]._meta.workflows.page_count; ++page) { apiClient.type('workflows').get({ project_id: config.projectId, fields, page }) .then(ws => dispatch(workflowsReceived(ws))); } }); }; }
import apiClient from 'panoptes-client/lib/api-client'; import { config } from 'constants/config'; import * as type from 'constants/actions'; function workflowsRequested() { return { type: type.WORKFLOWS_REQUESTED }; } function workflowsReceived(json) { return { type: type.WORKFLOWS_RECEIVED, json }; } export function fetchWorkflows() { const fields = 'active,classifications_count,completeness,' + 'display_name,finished_at,retirement,subjects_count'; let page = 1; return dispatch => { dispatch(workflowsRequested()); apiClient.type('workflows').get({ project_id: config.projectId, fields, page }) .then(json => { dispatch(workflowsReceived(json)); for (page = 2; page <= json[0]._meta.workflows.page_count; ++page) { apiClient.type('workflows').get({ project_id: config.projectId, fields, page }) .then(ws => dispatch(workflowsReceived(ws))); } }); }; }
Create action rather than toolbar button
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. define(["base/js/namespace"], function(Jupyter) { "use strict"; var save_state = function() { Jupyter.WidgetManager._managers[0].get_state().then(function(state) { var data = "text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(state, null, " ")); var a = document.createElement("a"); a.download = "state.json"; a.href = "data:" + data; a.click(); }); }; var action = { help: 'Download Widget State', icon: 'fa-sliders', help_index : 'zz', handler : save_state }; var action_name = 'save-widget-state'; var prefix = ''; Jupyter.notebook.keyboard_manager.actions.register(action, action_name, prefix); });
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. // npm compatibility if (typeof define !== 'function') { var define = require('./requirejs-shim')(module); } define(["base/js/namespace"], function(Jupyter) { "use strict"; var save_state = function() { Jupyter.WidgetManager._managers[0].get_state().then(function(state) { var data = "text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(state, null, " ")); var a = document.createElement("a"); a.download = "state.json"; a.href = "data:" + data; a.click(); }); }; var load_extension = function() { Jupyter.toolbar.add_buttons_group([{ id : 'widget_manager_state', label : 'Download Widget State', icon : 'fa-sliders', callback : save_state }]); }; load_extension(); });
Add public visibility to constructors
<?php namespace Kunstmaan\AdminBundle\EventListener; use FOS\UserBundle\Event\FilterUserResponseEvent; use FOS\UserBundle\Model\UserManager; /** * Set password_changed property to 1 after changing the password */ class PasswordResettingListener { /** * @var UserManager */ private $userManager; /** * @param UserManager $userManager */ public function __construct(UserManager $userManager) { $this->userManager = $userManager; } /** * @param FilterUserResponseEvent $event */ public function onPasswordResettingSuccess(FilterUserResponseEvent $event) { $user = $event->getUser(); $user->setPasswordChanged(true); $this->userManager->updateUser($user); } }
<?php namespace Kunstmaan\AdminBundle\EventListener; use FOS\UserBundle\Event\FilterUserResponseEvent; use FOS\UserBundle\Model\UserManager; /** * Set password_changed property to 1 after changing the password */ class PasswordResettingListener { /** * @var UserManager */ private $userManager; /** * @param UserManager $userManager */ function __construct(UserManager $userManager) { $this->userManager = $userManager; } /** * @param FilterUserResponseEvent $event */ public function onPasswordResettingSuccess(FilterUserResponseEvent $event) { $user = $event->getUser(); $user->setPasswordChanged(true); $this->userManager->updateUser($user); } }
Add socket.io to handle client real-time requests
const path = require('path'); const favicon = require('serve-favicon'); const compress = require('compression'); const cors = require('cors'); const helmet = require('helmet'); const bodyParser = require('body-parser'); const feathers = require('feathers'); const configuration = require('feathers-configuration'); const hooks = require('feathers-hooks'); const rest = require('feathers-rest'); const socketio = require('feathers-socketio'); const middleware = require('./middleware'); const services = require('./services'); const appHooks = require('./app.hooks'); const mongodb = require('./mongodb'); const app = feathers(); // Load app configuration app.configure(configuration(path.join(__dirname, '..'))); // Enable CORS, security, compression, favicon and body parsing app.use(cors()); app.use(helmet()); app.use(compress()); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(favicon(path.join(app.get('public'), 'favicon.ico'))); // Host the public folder app.use('/', feathers.static(app.get('public'))); // Set up Plugins and providers app.configure(hooks()); app.configure(mongodb); app.configure(rest()); app.configure(socketio()); // Set up our services (see `services/index.js`) app.configure(services); // Configure middleware (see `middleware/index.js`) - always has to be last app.configure(middleware); app.hooks(appHooks); module.exports = app;
const path = require('path'); const favicon = require('serve-favicon'); const compress = require('compression'); const cors = require('cors'); const helmet = require('helmet'); const bodyParser = require('body-parser'); const feathers = require('feathers'); const configuration = require('feathers-configuration'); const hooks = require('feathers-hooks'); const rest = require('feathers-rest'); const middleware = require('./middleware'); const services = require('./services'); const appHooks = require('./app.hooks'); const mongodb = require('./mongodb'); const app = feathers(); // Load app configuration app.configure(configuration(path.join(__dirname, '..'))); // Enable CORS, security, compression, favicon and body parsing app.use(cors()); app.use(helmet()); app.use(compress()); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(favicon(path.join(app.get('public'), 'favicon.ico'))); // Host the public folder app.use('/', feathers.static(app.get('public'))); // Set up Plugins and providers app.configure(hooks()); app.configure(mongodb); app.configure(rest()); // Set up our services (see `services/index.js`) app.configure(services); // Configure middleware (see `middleware/index.js`) - always has to be last app.configure(middleware); app.hooks(appHooks); module.exports = app;
Fix broken GitHub repository URL
try: from setuptools import setup except ImportError: from distutils.core import setup config = { 'name' : 'Redis Grepper', 'description' : 'Perform regex searches through Redis values', 'author' : 'Ionut G. Stan', 'author_email' : 'ionut.g.stan@gmail.com', 'url' : 'http://github.com/igstan/redis-grep', 'download_url' : 'http://github.com/igstan/redis-grep/zipball/0.1.1', 'version' : '0.1.1', 'install_requires' : ['redis'], 'py_modules' : ['redisgrep'], 'scripts' : ['redis-grep'], } setup(**config)
try: from setuptools import setup except ImportError: from distutils.core import setup config = { 'name' : 'Redis Grepper', 'description' : 'Perform regex searches through Redis values', 'author' : 'Ionut G. Stan', 'author_email' : 'ionut.g.stan@gmail.com', 'url' : 'http://github.com/igstan/regis-grep', 'download_url' : 'http://github.com/igstan/redis-grep/zipball/0.1.1', 'version' : '0.1.1', 'install_requires' : ['redis'], 'py_modules' : ['redisgrep'], 'scripts' : ['redis-grep'], } setup(**config)
Implement get() function with apc_fetch()
<?php class Better_PHP_Cache { public function __construct() { } public function add($entry_name, $entry_value, $time_to_live) { if(!($entry_name && $entry_value && $time_to_live)) { return FALSE; } return apc_store($entry_name, $entry_value, $time_to_live); } public function get($entry_name) { if(!$entry_name) { return FALSE; } return apc_fetch($entry_name); } public function delete($entry_name) { } } ?>
<?php class Better_PHP_Cache { public function __construct() { } public function add($entry_name, $entry_value, $time_to_live) { if(!($entry_name && $entry_value && $time_to_live)) { return FALSE; } return apc_store($entry_name, $entry_value, $time_to_live); } public function get($entry_name) { } public function delete($entry_name) { } } ?>
Order by modified_at create problem with endless_navigation and browser cache Need to handle cache properly before
from django.views.generic import TemplateView from chickpea.models import Map class Home(TemplateView): template_name = "youmap/home.html" list_template_name = "chickpea/map_list.html" def get_context_data(self, **kwargs): maps = Map.objects.order_by('-pk')[:100] return { "maps": maps } def get_template_names(self): """ Dispatch template according to the kind of request: ajax or normal. """ if self.request.is_ajax(): return [self.list_template_name] else: return [self.template_name] home = Home.as_view()
from django.views.generic import TemplateView from chickpea.models import Map class Home(TemplateView): template_name = "youmap/home.html" list_template_name = "chickpea/map_list.html" def get_context_data(self, **kwargs): maps = Map.objects.order_by('-modified_at')[:100] return { "maps": maps } def get_template_names(self): """ Dispatch template according to the kind of request: ajax or normal. """ if self.request.is_ajax(): return [self.list_template_name] else: return [self.template_name] home = Home.as_view()
Add my classic Struct "class." That's right, I embrace the lazy.
# Giles: utils.py # Copyright 2012 Phil Bordelon # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. class Struct(object): # Empty class, useful for making "structs." pass def booleanize(msg): # This returns: # -1 for False # 1 for True # 0 for invalid input. if type(msg) != str: return 0 msg = msg.strip().lower() if (msg == "on" or msg == "true" or msg == "yes" or msg == "y" or msg == "t" or msg == "1"): return 1 elif (msg == "off" or msg == "false" or msg == "no" or msg == "n" or msg == "f" or msg == "0"): return -1 return 0
# Giles: utils.py # Copyright 2012 Phil Bordelon # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. def booleanize(msg): # This returns: # -1 for False # 1 for True # 0 for invalid input. if type(msg) != str: return 0 msg = msg.strip().lower() if (msg == "on" or msg == "true" or msg == "yes" or msg == "y" or msg == "t" or msg == "1"): return 1 elif (msg == "off" or msg == "false" or msg == "no" or msg == "n" or msg == "f" or msg == "0"): return -1 return 0
Adjust Cursors render method map to iterate through a normal array
import React, { Component } from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import Cursor from './Cursor'; class Cursors extends Component { render() { return ( <div> {this.props.displayedUsers.valueSeq().toArray().map(user => ( <Cursor key={user.get('username')} username={user.get('username')} color={user.get('color')} x={user.get('x')} y={user.get('y')} /> ))} </div> ); } } Cursors.propTypes = { displayedUsers: ImmutablePropTypes.orderedMap.isRequired }; export default Cursors;
import React, { Component } from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import Cursor from './Cursor'; class Cursors extends Component { render() { return ( <div> {this.props.displayedUsers.map(user => ( <Cursor username={user.get('username')} color={user.get('color')} x={user.get('x')} y={user.get('y')} /> ))} </div> ); } } Cursors.propTypes = { displayedUsers: ImmutablePropTypes.orderedMap.isRequired }; export default Cursors;
Create error logging in snake observer
package observers import ( "github.com/sirupsen/logrus" "github.com/ivan1993spb/snake-server/objects/corpse" "github.com/ivan1993spb/snake-server/objects/snake" "github.com/ivan1993spb/snake-server/world" ) const chanSnakeObserverEventsBuffer = 32 type SnakeObserver struct{} func (SnakeObserver) Observe(stop <-chan struct{}, w *world.World, logger logrus.FieldLogger) { go func() { for event := range w.Events(stop, chanSnakeObserverEventsBuffer) { if event.Type == world.EventTypeObjectDelete { if s, ok := event.Payload.(*snake.Snake); ok { if c, err := corpse.NewCorpse(w, s.GetLocation()); err != nil { logger.WithError(err).Error("cannot create corpse") } else { c.Run(stop) } } } } }() }
package observers import ( "github.com/sirupsen/logrus" "github.com/ivan1993spb/snake-server/objects/corpse" "github.com/ivan1993spb/snake-server/objects/snake" "github.com/ivan1993spb/snake-server/world" ) type SnakeObserver struct{} func (SnakeObserver) Observe(stop <-chan struct{}, w *world.World, logger logrus.FieldLogger) { go func() { // TODO: Create buffer const. for event := range w.Events(stop, 32) { if event.Type == world.EventTypeObjectDelete { if s, ok := event.Payload.(*snake.Snake); ok { // TODO: Handle error. c, err := corpse.NewCorpse(w, s.GetLocation()) if err == nil { c.Run(stop) } } } } }() }
Fix crash when no data
import { DEFAULT_EMISSIONS_SELECTIONS, DATA_SCALE, CALCULATION_OPTIONS } from 'data/constants'; export const getGhgEmissionDefaults = (source, meta) => { const defaults = DEFAULT_EMISSIONS_SELECTIONS[source]; if (!defaults) return {}; const sectorDefaults = source === 'UNFCCC' ? Object.keys(defaults.sector).map(key => defaults.sector[key]) : defaults.sector; return { gas: meta.gas.find(g => g.label === defaults.gas).value, sector: meta.sector .filter(s => sectorDefaults.indexOf(s.label) > -1) .map(s => s.value) .toString(), location: defaults.location }; }; export const calculatedRatio = (selected, calculationData, x) => { if (!calculationData || !calculationData[x]) return 1; if (selected === CALCULATION_OPTIONS.PER_GDP.value) { // GDP is in dollars and we want to display it in million dollars return calculationData[x][0].gdp / DATA_SCALE; } if (selected === CALCULATION_OPTIONS.PER_CAPITA.value) { return calculationData[x][0].population; } return 1; }; export default { getGhgEmissionDefaults, calculatedRatio };
import { DEFAULT_EMISSIONS_SELECTIONS, DATA_SCALE, CALCULATION_OPTIONS } from 'data/constants'; export const getGhgEmissionDefaults = (source, meta) => { const defaults = DEFAULT_EMISSIONS_SELECTIONS[source]; const sectorDefaults = source === 'UNFCCC' ? Object.keys(defaults.sector).map(key => defaults.sector[key]) : defaults.sector; return { gas: meta.gas.find(g => g.label === defaults.gas).value, sector: meta.sector .filter(s => sectorDefaults.indexOf(s.label) > -1) .map(s => s.value) .toString(), location: defaults.location }; }; export const calculatedRatio = (selected, calculationData, x) => { if (!calculationData || !calculationData[x]) return 1; if (selected === CALCULATION_OPTIONS.PER_GDP.value) { // GDP is in dollars and we want to display it in million dollars return calculationData[x][0].gdp / DATA_SCALE; } if (selected === CALCULATION_OPTIONS.PER_CAPITA.value) { return calculationData[x][0].population; } return 1; }; export default { getGhgEmissionDefaults, calculatedRatio };
Add nologin in expected user shell test
""" Role tests """ import os import pytest from testinfra.utils.ansible_runner import AnsibleRunner testinfra_hosts = AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') @pytest.mark.parametrize('name', [ ('vsftpd'), ('db5.3-util'), ]) def test_installed_packages(host, name): """ Test if packages installed """ assert host.package(name).is_installed def test_service(host): """ Test service state """ service = host.service('vsftpd') assert service.is_enabled # if host.system_info.codename in ['jessie', 'xenial']: if host.file('/etc/init.d/vsftpd').exists: assert 'is running' in host.check_output('/etc/init.d/vsftpd status') else: assert service.is_running def test_process(host): """ Test process state """ assert len(host.process.filter(comm='vsftpd')) == 1 def test_socket(host): """ Test ports """ assert host.socket('tcp://127.0.0.1:21').is_listening def test_user(host): """ Test ftp user exists """ ftp_user = host.user('ftp') assert ftp_user.exists assert ftp_user.shell in ['/usr/sbin/nologin', '/bin/false']
""" Role tests """ import os import pytest from testinfra.utils.ansible_runner import AnsibleRunner testinfra_hosts = AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') @pytest.mark.parametrize('name', [ ('vsftpd'), ('db5.3-util'), ]) def test_installed_packages(host, name): """ Test if packages installed """ assert host.package(name).is_installed def test_service(host): """ Test service state """ service = host.service('vsftpd') assert service.is_enabled # if host.system_info.codename in ['jessie', 'xenial']: if host.file('/etc/init.d/vsftpd').exists: assert 'is running' in host.check_output('/etc/init.d/vsftpd status') else: assert service.is_running def test_process(host): """ Test process state """ assert len(host.process.filter(comm='vsftpd')) == 1 def test_socket(host): """ Test ports """ assert host.socket('tcp://127.0.0.1:21').is_listening def test_user(host): """ Test ftp user exists """ ftp_user = host.user('ftp') assert ftp_user.exists assert ftp_user.shell == '/bin/false'
Fix InspectorMemoryTest.testGetDOMStats to have consistent behaviour on CrOS and desktop versions of Chrome. Starting the browser in CrOS requires navigating through an initial setup that does not leave us with a tab at "chrome://newtab". This workaround runs the test in a new tab on all platforms for consistency. BUG=235634 TEST=InspectorMemoryTest.testGetDOMStats passes on cros and system NOTRY=true Review URL: https://chromiumcodereview.appspot.com/14672002 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@197490 0039d316-1c4b-4281-b951-d872f2087c98
# Copyright (c) 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. import os from telemetry.test import tab_test_case class InspectorMemoryTest(tab_test_case.TabTestCase): def testGetDOMStats(self): unittest_data_dir = os.path.join(os.path.dirname(__file__), '..', '..', '..', 'unittest_data') self._browser.SetHTTPServerDirectories(unittest_data_dir) # Due to an issue with CrOS, we create a new tab here rather than # using self._tab to get a consistent starting page on all platforms tab = self._browser.tabs.New() tab.Navigate( self._browser.http_server.UrlOf('dom_counter_sample.html')) tab.WaitForDocumentReadyStateToBeComplete() counts = tab.dom_stats self.assertEqual(counts['document_count'], 2) self.assertEqual(counts['node_count'], 18) self.assertEqual(counts['event_listener_count'], 2)
# Copyright (c) 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. import os from telemetry.test import tab_test_case class InspectorMemoryTest(tab_test_case.TabTestCase): def testGetDOMStats(self): unittest_data_dir = os.path.join(os.path.dirname(__file__), '..', '..', '..', 'unittest_data') self._browser.SetHTTPServerDirectories(unittest_data_dir) self._tab.Navigate( self._browser.http_server.UrlOf('dom_counter_sample.html')) self._tab.WaitForDocumentReadyStateToBeComplete() counts = self._tab.dom_stats self.assertEqual(counts['document_count'], 1) self.assertEqual(counts['node_count'], 14) self.assertEqual(counts['event_listener_count'], 2)
ERR: Fix space problem and put try around os.kill
""" Driver script for testing sockets Unix only """ import os, sys, time # Fork, run server in child, client in parent pid = os.fork() if pid == 0: # exec the parent os.execv(sys.argv[1], ('-D', sys.argv[3])) else: # wait a little to make sure that the server is ready time.sleep(10) # run the client retVal = os.system('"%s" -D "%s" -V "%s"' % ( sys.argv[2], sys.argv[3], sys.argv[4] )) # in case the client fails, we need to kill the server # or it will stay around time.sleep(20) try: os.kill(pid, 15) except: pass sys.exit(os.WEXITSTATUS(retVal))
""" Driver script for testing sockets Unix only """ import os, sys, time # Fork, run server in child, client in parent pid = os.fork() if pid == 0: # exec the parent os.execv(sys.argv[1], ('-D', sys.argv[3])) else: # wait a little to make sure that the server is ready time.sleep(10) # run the client retVal = os.system('%s -D %s -V %s' % ( sys.argv[2], sys.argv[3], sys.argv[4] )) # in case the client fails, we need to kill the server # or it will stay around time.sleep(20) os.kill(pid, 15) sys.exit(os.WEXITSTATUS(retVal))
Fix a bug discovered by Scrutinizer
<?php declare(strict_types=1); /** * This file is part of the Phootwork package. * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @license MIT License * @copyright Thomas Gossmann */ namespace phootwork\collection; use phootwork\lang\AbstractArray; /** * AbstractCollection providing implementation for the Collection interface. * * @author Thomas Gossmann */ abstract class AbstractCollection extends AbstractArray implements Collection { /** * Remove all elements from the collection. */ public function clear(): void { $this->array = []; } /** * @internal */ public function rewind() { return reset($this->array); } /** * @internal */ public function current() { return current($this->array); } /** * @internal */ public function key() { return key($this->array); } /** * @internal */ public function next() { return next($this->array); } /** * @internal */ public function valid(): bool { return key($this->array) !== null; } }
<?php declare(strict_types=1); /** * This file is part of the Phootwork package. * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @license MIT License * @copyright Thomas Gossmann */ namespace phootwork\collection; use phootwork\lang\AbstractArray; /** * AbstractCollection providing implementation for the Collection interface. * * @author Thomas Gossmann */ abstract class AbstractCollection extends AbstractArray implements Collection { /** * Remove all elements from the collection. */ public function clear(): void { $this->array = []; } /** * @internal */ public function rewind() { return reset($this->array); } /** * @internal */ public function current() { return current($this->array); } /** * @internal */ public function key(): int { return key($this->array); } /** * @internal */ public function next() { return next($this->array); } /** * @internal */ public function valid(): bool { return key($this->array) !== null; } }
Support for 'deed.pl' license URL.
# -*- coding: utf-8 -*- # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later. # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information. # from django.utils.translation import ugettext_lazy as _ LICENSES = { 'http://creativecommons.org/licenses/by-sa/3.0/': { 'icon': 'cc-by-sa', 'description': _('Creative Commons Attribution-ShareAlike 3.0 Unported'), }, } LICENSES['http://creativecommons.org/licenses/by-sa/3.0/deed.pl'] = \ LICENSES['http://creativecommons.org/licenses/by-sa/3.0/'] # Those will be generated only for books with own HTML. EBOOK_FORMATS_WITHOUT_CHILDREN = ['txt', 'fb2'] # Those will be generated for all books. EBOOK_FORMATS_WITH_CHILDREN = ['pdf', 'epub', 'mobi'] # Those will be generated when inherited cover changes. EBOOK_FORMATS_WITH_COVERS = ['pdf', 'epub', 'mobi'] EBOOK_FORMATS = EBOOK_FORMATS_WITHOUT_CHILDREN + EBOOK_FORMATS_WITH_CHILDREN
# -*- coding: utf-8 -*- # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later. # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information. # from django.utils.translation import ugettext_lazy as _ LICENSES = { 'http://creativecommons.org/licenses/by-sa/3.0/': { 'icon': 'cc-by-sa', 'description': _('Creative Commons Attribution-ShareAlike 3.0 Unported'), }, } # Those will be generated only for books with own HTML. EBOOK_FORMATS_WITHOUT_CHILDREN = ['txt', 'fb2'] # Those will be generated for all books. EBOOK_FORMATS_WITH_CHILDREN = ['pdf', 'epub', 'mobi'] # Those will be generated when inherited cover changes. EBOOK_FORMATS_WITH_COVERS = ['pdf', 'epub', 'mobi'] EBOOK_FORMATS = EBOOK_FORMATS_WITHOUT_CHILDREN + EBOOK_FORMATS_WITH_CHILDREN
Change parse errors to standard format.
# -*- coding: iso-8859-1 -*- from twisted.protocols.basic import Int32StringReceiver import json import apps class JSONProtocol(Int32StringReceiver): app = apps.LoginApp def connectionMade(self): self.app = self.__class__.app(self) def connectionLost(self, reason): self.app.disconnect(reason) def stringReceived(self, string): try: expr = json.loads(string) except: print 'Bad message received: %s' % string error = {'type': 'parse error'} error['args'] = {'message': string} self.send_json(error) return self.app.run(expr) def send_json(self, object): message = json.dumps(object) self.sendString(message)
# -*- coding: iso-8859-1 -*- from twisted.protocols.basic import Int32StringReceiver import json import apps class JSONProtocol(Int32StringReceiver): app = apps.LoginApp def connectionMade(self): self.app = self.__class__.app(self) def connectionLost(self, reason): self.app.disconnect(reason) def stringReceived(self, string): try: expr = json.loads(string) except: print 'Bad message received: %s' % string error = {'type': 'parse error'} error['message'] = string self.send_json(error) return self.app.run(expr) def send_json(self, object): message = json.dumps(object) self.sendString(message)
Test both all unique keys and common keys cases also redirect any `log` output to a file to keep the benchmarking stats clean
package storebench import ( "io/ioutil" "log" "os" "strconv" "testing" "github.com/skyec/astore" blobs "github.com/skyec/astore/testing" ) var benchStore astore.WriteableStore var benchDir string func init() { file, err := os.OpenFile("test.log", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) if err != nil { panic(err) } log.SetOutput(file) } func writeBench(b *testing.B, keyMod int) { benchDir, err := ioutil.TempDir("", "astore-benchmarking-") if err != nil { log.Fatal(err) } benchStore, err := astore.NewReadWriteableStore(benchDir) if err != nil { log.Fatal(err) } err = benchStore.Initialize() if err != nil { log.Fatal("Failed to initialze the store:", err) } blobs := blobs.GenerateBlobs(b.N) b.ResetTimer() for i := 0; i < len(blobs); i++ { err := benchStore.WriteToKey(strconv.Itoa(i%keyMod), blobs[i]) if err != nil { b.Fatal("Failed to write to store:", err) } } b.StopTimer() os.RemoveAll(benchDir) } func BenchmarkCommonKey10(b *testing.B) { writeBench(b, 10) } func BenchmarkUniqueKeys(b *testing.B) { writeBench(b, b.N) }
package storebench import ( "io/ioutil" "log" "os" "strconv" "testing" "github.com/skyec/astore" blobs "github.com/skyec/astore/testing" ) var benchStore astore.WriteableStore var benchDir string func init() { } func BenchmarkDefaultWrite(b *testing.B) { benchDir, err := ioutil.TempDir("", "astore-benchmarking-") if err != nil { log.Fatal(err) } benchStore, err := astore.NewReadWriteableStore(benchDir) if err != nil { log.Fatal(err) } err = benchStore.Initialize() if err != nil { log.Fatal("Failed to initialze the store:", err) } blobs := blobs.GenerateBlobs(b.N) b.ResetTimer() for i := 0; i < len(blobs); i++ { err := benchStore.WriteToKey(strconv.Itoa(i%10), blobs[i]) if err != nil { b.Fatal("Failed to write to store:", err) } } b.StopTimer() os.RemoveAll(benchDir) }
Remove import reference of "fmt" and "syscall".
// Copyright 2010 The W32 Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package w32 import ( "unicode/utf16" "unsafe" ) func MakeIntResource(id uint16) *uint16 { return (*uint16)(unsafe.Pointer(uintptr(id))) } func LOWORD(dw uint) uint16 { return uint16(dw) } func HIWORD(dw uint) uint16 { return uint16(dw >> 16 & 0xffff) } func BoolToBOOL(value bool) BOOL { if value { return 1 } return 0 } func UTF16PtrToString(cstr *uint16) string { if cstr != nil { us := make([]uint16, 0, 256) for p := uintptr(unsafe.Pointer(cstr)); ; p += 2 { u := *(*uint16)(unsafe.Pointer(p)) if u == 0 { return string(utf16.Decode(us)) } us = append(us, u) } } return "" }
// Copyright 2010 The W32 Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package w32 import ( "fmt" "syscall" "unicode/utf16" "unsafe" ) func MakeIntResource(id uint16) *uint16 { return (*uint16)(unsafe.Pointer(uintptr(id))) } func LOWORD(dw uint) uint16 { return uint16(dw) } func HIWORD(dw uint) uint16 { return uint16(dw >> 16 & 0xffff) } func BoolToBOOL(value bool) BOOL { if value { return 1 } return 0 } func UTF16PtrToString(cstr *uint16) string { if cstr != nil { us := make([]uint16, 0, 256) for p := uintptr(unsafe.Pointer(cstr)); ; p += 2 { u := *(*uint16)(unsafe.Pointer(p)) if u == 0 { return string(utf16.Decode(us)) } us = append(us, u) } } return "" }
Refactor to follow style guidelines
import Ember from 'ember'; /** * @module components * @class sl-span */ export default Ember.Component.extend({ // ------------------------------------------------------------------------- // Dependencies // ------------------------------------------------------------------------- // Attributes /** * The HTML tag name of the component * * @property {Ember.String} tagname * @default "span" */ tagName: 'span', // ------------------------------------------------------------------------- // Actions // ------------------------------------------------------------------------- // Events // ------------------------------------------------------------------------- // Properties /** * Whether to show the loading icon or content * * @property {boolean} isLoading * @default false */ isLoading: false // ------------------------------------------------------------------------- // Observers // ------------------------------------------------------------------------- // Methods });
import Ember from 'ember'; /** * @module components * @class sl-span */ export default Ember.Component.extend({ // ------------------------------------------------------------------------- // Dependencies // ------------------------------------------------------------------------- // Attributes /** * The HTML tag name of the component * * @property {string} tagname * @default "span" */ tagName: 'span', // ------------------------------------------------------------------------- // Actions // ------------------------------------------------------------------------- // Events // ------------------------------------------------------------------------- // Properties /** * Whether to show the loading icon or content * * @property {boolean} isLoading * @default false */ isLoading: false // ------------------------------------------------------------------------- // Observers // ------------------------------------------------------------------------- // Methods });
Add the RegExpRouter to the include path
<?php /** * This file parses the configuration and connection details for the catalog database. * * @package UNL_UCBCN * @author bbieber */ function autoload($class) { $class = str_replace(array('_', '\\'), '/', $class); include $class . '.php'; } spl_autoload_register('autoload'); set_include_path( __DIR__ . '/src' . PATH_SEPARATOR . __DIR__ . '/backend/src' . PATH_SEPARATOR . __DIR__ . '/vendor/php' . PATH_SEPARATOR . __DIR__ . '/vendor/unl_submodules/RegExpRouter/src' ); ini_set('display_errors', true); error_reporting(E_ALL); UNL\UCBCN\Frontend\Controller::$url = '/workspace/UNL_UCBCN_Frontend/www/'; UNL\UCBCN\ActiveRecord\Database::setDbSettings( array( 'host' => 'localhost', 'user' => 'events', 'password' => 'events', 'dbname' => 'events', ));
<?php /** * This file parses the configuration and connection details for the catalog database. * * @package UNL_UCBCN * @author bbieber */ function autoload($class) { $class = str_replace(array('_', '\\'), '/', $class); include $class . '.php'; } spl_autoload_register('autoload'); set_include_path( __DIR__ . '/src' . PATH_SEPARATOR . __DIR__ . '/backend/src' . PATH_SEPARATOR . __DIR__ . '/vendor/php' ); ini_set('display_errors', true); error_reporting(E_ALL); UNL\UCBCN\Frontend\Controller::$url = '/workspace/UNL_UCBCN_Frontend/www/'; UNL\UCBCN\ActiveRecord\Database::setDbSettings( array( 'host' => 'localhost', 'user' => 'events', 'password' => 'events', 'dbname' => 'events', ));
Add header to petition response
import React from 'react'; import styles from './petition-response.scss'; import settings from 'settings'; import Heading2 from 'components/Heading2'; import Paragraph from 'components/Paragraph'; import MarkdownParagraph from 'components/MarkdownParagraph'; import Icon from 'components/Icon'; const PetitionResponse = ({ cityResponse }) => { if (!cityResponse.text) { return null; } return ( <article className={styles.root} id='response'> <header className={styles.top}> <span className={styles.icon}> <Icon id='Note' size='small' /> </span> <Heading2 text={settings.petitionPage.cityResponse} /> </header> <MarkdownParagraph text={cityResponse.text} /> <Paragraph text={cityResponse.name} /> </article> ); }; export default PetitionResponse;
import React from 'react'; import styles from './petition-response.scss'; import settings from 'settings'; import Heading2 from 'components/Heading2'; import Paragraph from 'components/Paragraph'; import MarkdownParagraph from 'components/MarkdownParagraph'; import Icon from 'components/Icon'; const PetitionResponse = ({ cityResponse }) => { if (!cityResponse.text) { return null; } return ( <article className={styles.root} id='response'> <div className={styles.top}> <span className={styles.icon}> <Icon id='Note' size='small' /> </span> <Heading2 text={settings.petitionPage.cityResponse} /> </div> <MarkdownParagraph text={cityResponse.text} /> <Paragraph text={cityResponse.name} /> </article> ); }; export default PetitionResponse;
Fix comments for beta spec language
"""ResourceSync Resource Container object Both ResourceList and ChangeList objects are collections of Resource objects with additional metadata regarding capabilities and discovery information. This is a superclass for the ResourceList and ChangeList classes which contains common functionality. """ class ResourceContainer(object): """Class containing resource-like objects Core functionality:: - resources property that is the set/list of resources -- add() to add a resource-like object to self.resources -- iter() to get iterator over self.resource in appropriate order - capabilities property that is a dict of capabilities Derived classes may add extra functionality such as len() etc.. However, any code designed to work with any ResourceContainer should use only the core functionality. """ def __init__(self, resources=None, capabilities=None): self.resources=resources self.capabilities=(capabilities if (capabilities is not None) else {}) def __iter__(self): """Iterator over all the resources in this resourcelist Baseline implementation use iterator given by resources property """ return(iter(self.resources)) def add(self, resource): """Add a resource or an iterable collection of resources to this container Must be implemented in derived class """ raise NotImplemented("add() not implemented") def __str__(self): """Return string of all resources in order given by interator""" s = '' for resource in self: s += str(resource) + "\n" return(s)
"""ResourceSync Resource Container object Both ResourceList and Change Set objects are collections of Resource objects with additional metadata regarding capabilities and discovery information. This is a superclass for the ResourceList and ChangeSet classes which contains common functionality. """ class ResourceContainer(object): """Class containing resource-like objects Core functionality:: - resources property that is the set/list of resources -- add() to add a resource-like object to self.resources -- iter() to get iterator over self.resource in appropriate order - capabilities property that is a dict of capabilities Derived classes may add extra functionality such as len() etc.. However, any code designed to work with any ResourceContainer should use only the core functionality. """ def __init__(self, resources=None, capabilities=None): self.resources=resources self.capabilities=(capabilities if (capabilities is not None) else {}) def __iter__(self): """Iterator over all the resources in this resourcelist Baseline implementation use iterator given by resources property """ return(iter(self.resources)) def add(self, resource): """Add a resource or an iterable collection of resources to this container Must be implemented in derived class """ raise NotImplemented("add() not implemented") def __str__(self): """Return string of all resources in order given by interator""" s = '' for resource in self: s += str(resource) + "\n" return(s)
Add common predicate for can_vote
from secretballot.models import Vote from likes.signals import likes_enabled_test, can_vote_test from likes.exceptions import LikesNotEnabledException, CannotVoteException def _votes_enabled(obj): """See if voting is enabled on the class. Made complicated because secretballot.enable_voting_on takes parameters to set attribute names, so we can't safely check for eg. "add_vote" presence on obj. The safest bet is to check for the 'votes' attribute. The correct approach is to contact the secretballot developers and ask them to set some unique marker on a class that can be voted on.""" return hasattr(obj.__class__, 'votes') def likes_enabled(obj, request): if not _votes_enabled(obj): return False, None try: likes_enabled_test.send(obj, request=request) except LikesNotEnabledException: return False return True def can_vote(obj, user, request): if not _votes_enabled(obj): return False # Common predicate if Vote.objects.filter( object_id=modelbase_obj.id, token=request.secretballot_token ).count() != 0: return False try: can_vote_test.send(obj, user=user, request=request) except CannotVoteException: return False return True
from likes.signals import likes_enabled_test, can_vote_test from likes.exceptions import LikesNotEnabledException, CannotVoteException def _votes_enabled(obj): """See if voting is enabled on the class. Made complicated because secretballot.enable_voting_on takes parameters to set attribute names, so we can't safely check for eg. "add_vote" presence on obj. The safest bet is to check for the 'votes' attribute. The correct approach is to contact the secretballot developers and ask them to set some unique marker on a class that can be voted on.""" return hasattr(obj.__class__, 'votes') def likes_enabled(obj, request): if not _votes_enabled(obj): return False, None try: likes_enabled_test.send(obj, request=request) except LikesNotEnabledException: return False return True def can_vote(obj, user, request): if not _votes_enabled(obj): return False try: can_vote_test.send(obj, user=user, request=request) except CannotVoteException: return False return True
Fix export syntax that is tripping compilation up for some reason
export { default } from 'codemirror'; import 'codemirror/lib/codemirror.css'; import 'codemirror/addon/hint/show-hint.css'; import 'codemirror/addon/hint/show-hint'; import 'codemirror/addon/comment/comment'; import 'codemirror/addon/edit/matchbrackets'; import 'codemirror/addon/edit/closebrackets'; import 'codemirror/addon/search/search'; import 'codemirror/addon/search/searchcursor'; import 'codemirror/addon/search/jump-to-line'; import 'codemirror/addon/dialog/dialog.css'; import 'codemirror/addon/dialog/dialog'; import 'codemirror/addon/lint/lint'; import 'codemirror/addon/lint/lint.css'; import 'codemirror/keymap/sublime'; import 'codemirror-graphql/results/mode'; import 'codemirror-graphql/hint'; import 'codemirror-graphql/lint'; import 'codemirror-graphql/mode';
export default from 'codemirror'; import 'codemirror/lib/codemirror.css'; import 'codemirror/addon/hint/show-hint.css'; import 'codemirror/addon/hint/show-hint'; import 'codemirror/addon/comment/comment'; import 'codemirror/addon/edit/matchbrackets'; import 'codemirror/addon/edit/closebrackets'; import 'codemirror/addon/search/search'; import 'codemirror/addon/search/searchcursor'; import 'codemirror/addon/search/jump-to-line'; import 'codemirror/addon/dialog/dialog.css'; import 'codemirror/addon/dialog/dialog'; import 'codemirror/addon/lint/lint'; import 'codemirror/addon/lint/lint.css'; import 'codemirror/keymap/sublime'; import 'codemirror-graphql/results/mode'; import 'codemirror-graphql/hint'; import 'codemirror-graphql/lint'; import 'codemirror-graphql/mode';
Make implementation compatible with PHP 5.3
<?php namespace Eluceo\iCal\Property; class ArrayValue implements ValueInterface { /** * The value. * * @var array */ protected $values; public function __construct($values) { $this->values = $values; } public function setValues($values) { $this->values = $values; return $this; } public function getEscapedValue() { $escapedValues = array_map(function ($value) { return (new StringValue($value))->getEscapedValue(); }, $this->values); return implode(',', $escapedValues); } }
<?php namespace Eluceo\iCal\Property; class ArrayValue implements ValueInterface { /** * The value. * * @var array */ protected $values; public function __construct(array $values) { $this->values = $values; } public function setValues(array $values) { $this->values = $values; return $this; } public function getEscapedValue() { $escapedValues = array_map(function ($value) { return (new StringValue($value))->getEscapedValue(); }, $this->values); return implode(',', $escapedValues); } }
Use created for ordering and date_hierarchy in ReactionAdmin.
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from .models import Reaction class ReactionAdmin(admin.ModelAdmin): fieldsets = ( (None, { 'fields': ('content_type', 'object_pk'), }), (_('Content'), { 'fields': ('author', 'editor', 'reaction'), }), (_('Metadata'), { 'fields': ('deleted', 'ip_address'), }), ) list_display = ('author_full_name', 'content_type', 'object_pk', 'ip_address', 'created', 'updated', 'deleted') list_filter = ('created', 'updated', 'deleted') date_hierarchy = 'created' ordering = ('-created',) raw_id_fields = ('author', 'editor') search_fields = ('reaction', 'author__username', 'author__email', 'author__first_name', 'author__last_name', 'ip_address') def author_full_name(self, obj): full_name = obj.author.get_full_name() if not full_name: return obj.author.username else: return full_name author_full_name.short_description = _('Author') admin.site.register(Reaction, ReactionAdmin)
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from .models import Reaction class ReactionAdmin(admin.ModelAdmin): fieldsets = ( (None, { 'fields': ('content_type', 'object_pk'), }), (_('Content'), { 'fields': ('author', 'editor', 'reaction'), }), (_('Metadata'), { 'fields': ('deleted', 'ip_address'), }), ) list_display = ('author_full_name', 'content_type', 'object_pk', 'ip_address', 'created', 'updated', 'deleted') list_filter = ('created', 'updated', 'deleted') date_hierarchy = 'updated' ordering = ('-updated',) raw_id_fields = ('author', 'editor') search_fields = ('reaction', 'author__username', 'author__email', 'author__first_name', 'author__last_name', 'ip_address') def author_full_name(self, obj): full_name = obj.author.get_full_name() if not full_name: return obj.author.username else: return full_name author_full_name.short_description = _('Author') admin.site.register(Reaction, ReactionAdmin)
Allow no return from run
"use strict"; const runall = async function(commands, state, model) { for (let idx = 0 ; idx != commands.length ; ++idx) { const cm = commands[idx]; if (cm.command.check(model)) { cm.hasStarted = true; try { const status = await cm.command.run(state, model); if (status !== undefined && !status) { return false; } } catch(e) { return false; } } } return true; }; const runner = function(warmup, teardown) { return async function(seed, commands) { const {state, model} = await warmup(seed); const result = await runall(commands, state, model); await teardown(state, model); return result; }; }; module.exports = { runner: runner };
"use strict"; const runall = async function(commands, state, model) { for (let idx = 0 ; idx != commands.length ; ++idx) { const cm = commands[idx]; if (cm.command.check(model)) { cm.hasStarted = true; try { if (! await cm.command.run(state, model)) { return false; } } catch(e) { return false; } } } return true; }; const runner = function(warmup, teardown) { return async function(seed, commands) { const {state, model} = await warmup(seed); const result = await runall(commands, state, model); await teardown(state, model); return result; }; }; module.exports = { runner: runner };
Fix return value of list_files
import os from os import listdir from django.conf import settings def handle_uploaded_file(f, title, user): targetdir = 'uploads/' + user.__str__() + '/incoming/' if not os.path.exists(targetdir): os.makedirs(targetdir) with open(targetdir + title, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) def user_is_admin(user): return user.is_superuser def is_admin(request): return request.user.is_superuser def list_files(account, mode): targetdir = os.path.join('uploads', account.username, mode) if os.path.exists(targetdir): return [f for f in listdir(targetdir)] else: return None def create_user_uploads(user): userdir = os.path.join(settings.MEDIA_ROOT, user.username) if not os.path.exists(userdir): incoming = os.path.join(userdir, 'incoming') outgoing = os.path.join(userdir, 'outgoing') # TODO: Fix perms? os.makedirs(incoming) os.chmod(incoming, 0777) os.makedirs(outgoing) os.chmod(outgoing, 0777)
import os from os import listdir from django.conf import settings def handle_uploaded_file(f, title, user): targetdir = 'uploads/' + user.__str__() + '/incoming/' if not os.path.exists(targetdir): os.makedirs(targetdir) with open(targetdir + title, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) def user_is_admin(user): return user.is_superuser def is_admin(request): return request.user.is_superuser def list_files(account, mode): targetdir = os.path.join('uploads', account.username, mode) if os.path.exists(targetdir): return [f for f in listdir(targetdir)] else: return False def create_user_uploads(user): userdir = os.path.join(settings.MEDIA_ROOT, user.username) if not os.path.exists(userdir): incoming = os.path.join(userdir, 'incoming') outgoing = os.path.join(userdir, 'outgoing') # TODO: Fix perms? os.makedirs(incoming) os.chmod(incoming, 0777) os.makedirs(outgoing) os.chmod(outgoing, 0777)