text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Put things in in alphabetical order.
""" The FVCOM Python toolbox (PyFVCOM) """ __version__ = '1.6.2' __author__ = 'Pierre Cazenave' __credits__ = ['Pierre Cazenave'] __license__ = 'MIT' __maintainer__ = 'Pierre Cazenave' __email__ = 'pica@pml.ac.uk' import inspect from warnings import warn # Import everything! from PyFVCOM import buoy_tools from PyFVCOM import cst_tools from PyFVCOM import ctd_tools from PyFVCOM import current_tools from PyFVCOM import grid_tools from PyFVCOM import ll2utm from PyFVCOM import ll2utm as coordinate_tools from PyFVCOM import ocean_tools from PyFVCOM import stats_tools from PyFVCOM import tidal_ellipse from PyFVCOM import tide_tools from PyFVCOM import process_results from PyFVCOM import read_results from PyFVCOM import plot from PyFVCOM import utilities
""" The FVCOM Python toolbox (PyFVCOM) """ __version__ = '1.6.2' __author__ = 'Pierre Cazenave' __credits__ = ['Pierre Cazenave'] __license__ = 'MIT' __maintainer__ = 'Pierre Cazenave' __email__ = 'pica@pml.ac.uk' import inspect from warnings import warn # Import everything! from PyFVCOM import buoy_tools from PyFVCOM import cst_tools from PyFVCOM import ctd_tools from PyFVCOM import current_tools from PyFVCOM import grid_tools from PyFVCOM import ll2utm from PyFVCOM import ll2utm as coordinate_tools from PyFVCOM import ocean_tools from PyFVCOM import stats_tools from PyFVCOM import tide_tools from PyFVCOM import tidal_ellipse from PyFVCOM import process_results from PyFVCOM import read_results from PyFVCOM import plot from PyFVCOM import utilities
[PeasDemo] Fix a typo in the python plugin. It was indicating "do_activate" in the console when actually deactivating the plugin.
# -*- coding: utf-8 -*- # ex:set ts=4 et sw=4 ai: import gobject import libpeas import gtk LABEL_STRING="Python Says Hello!" class PythonHelloPlugin(libpeas.Plugin): def do_activate(self, window): print "PythonHelloPlugin.do_activate", repr(window) window._pythonhello_label = gtk.Label(LABEL_STRING) window._pythonhello_label.show() window.get_child().pack_start(window._pythonhello_label) def do_deactivate(self, window): print "PythonHelloPlugin.do_deactivate", repr(window) window.get_child().remove(window._pythonhello_label) window._pythonhello_label.destroy() gobject.type_register(PythonHelloPlugin)
# -*- coding: utf-8 -*- # ex:set ts=4 et sw=4 ai: import gobject import libpeas import gtk LABEL_STRING="Python Says Hello!" class PythonHelloPlugin(libpeas.Plugin): def do_activate(self, window): print "PythonHelloPlugin.do_activate", repr(window) window._pythonhello_label = gtk.Label(LABEL_STRING) window._pythonhello_label.show() window.get_child().pack_start(window._pythonhello_label) def do_deactivate(self, window): print "PythonHelloPlugin.do_activate", repr(window) window.get_child().remove(window._pythonhello_label) window._pythonhello_label.destroy() gobject.type_register(PythonHelloPlugin)
Fix Analytics link in the footer.
/** * Footer component of the ModulePopularPagesWidget widget. * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * WordPress dependencies */ import { _x } from '@wordpress/i18n'; /** * Internal dependencies */ import Data from 'googlesitekit-data'; import { MODULES_ANALYTICS } from '../../../datastore/constants'; import SourceLink from '../../../../../components/SourceLink'; const { useSelect } = Data; export default function Footer() { const contentPagesURL = useSelect( ( select ) => select( MODULES_ANALYTICS ).getServiceReportURL( 'content-pages' ) ); return ( <SourceLink href={ contentPagesURL } name={ _x( 'Analytics', 'Service name', 'google-site-kit' ) } external /> ); }
/** * Footer component of the ModulePopularPagesWidget widget. * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * WordPress dependencies */ import { _x } from '@wordpress/i18n'; /** * Internal dependencies */ import Data from 'googlesitekit-data'; import { MODULES_ANALYTICS } from '../../../datastore/constants'; import SourceLink from '../../../../../components/SourceLink'; const { useSelect } = Data; export default function Footer() { const visitorsOverview = useSelect( ( select ) => select( MODULES_ANALYTICS ).getServiceReportURL( 'visitors-overview' ) ); return ( <SourceLink href={ visitorsOverview } name={ _x( 'Analytics', 'Service name', 'google-site-kit' ) } external /> ); }
Increment version. New in 1.3: Linux binaries are properly included
from setuptools import setup, find_packages import sys if sys.version_info.major != 3: raise RuntimeError("PhenoGraph requires Python 3") setup( name="PhenoGraph", description="Graph-based clustering for high-dimensional single-cell data", version="1.3", author="Jacob Levine", author_email="jl3545@columbia.edu", packages=find_packages(), package_data={ '': ['louvain/*convert*', 'louvain/*community*', 'louvain/*hierarchy*'] }, include_package_data=True, zip_safe=False, url="https://github.com/jacoblevine/PhenoGraph", license="LICENSE", long_description=open("README.md").read(), install_requires=open("requirements.txt").read() )
from setuptools import setup, find_packages import sys if sys.version_info.major != 3: raise RuntimeError("PhenoGraph requires Python 3") setup( name="PhenoGraph", description="Graph-based clustering for high-dimensional single-cell data", version="1.2", author="Jacob Levine", author_email="jl3545@columbia.edu", packages=find_packages(), package_data={ '': ['louvain/*convert*', 'louvain/*community*', 'louvain/*hierarchy*'] }, include_package_data=True, zip_safe=False, url="https://github.com/jacoblevine/PhenoGraph", license="LICENSE", long_description=open("README.md").read(), install_requires=open("requirements.txt").read() )
Fix issues found by SonarCloud
package nl.homeserver.energie; import java.math.BigDecimal; import java.util.Collection; import java.util.Objects; import javax.annotation.Nullable; class VerbruikenEnKosten { private final Collection<VerbruikKosten> all; VerbruikenEnKosten(final Collection<VerbruikKosten> all) { this.all = all; } @Nullable private BigDecimal getTotaalVerbruik() { return all.stream() .map(VerbruikKosten::getVerbruik) .filter(Objects::nonNull) .reduce(BigDecimal::add) .orElse(null); } @Nullable private BigDecimal getTotaalKosten() { return all.stream() .map(VerbruikKosten::getKosten) .filter(Objects::nonNull) .reduce(BigDecimal::add) .orElse(null); } VerbruikKosten sumToSingle() { return new VerbruikKosten(getTotaalVerbruik(), getTotaalKosten()); } }
package nl.homeserver.energie; import java.math.BigDecimal; import java.util.Collection; import java.util.Objects; public class VerbruikenEnKosten { private final Collection<VerbruikKosten> all; public VerbruikenEnKosten(final Collection<VerbruikKosten> all) { this.all = all; } private BigDecimal getTotaalVerbruik() { return all.stream() .map(VerbruikKosten::getVerbruik) .filter(Objects::nonNull) .reduce(BigDecimal::add) .orElse(null); } private BigDecimal getTotaalKosten() { return all.stream() .map(VerbruikKosten::getKosten) .filter(Objects::nonNull) .reduce(BigDecimal::add) .orElse(null); } public VerbruikKosten sumToSingle() { return new VerbruikKosten(getTotaalVerbruik(), getTotaalKosten()); } }
Set abstract test to abstract
<?php namespace MS\PHPMD\Tests\Functional; use Symfony\Component\Process\ProcessBuilder; use Symfony\Component\Process\Process; /** * Class AbstractProcessTest * * @package MS\PHPMD\Tests\Functional */ abstract class AbstractProcessTest extends \PHPUnit_Framework_TestCase { /** * @param $filename * @param $ruleset * * @return Process */ protected function runPhpmd($filename, $ruleset) { $processBuilder = new ProcessBuilder(); $processBuilder->setPrefix(__DIR__ . '/../../vendor/bin/phpmd'); $processBuilder ->add(__DIR__ . '/../Fixtures/' . $filename) ->add('text') ->add(__DIR__ . '/../../Rulesets/' . $ruleset); $process = $processBuilder->getProcess(); $process->run(); return $process; } }
<?php namespace MS\PHPMD\Tests\Functional; use Symfony\Component\Process\ProcessBuilder; use Symfony\Component\Process\Process; /** * Class AbstractProcessTest * * @package MS\PHPMD\Tests\Functional */ class AbstractProcessTest extends \PHPUnit_Framework_TestCase { /** * @param $filename * @param $ruleset * * @return Process */ protected function runPhpmd($filename, $ruleset) { $processBuilder = new ProcessBuilder(); $processBuilder->setPrefix(__DIR__ . '/../../vendor/bin/phpmd'); $processBuilder ->add(__DIR__ . '/../Fixtures/' . $filename) ->add('text') ->add(__DIR__ . '/../../Rulesets/' . $ruleset); $process = $processBuilder->getProcess(); $process->run(); return $process; } }
Use filesGlob from tsconfig in gulp file
var gulp = require('gulp'); var tslint = require('gulp-tslint'); var exec = require('child_process').exec; var jasmine = require('gulp-jasmine'); var gulp = require('gulp-help')(gulp); var tsFilesGlob = (function(c) { return c.filesGlob || c.files || '**/*.ts'; })(require('./tsconfig.json')); gulp.task('tslint', 'Lints all TypeScript source files', function(){ return gulp.src(tsFilesGlob) .pipe(tslint()) .pipe(tslint.report('verbose')); }); gulp.task('build', 'Compiles all TypeScript source files', function (cb) { exec('tsc', function (err, stdout, stderr) { console.log(stdout); console.log(stderr); cb(err); }); }); gulp.task('test', 'Runs the Jasmine test specs', ['build'], function () { return gulp.src('test/*.js') .pipe(jasmine()); });
var gulp = require('gulp'); var tslint = require('gulp-tslint'); var exec = require('child_process').exec; var jasmine = require('gulp-jasmine'); var gulp = require('gulp-help')(gulp); gulp.task('tslint', 'Lints all TypeScript source files', function(){ return gulp.src('src/**/*.ts') .pipe(tslint()) .pipe(tslint.report('verbose')); }); gulp.task('build', 'Compiles all TypeScript source files', function (cb) { exec('tsc', function (err, stdout, stderr) { console.log(stdout); console.log(stderr); cb(err); }); }); gulp.task('test', 'Runs the Jasmine test specs', ['build'], function () { return gulp.src('test/*.js') .pipe(jasmine()); });
[AC-4764] Switch from "history" to "results" in the history API calls
# MIT License # Copyright (c) 2017 MassChallenge, Inc. from rest_framework.response import Response from rest_framework.views import APIView from impact.permissions import ( V1APIPermissions, ) from impact.v1.metadata import ImpactMetadata class BaseHistoryView(APIView): metadata_class = ImpactMetadata permission_classes = ( V1APIPermissions, ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def get(self, request, pk): self.instance = self.model.objects.get(pk=pk) events = [] for event_class in self.event_classes: events = events + event_class.events(self.instance) result = { "results": sorted([event.serialize() for event in events], key=lambda e: e["datetime"]) } return Response(result)
# MIT License # Copyright (c) 2017 MassChallenge, Inc. from rest_framework.response import Response from rest_framework.views import APIView from impact.permissions import ( V1APIPermissions, ) from impact.v1.metadata import ImpactMetadata class BaseHistoryView(APIView): metadata_class = ImpactMetadata permission_classes = ( V1APIPermissions, ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def get(self, request, pk): self.instance = self.model.objects.get(pk=pk) events = [] for event_class in self.event_classes: events = events + event_class.events(self.instance) result = { "history": sorted([event.serialize() for event in events], key=lambda e: e["datetime"]) } return Response(result)
Add missing event listener for new overrides While rolling the test code for creating overrides into the base code, we remembered to make sure that we put the event handler used to handle override creation in place but forgot to export them to to the base plugin so that it would actually do something.
from ..override_audit import reload reload("src", ["core", "events", "contexts", "browse", "settings_proxy"]) reload("src.commands") from . import core from .core import * from .events import * from .contexts import * from .settings_proxy import * from .commands import * __all__ = [ # core "core", # browse "browse", # settings_proxy "OverrideAuditOpenFileCommand", "OverrideAuditEditSettingsCommand", # events/contexts "OverrideAuditEventListener", "CreateOverrideEventListener", "OverrideAuditContextListener", # commands/* "OverrideAuditPackageReportCommand", "OverrideAuditOverrideReportCommand", "OverrideAuditDiffReportCommand", "OverrideAuditRefreshReportCommand", "OverrideAuditToggleOverrideCommand", "OverrideAuditCreateOverrideCommand", "OverrideAuditDiffOverrideCommand", "OverrideAuditRevertOverrideCommand", "OverrideAuditDiffExternallyCommand", "OverrideAuditEditOverrideCommand", "OverrideAuditDeleteOverrideCommand", "OverrideAuditFreshenOverrideCommand", "OverrideAuditDiffPackageCommand", "OverrideAuditFreshenPackageCommand", "OverrideAuditDiffSingleCommand", "OverrideAuditModifyMarkCommand" ]
from ..override_audit import reload reload("src", ["core", "events", "contexts", "browse", "settings_proxy"]) reload("src.commands") from . import core from .core import * from .events import * from .contexts import * from .settings_proxy import * from .commands import * __all__ = [ # core "core", # browse "browse", # settings_proxy "OverrideAuditOpenFileCommand", "OverrideAuditEditSettingsCommand", # events/contexts "OverrideAuditEventListener", "OverrideAuditContextListener", # commands/* "OverrideAuditPackageReportCommand", "OverrideAuditOverrideReportCommand", "OverrideAuditDiffReportCommand", "OverrideAuditRefreshReportCommand", "OverrideAuditToggleOverrideCommand", "OverrideAuditCreateOverrideCommand", "OverrideAuditDiffOverrideCommand", "OverrideAuditRevertOverrideCommand", "OverrideAuditDiffExternallyCommand", "OverrideAuditEditOverrideCommand", "OverrideAuditDeleteOverrideCommand", "OverrideAuditFreshenOverrideCommand", "OverrideAuditDiffPackageCommand", "OverrideAuditFreshenPackageCommand", "OverrideAuditDiffSingleCommand", "OverrideAuditModifyMarkCommand" ]
Fix spelling error in file header.
/** * Utility to have the page wait for a given length. * * Site Kit by Google, Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ export const E2E_PAGE_WAIT = 250; /** * Set the page to wait for the passed time. Defaults to 250 milliseconds. * * @since 1.10.0 * * @param {number} [delay] Optional. The amount of milliseconds to wait. */ export const pageWait = async ( delay = E2E_PAGE_WAIT ) => { if ( typeof delay !== 'number' ) { throw new Error( 'pageWait requires a number to be passed.' ); } await page.waitFor( delay ); };
/** * Utlity to have the page wait for a given length. * * Site Kit by Google, Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ export const E2E_PAGE_WAIT = 250; /** * Set the page to wait for the passed time. Defaults to 250 milliseconds. * * @since 1.10.0 * * @param {number} [delay] Optional. The amount of milliseconds to wait. */ export const pageWait = async ( delay = E2E_PAGE_WAIT ) => { if ( typeof delay !== 'number' ) { throw new Error( 'pageWait requires a number to be passed.' ); } await page.waitFor( delay ); };
Fix an typo error in test
from ev3.ev3dev import LegoSensor import unittest from util import get_input import glob class TestLegoSensor(unittest.TestCase): def test_LegoSensor(self): get_input('Attach a Lego on port 1 then continue') d = LegoSensor(port=1) print(d.mode) print(d.port) if (len(glob.glob('/sys/class/lego-sensor/sensor*/name')) >0): name = d.name print(name) d = LegoSensor(name=name) print(d.mode) print(d.port) if __name__ == '__main__': unittest.main()
from ev3.ev3dev import LegoSensor import unittest from util import get_input import glob class TestLegoSensor(unittest.TestCase): def test_LegoSensor(self): get_input('Attach a Msensor on port 1 then continue') d = LegoSensor(port=1) print(d.mode) print(d.port) if (len(glob.glob('/sys/class/lego-sensor/sensor*/name')) >0): name = d.name print(name) d = LegoSensor(name=name) print(d.mode) print(d.port) if __name__ == '__main__': unittest.main()
Hide form if signed in
<div class="page-header"> <div class="container"> <h1>Välkommen till Chalmers IT:s Autentiseringssystem!</h1> </div> </div> <div class="row"> <div class="col-lg-4"> <p></p> </div> <?php if (!is_signed_in()): ?> <div class="col-lg-5 col-lg-offset-3"> <form role="form" class="form-horizontal" method="post" action="/auth/login.php"> <?php form_control("username", "CID", "input", "user", true); form_control("password", "Lösenord", "password", "lock"); ?> <div class="form-group"> <div class="col-lg-offset-2 col-lg-10"> <button type="submit" class="btn btn-primary" name="intent" value="login">Logga in</button> </div> </div> </form> </div> <?php endif; ?> </div>
<div class="page-header"> <div class="container"> <h1>Välkommen till Chalmers IT:s Autentiseringssystem!</h1> </div> </div> <div class="row"> <div class="col-lg-4"> <p></p> </div> <div class="col-lg-5 col-lg-offset-3"> <form role="form" class="form-horizontal" method="post" action="/auth/login.php"> <?php form_control("username", "CID", "input", "user", true); form_control("password", "Lösenord", "password", "lock"); ?> <div class="form-group"> <div class="col-lg-offset-2 col-lg-10"> <button type="submit" class="btn btn-primary" name="intent" value="login">Logga in</button> </div> </div> </form> </div> </div>
Use increments() instead of id() for users.id column
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->rememberToken(); $table->timestamps(); $table->engine = 'InnoDB'; }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('users'); } }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->id('id'); $table->string('name'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->rememberToken(); $table->timestamps(); $table->engine = 'InnoDB'; }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('users'); } }
Allow for different execution modes between the sys and app domains.
var AVM2 = (function () { function AVM2(builtinABC, sysMode, appMode) { if (!builtinABC) { throw new Error("Cannot initialize AVM2 without builtin.abc"); } var sysDomain = new Domain(null, sysMode, true); sysDomain.executeAbc(new AbcFile(builtinABC), "builtin.abc"); // TODO: this will change when we implement security domains. this.systemDomain = sysDomain; this.applicationDomain = new Domain(sysDomain, appMode, false); } AVM2.prototype = { loadPlayerGlobal: function (playerGlobalSWF) { var sysDomain = this.systemDomain; // Load, but don't execute, the default player globals. Timer.start("Load Player Globals"); SWF.parse(playerGlobalSWF, { oncomplete: function(result) { var tags = result.tags; for (var i = 0, n = tags.length; i < n; i++) { var tag = tags[i]; if (tag.type === "abc") { sysDomain.loadAbc(new AbcFile(tag.data, "playerGlobal/library" + i + ".abc")); } } } }); Timer.stop(); } }; return AVM2; })();
var AVM2 = (function () { function AVM2(builtinABC, mode) { if (!builtinABC) { throw new Error("Cannot initialize AVM2 without builtin.abc"); } var sysDomain = new Domain(null, mode, true); sysDomain.executeAbc(new AbcFile(builtinABC), "builtin.abc"); // TODO: this will change when we implement security domains. this.systemDomain = sysDomain; this.applicationDomain = new Domain(sysDomain, mode, false); } AVM2.prototype = { loadPlayerGlobal: function (playerGlobalSWF) { var sysDomain = this.systemDomain; // Load, but don't execute, the default player globals. Timer.start("Load Player Globals"); SWF.parse(playerGlobalSWF, { oncomplete: function(result) { var tags = result.tags; for (var i = 0, n = tags.length; i < n; i++) { var tag = tags[i]; if (tag.type === "abc") { sysDomain.loadAbc(new AbcFile(tag.data, "playerGlobal/library" + i + ".abc")); } } } }); Timer.stop(); } }; return AVM2; })();
Add more comment for explain the code
'use strict' // let plusES5 = function(a, b){ // console.log("A:", a, ", B:", b); // let result = a + b; // return result; // }; // console.log(plusES5(9,10)); // ES6 style (arrow function) // let plusES6 = (a,b) => { // console.log("A:", a, ", B:", b); // let result = a + b; // return result; // } // console.log(plusES6(9,10)); // Arrow function with one parameter // let hello = (name) => { // console.log("Hi,", name); // } // let hello = name => { // console.log("Hi,", name); // } // hello("Pon"); // Arrow function wihtout parameter // let hiES6 = () => { // console.log('Hi, ES6'); // } // If there's only 1 statement in function, you can do this. // let hiES6 = () => console.log("Hi, ES6"); // hiES6(); // let hiES6 = () => { return "Hi, ES6" }; // console.log(hiES6());
'use strict' // let plusES5 = function(a, b){ // console.log("A:", a, ", B:", b); // let result = a + b; // return result; // }; // console.log(plusES5(9,10)); // ES6 style (arrow function) // let plusES6 = (a,b) => { // console.log("A:", a, ", B:", b); // let result = a + b; // return result; // } // console.log(plusES6(9,10)); // Arrow function with one parameter // let hello = (name) => { // console.log("Hi,", name); // } // let hello = name => { // console.log("Hi,", name); // } // hello("Pon"); // Arrow function wihtout parameter // let hiES6 = () => { // console.log('Hi, ES6'); // } // let hiES6 = () => console.log("Hi, ES6"); // hiES6(); // let hiES6 = () => { return "Hi, ES6" }; // console.log(hiES6());
Extend Service instead of Object for services It's for removing following deprecation warning in Ember.js 1.13 ``` DEPRECATION: In Ember 2.0 service factories must have an `isServiceFactory` property set to true. You registered (unknown mixin) as a service factory. Either add the `isServiceFactory` property to this factory or extend from Ember.Service. ```
import Ember from 'ember'; export default Ember.Service.extend({ onAjaxComplete: function() { var _this = this; this.fetchToken(); Ember.$(document).on("ajaxComplete", function(event, xhr, settings) { var csrf_param = xhr.getResponseHeader('X-CSRF-Param'), csrf_token = xhr.getResponseHeader('X-CSRF-Token'); if (csrf_param && csrf_token) { _this.setData({csrf_param: csrf_token}); } }); }.on('init'), setPrefilter: function() { var token = this.get('data').token; var preFilter = function(options, originalOptions, jqXHR) { return jqXHR.setRequestHeader('X-CSRF-Token', token ); }; $.ajaxPrefilter(preFilter); }, setData: function(data) { var param = Ember.keys(data)[0]; this.set('data', { param: param, token: data[param] }); this.setPrefilter(); return this.get('data'); }, fetchToken: function() { var _this = this; var token = Ember.$('meta[name="csrf-token"]').attr('content') || ''; return Ember.RSVP.resolve().then(function() { return _this.setData({'authenticity_token': token }); }); } });
import Ember from 'ember'; export default Ember.Object.extend({ onAjaxComplete: function() { var _this = this; this.fetchToken(); Ember.$(document).on("ajaxComplete", function(event, xhr, settings) { var csrf_param = xhr.getResponseHeader('X-CSRF-Param'), csrf_token = xhr.getResponseHeader('X-CSRF-Token'); if (csrf_param && csrf_token) { _this.setData({csrf_param: csrf_token}); } }); }.on('init'), setPrefilter: function() { var token = this.get('data').token; var preFilter = function(options, originalOptions, jqXHR) { return jqXHR.setRequestHeader('X-CSRF-Token', token ); }; $.ajaxPrefilter(preFilter); }, setData: function(data) { var param = Ember.keys(data)[0]; this.set('data', { param: param, token: data[param] }); this.setPrefilter(); return this.get('data'); }, fetchToken: function() { var _this = this; var token = Ember.$('meta[name="csrf-token"]').attr('content') || ''; return Ember.RSVP.resolve().then(function() { return _this.setData({'authenticity_token': token }); }); } });
Read the `__version__` parameter by directly running [trakt/version.py]
from setuptools import setup, find_packages import os base_dir = os.path.dirname(__file__) version = {} with open(os.path.join(base_dir, "trakt", "version.py")) as f: exec(f.read(), version) setup( name='trakt.py', version=version['__version__'], license='MIT', url='https://github.com/fuzeman/trakt.py', author='Dean Gardiner', author_email='me@dgardiner.net', description='Python interface for the trakt.tv API', packages=find_packages(exclude=[ 'examples' ]), platforms='any', install_requires=[ 'arrow', 'requests>=2.4.0', 'six' ], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python' ], )
from trakt.version import __version__ from setuptools import setup, find_packages setup( name='trakt.py', version=__version__, license='MIT', url='https://github.com/fuzeman/trakt.py', author='Dean Gardiner', author_email='me@dgardiner.net', description='Python interface for the trakt.tv API', packages=find_packages(exclude=[ 'examples' ]), platforms='any', install_requires=[ 'arrow', 'requests>=2.4.0', 'six' ], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python' ], )
Correct errors in pricing snippets
from twilio.rest import TwilioPricingClient, TwilioLookupsClient #auth credentials account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" auth_token = "{{ auth_token }}" #Use Lookup API to get country code / MCC / MNC that corresponds to given phone number phone_number = "+15108675309" print "Find outbound SMS price to:",phone_number client = TwilioLookupsClient(account_sid, auth_token) number= client.phone_numbers.get(phone_number,include_carrier_info=True) mcc = number.carrier['mobile_country_code'] mnc = number.carrier['mobile_network_code'] country_code = number.country_code #Use Pricing API to find the matching base/current prices to call that #particular country / MCC / MNC from local phone number client = TwilioPricingClient(account_sid, auth_token) messaging_country = client.messaging_countries().get(country_code) for c in messaging_country.outbound_sms_prices: if ((c['mcc'] == mcc) and (c['mnc'] == mnc)): for p in c['prices']: if (p['number_type'] == "local"): print "Country: ",country_code print "Base Price: ",p['base_price'] print "Current Price: ",p['current_price']
from twilio.rest import TwilioPricingClient, TwilioLookupsClient #auth credentials account_sid = "ACCOUNT_SID" auth_token = "AUTH_TOKEN" #Use Lookup API to get country code / MCC / MNC that corresponds to given phone number phone_number = "+15108675309" print "Find outbound SMS price to:",phone_number client = TwilioLookupsClient(account_sid, auth_token) number= client.phone_numbers.get(phone_number,include_carrier_info=True) mcc = number.carrier['mobile_country_code'] mnc = number.carrier['mobile_network_code'] country_code = number.country_code #Use Pricing API to find the matching base/current prices to call that #particular country / MCC / MNC from local phone number client = TwilioPricingClient(account_sid, auth_token) messaging_country = client.messaging_countries().get(country_code) for c in messaging_country.outbound_sms_prices: if ((c['mcc'] == mcc) and (c['mnc'] == mnc)): for p in c['prices']: if (p['number_type'] == "local"): print "Country: ",country_code print "Base Price: ",p['base_price'] print "Current Price: ",p['current_price']
Fix (unused) report page to use new schema.
<?php class ReportController extends AbstractController { function doGET(HttpRequest $request, HttpResponse $response) { $cols_raw = $request->get('cols'); $col_list = explode(',', $cols_raw); // We need a list of tag objects in the order provided by the user $col_query = sprintf('select * from tag where tag in (%s)', implode(',', array_fill(0, count($col_list), '?'))); $params = $col_list; array_unshift($params, $col_query); $cols = call_user_method_array('doQuery', $this, $params); foreach ($cols as $col) { $col_map[$col->tag] = $col; } $cols = array(); foreach ($col_list as $col_tag) { array_push($cols, $col_map[$col_tag]); } // Now we need a list of matching values $value_query = sprintf('select V.* from value_view V join latest_import_view LI using(import) where V.tag in (%s) order by V.row, V.col', implode(',', array_fill(0, count($col_list), '?'))); $params = $col_list; array_unshift($params, $value_query); $values = call_user_method_array('doQuery', $this, $params); $response->setParameter('cols', $cols); $response->setParameter('values', $values); $response->setTemplate('report'); } }
<?php class ReportController extends AbstractController { function doGET(HttpRequest $request, HttpResponse $response) { $cols_raw = $request->get('cols'); $col_list = explode(',', $cols_raw); // We need a list of tag objects in the order provided by the user $col_query = sprintf('select * from tag where tag in (%s)', implode(',', array_fill(0, count($col_list), '?'))); $params = $col_list; array_unshift($params, $col_query); $cols = call_user_method_array('doQuery', $this, $params); foreach ($cols as $col) { $col_map[$col->tag] = $col; } $cols = array(); foreach ($col_list as $col_tag) { array_push($cols, $col_map[$col_tag]); } // Now we need a list of matching values $value_query = sprintf('select V.* from value_view V join latest_import_view LI on V.import=LI.id where V.tag in (%s) order by V.row, V.col', implode(',', array_fill(0, count($col_list), '?'))); $params = $col_list; array_unshift($params, $value_query); $values = call_user_method_array('doQuery', $this, $params); $response->setParameter('cols', $cols); $response->setParameter('values', $values); $response->setTemplate('report'); } }
[Security] Fix some broken BC layers
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Security\Core\Encoder; trigger_deprecation('symfony/security-core', '5.3', sprintf('The "%s" interface is deprecated, use "%s" instead.', UserPasswordEncoderInterface::class, UserPasswordHasherInterface::class)); use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface; use Symfony\Component\Security\Core\User\UserInterface; /** * UserPasswordEncoderInterface is the interface for the password encoder service. * * @author Ariel Ferrandini <arielferrandini@gmail.com> * * @deprecated since Symfony 5.3, use {@link UserPasswordHasherInterface} instead */ interface UserPasswordEncoderInterface { /** * Encodes the plain password. * * @return string The encoded password */ public function encodePassword(UserInterface $user, string $plainPassword); /** * @return bool true if the password is valid, false otherwise */ public function isPasswordValid(UserInterface $user, string $raw); /** * Checks if an encoded password would benefit from rehashing. */ public function needsRehash(UserInterface $user): bool; }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Security\Core\Encoder; trigger_deprecation('symfony/security-core', '5.3', sprintf('The "%s" interface is deprecated, use "%s" on hasher implementations that deal with salts instead.', UserPasswordEncoderInterface::class, UserPasswordHasherInterface::class)); use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface; /** * UserPasswordEncoderInterface is the interface for the password encoder service. * * @author Ariel Ferrandini <arielferrandini@gmail.com> * * @deprecated since Symfony 5.3, use {@link UserPasswordHasherInterface} instead */ interface UserPasswordEncoderInterface { /** * Encodes the plain password. * * @return string The encoded password */ public function encodePassword(UserInterface $user, string $plainPassword); /** * @return bool true if the password is valid, false otherwise */ public function isPasswordValid(UserInterface $user, string $raw); /** * Checks if an encoded password would benefit from rehashing. */ public function needsRehash(UserInterface $user): bool; }
Break out dispatch, and drop prepare. Easier testing
from .request import Request from .response import Response, response import logging log = logging.getLogger() class View: def __call__(self, event, context): kwargs = event.get('pathParameters') or {} self.dispatch(request, **kwargs) def dispatch(self, request, **kwargs): func = getattr(self, request.method.lower()) try: resp = func(request, **kwargs) except: import traceback log.error(self) log.error(traceback.format_exc()) return response(body='Internal server Error', status=500) if isinstance(resp, Response): resp = resp.render() return resp def prepare(self, request): pass
from .request import Request from .response import Response, response import logging log = logging.getLogger() class View: def __call__(self, event, context): request = Request(event, context) resp = self.prepare(request) if resp: return resp kwargs = event.get('pathParameters') or {} func = getattr(self, request.method.lower()) try: resp = func(request, **kwargs) except: import traceback log.error(self) log.error(traceback.format_exc()) return response(body='Internal server Error', status=500) if isinstance(resp, Response): resp = resp.render() return resp def prepare(self, request): pass
Fix method in dni validator
<?php namespace Listabierta\Bundle\MunicipalesBundle\Validator\Constraints; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\ConstraintValidator; class DNIValidator extends ConstraintValidator { public function validate($value, Constraint $constraint) { // Check format if (0 === preg_match("/\d{1,8}[a-z]/i", $value)) { $this->context->addViolationAt('dni', 'El DNI introducido no tiene el formato correcto (entre 1 y 8 números seguidos de una letra, sin guiones y sin dejar ningún espacio en blanco)', array(), NULL); return; } // Check letter with algorithm $dni_number = substr($value, 0, -1); $dni_letter = strtoupper(substr($value, -1)); if ($dni_letter != substr("TRWAGMYFPDXBNJZSQVHLCKE", strtr($dni_number, "XYZ", "012")%23, 1)) { $this->context->addViolationAt('dni', 'La letra no coincide con el número del DNI. Comprueba que has escrito bien tanto el número como la letra', array(), NULL); } } }
<?php namespace Listabierta\Bundle\MunicipalesBundle\Validator\Constraints; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\ConstraintValidator; class DNIValidator extends ConstraintValidator { public function validate($value, Constraint $constraint) { // Check format if (0 === preg_match("/\d{1,8}[a-z]/i", $value)) { $this->context->addViolationAtSubPath('dni', 'El DNI introducido no tiene el formato correcto (entre 1 y 8 números seguidos de una letra, sin guiones y sin dejar ningún espacio en blanco)', array(), NULL); return; } // Check letter with algorithm $dni_number = substr($value, 0, -1); $dni_letter = strtoupper(substr($value, -1)); if ($dni_letter != substr("TRWAGMYFPDXBNJZSQVHLCKE", strtr($dni_number, "XYZ", "012")%23, 1)) { $this->context->addViolationAtSubPath('dni', 'La letra no coincide con el número del DNI. Comprueba que has escrito bien tanto el número como la letra', array(), NULL); } } }
Fix user settings with php7.1
<?php /** * ownCloud - password * * This file is licensed under the Affero General Public License version 3 or * later. See the COPYING file. * * @author Patrick Paysant / CNRS <ppaysant@linagora.com> * @copyright Patrick Paysant / CNRS 2016 */ \OCP\App::checkAppEnabled('password_policy'); \OC_Util::checkLoggedIn(); $tpl = new OCP\Template("password_policy", "settings-personal"); $policy = new \OCA\PasswordPolicyEnforcement\Policy(\OCP\Util::getL10N('password_policy')); $minlength = $policy->getMinLength(); $mixedcase = $policy->getMixedCase(); $mixedcase = ($mixedcase==='yes')?true:false; $numbers = $policy->getNumbers(); $numbers = ($numbers==='yes')?true:false; $specialcharacters = $policy->getSpecialChars(); $specialcharacters = ($specialcharacters==='yes')?true:false; $specialcharslist = $policy->getSpecialCharsList(); $tpl->assign('numbers', $numbers); $tpl->assign('minlength', $minlength); $tpl->assign('mixedcase', $mixedcase); $tpl->assign('specialcharacters', $specialcharacters); $tpl->assign('specialcharslist', $specialcharslist); return $tpl->fetchPage();
<?php /** * ownCloud - password * * This file is licensed under the Affero General Public License version 3 or * later. See the COPYING file. * * @author Patrick Paysant / CNRS <ppaysant@linagora.com> * @copyright Patrick Paysant / CNRS 2016 */ \OCP\App::checkAppEnabled('password_policy'); \OC_Util::checkLoggedIn(); $tpl = new OCP\Template("password_policy", "settings-personal"); $policy = new \OCA\PasswordPolicyEnforcement\Policy; $minlength = $policy->getMinLength(); $mixedcase = $policy->getMixedCase(); $mixedcase = ($mixedcase==='yes')?true:false; $numbers = $policy->getNumbers(); $numbers = ($numbers==='yes')?true:false; $specialcharacters = $policy->getSpecialChars(); $specialcharacters = ($specialcharacters==='yes')?true:false; $specialcharslist = $policy->getSpecialCharsList(); $tpl->assign('numbers', $numbers); $tpl->assign('minlength', $minlength); $tpl->assign('mixedcase', $mixedcase); $tpl->assign('specialcharacters', $specialcharacters); $tpl->assign('specialcharslist', $specialcharslist); return $tpl->fetchPage();
Fix displying right tags per category
/*global hexo */ var _ = require('lodash'); function tag_to_class(tag_name) { return 'tag-' + tag_name.replace(/\s/g, '-'); } hexo.extend.helper.register('tag_to_class', tag_to_class); hexo.extend.helper.register('tags_to_class', function(tags){ var cls = ''; tags.each(function(tag) { cls += tag_to_class(tag.name) + ' '; }); return cls; }); hexo.extend.helper.register('category_tags', function(category) { var tags = []; var cat = Category.findOne({name: category}).populate('posts'); cat.posts.each(function(post) { tags = _.union(tags, post.tags); }); tags = Tag.find({_id: {$in: tags}}).toArray(); return tags; });
/*global hexo */ var _ = require('lodash'); function tag_to_class(tag_name) { return 'tag-' + tag_name.replace(/\s/g, '-'); } hexo.extend.helper.register('tag_to_class', tag_to_class); hexo.extend.helper.register('tags_to_class', function(tags){ var cls = ''; tags.each(function(tag) { cls += tag_to_class(tag.name) + ' '; }); return cls; }); hexo.extend.helper.register('category_tags', function(category) { var tags = []; var cat = Category.first({name: category}).populate('posts'); cat.posts.each(function(post) { tags = _.union(tags, post.tags); }); tags = Tag.find({_id: {$in: tags}}).toArray(); return tags; });
Hide constructor for utility class
package org.parallelj.ssh.publickey; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class IO { private IO() { } public static byte[] readAsBytes(InputStream in) throws IOException { return read(in).toByteArray(); } public static void copy(InputStream in, OutputStream out) throws IOException { if (in == null) { throw new NullPointerException(); } try { byte[] buffer = new byte[256]; for (int l = in.read(buffer); l != -1; l = in.read(buffer)) { out.write(buffer, 0, l); } } finally { close(in); } } private static ByteArrayOutputStream read(InputStream in) throws IOException { if (in == null) { throw new NullPointerException(); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); copy(in, baos); return baos; } public static void close(Closeable closeable) { if (closeable != null) { try { closeable.close(); } catch (IOException ignore) { } } } }
package org.parallelj.ssh.publickey; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class IO { public static byte[] readAsBytes(InputStream in) throws IOException { return read(in).toByteArray(); } public static void copy(InputStream in, OutputStream out) throws IOException { if (in == null) { throw new NullPointerException(); } try { byte[] buffer = new byte[256]; for (int l = in.read(buffer); l != -1; l = in.read(buffer)) { out.write(buffer, 0, l); } } finally { close(in); } } private static ByteArrayOutputStream read(InputStream in) throws IOException { if (in == null) { throw new NullPointerException(); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); copy(in, baos); return baos; } public static void close(Closeable closeable) { if (closeable != null) { try { closeable.close(); } catch (IOException ignore) { } } } }
Refactor response page to say project title.
package com.johnstarich.moviematcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Handles all requests sent to the root ("/") of this server. * Created by johnstarich on 1/30/16. */ public class RootServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html; charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println("<h1>Hey there!</h1><h2>This is Movie Matcher</h2> <p>This is the request path we received: " + request.getPathInfo() + "</p>"); System.out.println("Request was = GET " + request.getPathInfo()); } }
package com.johnstarich.moviematcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Handles all requests sent to the root ("/") of this server. * Created by johnstarich on 1/30/16. */ public class RootServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html; charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println("<h1>Hey there!</h1><h2>This is our EE461L design project</h2> <p>This is the request path we received: " + request.getPathInfo() + "</p>"); System.out.println("Request was = GET " + request.getPathInfo()); } }
Return structure and sensors with ExperimentSchema
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema, MediaSchema = require('./media.server.model').schema, _ = require('lodash'); /** * ExperimentSchema Schema */ var ExperimentSchemaSchema = new Schema({ structure: {}, sensors: [String], trialCount: { type: Number, required: true }, mediaPool: [{ type: Schema.Types.ObjectId, ref: 'Media' }] }); // Validator that requires the value is an array and contains at least one entry function requiredArrayValidator(value) { return Object.prototype.toString.call(value) === '[object Array]' && value.length > 0; } // Use the above validator for `mediaPool` ExperimentSchemaSchema.path('mediaPool').validate(requiredArrayValidator); ExperimentSchemaSchema.methods.buildExperiment = function(callback) { // Populate mediaPool this.populate('mediaPool'); var selectedMedia = _.sample(this.mediaPool, this.trialCount); var schemaSubset = { _id: this._id, structure: this.structure, sensors: this.sensors, media: selectedMedia, }; if (typeof callback === 'function') { return callback(null, schemaSubset); } else { return schemaSubset; } }; // Register schema for `ExperimentSchema` model mongoose.model('ExperimentSchema', ExperimentSchemaSchema);
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema, MediaSchema = require('./media.server.model').schema, _ = require('lodash'); /** * ExperimentSchema Schema */ var ExperimentSchemaSchema = new Schema({ trialCount: { type: Number, required: true }, mediaPool: [{ type: Schema.Types.ObjectId, ref: 'Media' }] }); // Validator that requires the value is an array and contains at least one entry function requiredArrayValidator(value) { return Object.prototype.toString.call(value) === '[object Array]' && value.length > 0; } // Use the above validator for `mediaPool` ExperimentSchemaSchema.path('mediaPool').validate(requiredArrayValidator); ExperimentSchemaSchema.methods.buildExperiment = function(callback) { // Populate mediaPool this.populate('mediaPool'); var selectedMedia = _.sample(this.mediaPool, this.trialCount); if (typeof callback === 'function') { return callback(null, {media: selectedMedia}); } else { return {media: selectedMedia}; } }; // Register schema for `ExperimentSchema` model mongoose.model('ExperimentSchema', ExperimentSchemaSchema);
Make docker credentials Nullable to match API definition
/* * Copyright 2013-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cloudfoundry.client.v3.packages; import org.cloudfoundry.Nullable; import org.immutables.value.Value; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; /** * Data type for docker packages */ @JsonDeserialize @Value.Immutable abstract class _DockerData implements PackageData { /** * The Docker image */ @JsonProperty("image") abstract String getImage(); /** * The password for the image's registry */ @JsonProperty("password") @Nullable abstract String getPassword(); /** * The username for the image's registry */ @JsonProperty("username") @Nullable abstract String getUsername(); }
/* * Copyright 2013-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cloudfoundry.client.v3.packages; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import org.immutables.value.Value; /** * Data type for docker packages */ @JsonDeserialize @Value.Immutable abstract class _DockerData implements PackageData { /** * The Docker image */ @JsonProperty("image") abstract String getImage(); /** * The password for the image's registry */ @JsonProperty("password") abstract String getPassword(); /** * The username for the image's registry */ @JsonProperty("username") abstract String getUsername(); }
Use the function form of "use strict".
var gutil = require('gulp-util'); var through = require('through2'); var juice = require('juice'); module.exports = function(opt){ return through.obj(function (file, enc, cb) { 'use strict'; opt = opt || {}; // 'url' option is required // set it automatically if not provided opt.url = opt.url || 'file://' + file.path; if (file.isNull()) { this.push(file); return cb(); } if (file.isStream()) { this.emit('error', new gutil.PluginError('gulp-inline-css', 'Streaming not supported')); return cb(); } juice.juiceContent(file.contents, opt, function(err, html) { if (err) { this.emit('error', new gutil.PluginError('gulp-inline-css', err)); } file.contents = new Buffer(String(html)); this.push(file); return cb(); }.bind(this)); }); };
'use strict'; var gutil = require('gulp-util'); var through = require('through2'); var juice = require('juice'); module.exports = function(opt){ return through.obj(function (file, enc, cb) { if (!opt) { opt = {}; } // 'url' option is required // set it automatically if not provided if(!opt.url) { opt.url = 'file://' + file.path; } if (file.isNull()) { this.push(file); return cb(); } if (file.isStream()) { this.emit('error', new gutil.PluginError('gulp-inline-css', 'Streaming not supported')); return cb(); } juice.juiceContent(file.contents, opt, function(err, html) { if (err) { this.emit('error', new gutil.PluginError('gulp-inline-css', err)); } file.contents = new Buffer(String(html)); this.push(file); return cb(); }.bind(this)); }); };
Update the 503 error message.
import httpx from linguee_api.downloaders.interfaces import DownloaderError, IDownloader ERROR_503 = ( "The Linguee server returned 503. The API proxy was temporarily blocked by " "Linguee. For more details, see https://github.com/imankulov/linguee-api#" "the-api-server-returns-the-linguee-server-returned-503" ) class HTTPXDownloader(IDownloader): """ Real downloader. Sends request to linguee.com to read the page. """ async def download(self, url: str) -> str: async with httpx.AsyncClient() as client: try: response = await client.get(url) except httpx.ConnectError as e: raise DownloaderError(str(e)) from e if response.status_code == 503: raise DownloaderError(ERROR_503) if response.status_code != 200: raise DownloaderError( f"The Linguee server returned {response.status_code}" ) return response.text
import httpx from linguee_api.downloaders.interfaces import DownloaderError, IDownloader class HTTPXDownloader(IDownloader): """ Real downloader. Sends request to linguee.com to read the page. """ async def download(self, url: str) -> str: async with httpx.AsyncClient() as client: try: response = await client.get(url) except httpx.ConnectError as e: raise DownloaderError(str(e)) from e if response.status_code != 200: raise DownloaderError( f"The Linguee server returned {response.status_code}" ) return response.text
Change test data for mimetype to content_type.
import unittest from activity.activity_DepositAssets import activity_DepositAssets import settings_mock from ddt import ddt, data, unpack @ddt class TestDepositAssets(unittest.TestCase): def setUp(self): self.depositassets = activity_DepositAssets(settings_mock, None, None, None, None) @unpack @data({'input': '.tif', 'expected': ['.tif']}, {'input': '.jpg, .tiff, .png', 'expected':['.jpg', '.tiff', '.png']}) def test_get_no_download_extensions(self, input, expected): result = self.depositassets.get_no_download_extensions(input) self.assertListEqual(result, expected) @unpack @data( (None, None), ('image.jpg', 'image/jpeg'), ('/folder/file.test.pdf', 'application/pdf'), ('/folder/weird_file.wdl', 'binary/octet-stream'), ('a_file', 'binary/octet-stream') ) def test_content_type_from_file_name(self, input, expected): result = self.depositassets.content_type_from_file_name(input) self.assertEqual(result, expected) if __name__ == '__main__': unittest.main()
import unittest from activity.activity_DepositAssets import activity_DepositAssets import settings_mock from ddt import ddt, data, unpack @ddt class TestDepositAssets(unittest.TestCase): def setUp(self): self.depositassets = activity_DepositAssets(settings_mock, None, None, None, None) @unpack @data({'input': '.tif', 'expected': ['.tif']}, {'input': '.jpg, .tiff, .png', 'expected':['.jpg', '.tiff', '.png']}) def test_get_no_download_extensions(self, input, expected): result = self.depositassets.get_no_download_extensions(input) self.assertListEqual(result, expected) @unpack @data( (None, None), ('image.jpg', 'image/jpeg'), ('/folder/file.pdf.zip', 'application/x-zip-compressed'), ('/folder/weird_file.wdl', 'binary/octet-stream'), ('a_file', 'binary/octet-stream') ) def test_content_type_from_file_name(self, input, expected): result = self.depositassets.content_type_from_file_name(input) self.assertEqual(result, expected) if __name__ == '__main__': unittest.main()
Print if nothing to update
import sys import sh from fabric import api as fab sed = sh.sed.bake('-i bak -e') TRAVIS_YAML = '.travis.yml' REPLACE_LANGUAGE = 's/language: .*/language: {}/' def is_dirty(): return "" != sh.git.status(porcelain=True).strip() def release(language, message): if is_dirty(): sys.exit("Repo must be in clean state before deploying. Please commit changes.") sed(REPLACE_LANGUAGE.format(language), TRAVIS_YAML) if is_dirty(): sh.git.add(TRAVIS_YAML) sh.git.commit(m=message, allow_empty=True) sh.git.pull(rebase=True) sh.git.push() @fab.task def update(): if is_dirty(): sys.exit("Repo must be in clean state before deploying. Please commit changes.") sh.git.submodule.update(remote=True, rebase=True) if is_dirty(): sh.git.add(all=True) sh.git.commit(m="Update submodules to origin") else: sys.exit('Nothing to update.') @fab.task def release_osx(): release('objective-c', "Release OS X") @fab.task def release_linux(): release('python', "Release Linux")
import sys import sh from fabric import api as fab sed = sh.sed.bake('-i bak -e') TRAVIS_YAML = '.travis.yml' REPLACE_LANGUAGE = 's/language: .*/language: {}/' def is_dirty(): return "" != sh.git.status(porcelain=True).strip() def release(language, message): if is_dirty(): sys.exit("Repo must be in clean state before deploying. Please commit changes.") sed(REPLACE_LANGUAGE.format(language), TRAVIS_YAML) if is_dirty(): sh.git.add(TRAVIS_YAML) sh.git.commit(m=message, allow_empty=True) sh.git.pull(rebase=True) sh.git.push() @fab.task def update(): if is_dirty(): sys.exit("Repo must be in clean state before deploying. Please commit changes.") sh.git.submodule.update(remote=True, rebase=True) if is_dirty(): sh.git.add(all=True) sh.git.commit(m="Update submodules to origin") @fab.task def release_osx(): release('objective-c', "Release OS X") @fab.task def release_linux(): release('python', "Release Linux")
Drop loop in EIN test
<?php namespace Faker\Test\Provider\en_US; use Faker\Provider\en_US\Company; use Faker\Generator; class CompanyTest extends \PHPUnit_Framework_TestCase { /** * @var Generator */ private $faker; public function setUp() { $faker = new Generator(); $faker->addProvider(new Company($faker)); $this->faker = $faker; } public function testEin() { $number = $this->faker->ein; // should be in the format ##-#######, with a valid prefix $this->assertRegExp('/^(0[1-6]||1[0-6]|2[0-7]|[35]\d|[468][0-8]|7[1-7]|9[0-58-9])-\d{7}$/', $number); } }
<?php namespace Faker\Test\Provider\en_US; use Faker\Provider\en_US\Company; use Faker\Generator; class CompanyTest extends \PHPUnit_Framework_TestCase { /** * @var Generator */ private $faker; public function setUp() { $faker = new Generator(); $faker->addProvider(new Company($faker)); $this->faker = $faker; } public function testEin() { for ($i = 0; $i < 100; $i++) { $number = $this->faker->ein; // should be in the format ##-#######, with a valid prefix $this->assertRegExp('/^(0[1-6]||1[0-6]|2[0-7]|[35]\d|[468][0-8]|7[1-7]|9[0-58-9])-\d{7}$/', $number); } } }
Fix date of DPA activity properly
<?php class CRM_Speakcivi_Logic_Consent { public $publicId; public $version; public $language; public $date; public $createDate; public $level; public $method; public $methodOption; /** * @param $param * * @return array */ public static function prepareFields($param) { $consents = []; if (property_exists($param, 'consents')) { foreach ($param->consents as $consent) { list($consentVersion, $consentLanguage) = explode('-', $consent->public_id); $cd = new DateTime(substr($param->create_dt, 0, 10)); $c = new self(); $c->publicId = $consent->public_id; $c->version = $consentVersion; $c->language = $consentLanguage; $c->date = $cd->format('Y-m-d'); $c->createDate = $param->create_dt; $c->level = $consent->consent_level; $c->method = $consent->consent_method; $c->methodOption = $consent->consent_method_option; $consents[] = $c; } } return $consents; } }
<?php class CRM_Speakcivi_Logic_Consent { public $publicId; public $version; public $language; public $date; public $createDate; public $level; public $method; public $methodOption; /** * @param $param * * @return array */ public static function prepareFields($param) { $consents = []; if (property_exists($param, 'consents')) { foreach ($param->consents as $consent) { list($consentVersion, $consentLanguage) = explode('-', $consent->public_id); $cd = new DateTime(substr($param->create_dt, 0, 10)); $c = new self(); $c->publicId = $consent->public_id; $c->version = $consentVersion; $c->language = $consentLanguage; $c->date = $cd->format('Y-m-d'); $c->createDate = $cd->format('Y-m-d H:i:s'); $c->level = $consent->consent_level; $c->method = $consent->consent_method; $c->methodOption = $consent->consent_method_option; $consents[] = $c; } } return $consents; } }
Reduce max heap from 512m to 384m
// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.model.admin; import com.yahoo.config.model.deploy.DeployState; import com.yahoo.config.model.producer.AbstractConfigProducer; import com.yahoo.container.handler.ThreadpoolConfig; import com.yahoo.search.config.QrStartConfig; import com.yahoo.vespa.model.container.ContainerCluster; import com.yahoo.vespa.model.container.component.Handler; import java.util.Objects; /** * @author hmusum */ public class LogserverContainerCluster extends ContainerCluster<LogserverContainer> implements ThreadpoolConfig.Producer { public LogserverContainerCluster(AbstractConfigProducer<?> parent, String name, DeployState deployState) { super(parent, name, name, deployState); addDefaultHandlersWithVip(); addLogHandler(); } @Override protected void doPrepare(DeployState deployState) { } @Override public void getConfig(ThreadpoolConfig.Builder builder) { builder.maxthreads(10); } @Override public void getConfig(QrStartConfig.Builder builder) { super.getConfig(builder); builder.jvm.heapsize(384); } protected boolean messageBusEnabled() { return false; } private void addLogHandler() { Handler<?> logHandler = Handler.fromClassName(ContainerCluster.LOG_HANDLER_CLASS); logHandler.addServerBindings("http://*/logs"); addComponent(logHandler); } }
// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.model.admin; import com.yahoo.config.model.deploy.DeployState; import com.yahoo.config.model.producer.AbstractConfigProducer; import com.yahoo.container.handler.ThreadpoolConfig; import com.yahoo.vespa.model.container.ContainerCluster; import com.yahoo.vespa.model.container.component.Handler; /** * @author hmusum */ public class LogserverContainerCluster extends ContainerCluster<LogserverContainer> implements ThreadpoolConfig.Producer { public LogserverContainerCluster(AbstractConfigProducer<?> parent, String name, DeployState deployState) { super(parent, name, name, deployState); addDefaultHandlersWithVip(); addLogHandler(); } @Override protected void doPrepare(DeployState deployState) { } @Override public void getConfig(ThreadpoolConfig.Builder builder) { builder.maxthreads(10); } protected boolean messageBusEnabled() { return false; } private void addLogHandler() { Handler<?> logHandler = Handler.fromClassName(ContainerCluster.LOG_HANDLER_CLASS); logHandler.addServerBindings("http://*/logs"); addComponent(logHandler); } }
Update my contacts and the copyright.
# vim:fileencoding=utf-8 # Copyright -2014 (c) gocept gmbh & co. kg # Copyright 2015- (c) Flying Circus Internet Operations GmbH # See also LICENSE.txt from setuptools import setup, find_packages setup( name='pycountry', version='1.12.dev0', author='Christian Theune', author_email='ct@flyingcircus.io', description='ISO country, subdivision, language, currency and script ' 'definitions and their translations', long_description=( open('README').read() + '\n' + open('HISTORY.txt').read()), license='LGPL 2.1', keywords='country subdivision language currency iso 3166 639 4217 ' '15924 3166-2', zip_safe=False, packages=find_packages('src'), include_package_data=True, package_dir={'': 'src'})
# vim:fileencoding=utf-8 # Copyright (c) gocept gmbh & co. kg # See also LICENSE.txt import os.path from setuptools import setup, find_packages setup( name='pycountry', version='1.12.dev0', author='Christian Theune', author_email='ct@gocept.com', description='ISO country, subdivision, language, currency and script ' 'definitions and their translations', long_description=( open('README').read() + '\n' + open('HISTORY.txt').read()), license='LGPL 2.1', keywords='country subdivision language currency iso 3166 639 4217 ' '15924 3166-2', zip_safe=False, packages=find_packages('src'), include_package_data=True, package_dir={'': 'src'})
Make directory if it doesnt exist
import os import collections LearningObject = collections.namedtuple( 'LearningObject', ['text', 'image']) class Model(object): def __init__(self, name): self._name = name self._objs = [] def add_object(self, text, image): self._objs.append(LearningObject(text, image)) def write(self): if not os.path.exists('xml'): os.mkdir('xml') path = 'xml/LearningObjectsModularList-%s.xml' % self._name with open(path, 'w') as manifest_file: manifest_file.write('<Modules>\n') manifest_file.write(' <Module>\n') manifest_file.write(' <ModuleName>%s</ModuleName>\n' % self._name) for o in self._objs: manifest_file.write( ' <LearningObject>\n' ' <TextToDisplay>%s</TextToDisplay>\n' ' <ImageToDisplay>%s</ImageToDisplay>\n' ' </LearningObject>\n' % (o.text, o.image)) manifest_file.write(' </Module>\n') manifest_file.write('</Modules>')
import collections LearningObject = collections.namedtuple( 'LearningObject', ['text', 'image']) class Model(object): def __init__(self, name): self._name = name self._objs = [] def add_object(self, text, image): self._objs.append(LearningObject(text, image)) def write(self): path = 'xml/LearningObjectsModularList-%s.xml' % self._name with open(path, 'w') as manifest_file: manifest_file.write('<Modules>\n') manifest_file.write(' <Module>\n') manifest_file.write(' <ModuleName>%s</ModuleName>\n' % self._name) for o in self._objs: manifest_file.write( ' <LearningObject>\n' ' <TextToDisplay>%s</TextToDisplay>\n' ' <ImageToDisplay>%s</ImageToDisplay>\n' ' </LearningObject>\n' % (o.text, o.image)) manifest_file.write(' </Module>\n') manifest_file.write('</Modules>')
Test de cambio de dependencia en traduccion
'use strict'; angular.module('core').controller('HeaderController', ['$scope', 'Authentication', 'Menus','pascalprecht.translate','$rootScope','$locale', function($scope, Authentication, Menus,$translate,$rootScope,$locale) { $scope.authentication = Authentication; $scope.isCollapsed = false; $scope.menu = Menus.getMenu('topbar'); $translate.useSanitizeValueStrategy('sanitize'); $scope.toggleCollapsibleMenu = function() { $scope.isCollapsed = !$scope.isCollapsed; }; // Collapsing the menu after navigation $scope.$on('$stateChangeSuccess', function() { $scope.isCollapsed = false; }); $rootScope.changeLanguage = function (langKey) { $translate.use(langKey); }; $rootScope.changeLanguage($locale.id.split('-')[0]); } ]);
'use strict'; angular.module('core').controller('HeaderController', ['$scope', 'Authentication', 'Menus','$translate','$rootScope','$locale', function($scope, Authentication, Menus,$translate,$rootScope,$locale) { $scope.authentication = Authentication; $scope.isCollapsed = false; $scope.menu = Menus.getMenu('topbar'); $translate.useSanitizeValueStrategy('sanitize'); $scope.toggleCollapsibleMenu = function() { $scope.isCollapsed = !$scope.isCollapsed; }; // Collapsing the menu after navigation $scope.$on('$stateChangeSuccess', function() { $scope.isCollapsed = false; }); $rootScope.changeLanguage = function (langKey) { $translate.use(langKey); }; $rootScope.changeLanguage($locale.id.split('-')[0]); } ]);
Bump version of `accounts-password` in preparation for publishing.
Package.describe({ summary: "Password support for accounts", version: "1.3.7" }); Package.onUse(function(api) { api.use('npm-bcrypt', 'server'); api.use([ 'accounts-base', 'srp', 'sha', 'ejson', 'ddp' ], ['client', 'server']); // Export Accounts (etc) to packages using this one. api.imply('accounts-base', ['client', 'server']); api.use('email', ['server']); api.use('random', ['server']); api.use('check'); api.use('underscore'); api.use('ecmascript'); api.addFiles('email_templates.js', 'server'); api.addFiles('password_server.js', 'server'); api.addFiles('password_client.js', 'client'); }); Package.onTest(function(api) { api.use(['accounts-password', 'tinytest', 'test-helpers', 'tracker', 'accounts-base', 'random', 'email', 'underscore', 'check', 'ddp', 'ecmascript']); api.addFiles('password_tests_setup.js', 'server'); api.addFiles('password_tests.js', ['client', 'server']); api.addFiles('email_tests_setup.js', 'server'); api.addFiles('email_tests.js', 'client'); });
Package.describe({ summary: "Password support for accounts", version: "1.3.6" }); Package.onUse(function(api) { api.use('npm-bcrypt', 'server'); api.use([ 'accounts-base', 'srp', 'sha', 'ejson', 'ddp' ], ['client', 'server']); // Export Accounts (etc) to packages using this one. api.imply('accounts-base', ['client', 'server']); api.use('email', ['server']); api.use('random', ['server']); api.use('check'); api.use('underscore'); api.use('ecmascript'); api.addFiles('email_templates.js', 'server'); api.addFiles('password_server.js', 'server'); api.addFiles('password_client.js', 'client'); }); Package.onTest(function(api) { api.use(['accounts-password', 'tinytest', 'test-helpers', 'tracker', 'accounts-base', 'random', 'email', 'underscore', 'check', 'ddp', 'ecmascript']); api.addFiles('password_tests_setup.js', 'server'); api.addFiles('password_tests.js', ['client', 'server']); api.addFiles('email_tests_setup.js', 'server'); api.addFiles('email_tests.js', 'client'); });
Update aggregate definition, groupby not required.
export default { "type": "Aggregate", "metadata": {"generates": true, "changes": true}, "params": [ { "name": "groupby", "type": "field", "array": true }, { "name": "fields", "type": "field", "array": true }, { "name": "ops", "type": "enum", "array": true, "values": [ "count", "valid", "missing", "distinct", "sum", "mean", "average", "variance", "variancep", "stdev", "stdevp", "median", "q1", "q3", "modeskew", "min", "max", "argmin", "argmax" ] }, { "name": "as", "type": "string", "array": true }, { "name": "drop", "type": "boolean", "default": true } ] };
export default { "type": "Aggregate", "metadata": {"generates": true, "changes": true}, "params": [ { "name": "groupby", "type": "field", "array": true, "required": true }, { "name": "fields", "type": "field", "array": true }, { "name": "ops", "type": "enum", "array": true, "values": [ "count", "valid", "missing", "distinct", "sum", "mean", "average", "variance", "variancep", "stdev", "stdevp", "median", "q1", "q3", "modeskew", "min", "max", "argmin", "argmax" ] }, { "name": "as", "type": "string", "array": true }, { "name": "drop", "type": "boolean", "default": true } ] };
Remove reference to non-existent file
var chai = require('chai'); var expect = chai.expect; var jsdom = require('mocha-jsdom'); describe('DrawerTabsView', function() { jsdom(); describe('::initialize', function() { describe('with forceOpen', function() { var $fixture, view; beforeEach(function() { var DrawerTabsView = require('../../../source/views/drawer/drawer-tabs-view'); $fixture = $('<div id="fixutre"></div>'); $fixture.append('<div class="toc-head"><a href="#" id="panel-link" class="toc-toggle panel-slide"></a></div>' ).appendTo('body'); view = new DrawerTabsView({forceOpen: true}); }); afterEach(function() { view.remove(); $fixture.remove(); }); it('is in the open state', function() { expect(view).to.be.ok; expect(view.drawerState).to.eql('open'); expect(view.$toggleArrow.attr('class')).to.match(/\bopen\b/); }); }); }); });
var chai = require('chai'); var expect = chai.expect; var jsdom = require('mocha-jsdom'); var helpers = require('../spec-helpers'); describe('DrawerTabsView', function() { jsdom(); describe('::initialize', function() { describe('with forceOpen', function() { var $fixture, view; beforeEach(function() { var DrawerTabsView = require('../../../source/views/drawer/drawer-tabs-view'); $fixture = $('<div id="fixutre"></div>'); $fixture.append('<div class="toc-head"><a href="#" id="panel-link" class="toc-toggle panel-slide"></a></div>' ).appendTo('body'); view = new DrawerTabsView({forceOpen: true}); }); afterEach(function() { view.remove(); $fixture.remove(); }); it('is in the open state', function() { expect(view).to.be.ok; expect(view.drawerState).to.eql('open'); expect(view.$toggleArrow.attr('class')).to.match(/\bopen\b/); }); }); }); });
Fix typo in action types for filter by type fatality
export const START_DATE_CHANGE = 'START_DATE_CHANGE'; export const END_DATE_CHANGE = 'END_DATE_CHANGE'; export const FILTER_BY_AREA = 'FILTER_BY_AREA'; export const FILTER_BY_IDENTIFIER = 'FILTER_BY_IDENTIFIER'; export const FILTER_BY_TYPE_INJURY = 'FILTER_BY_TYPE_INJURY'; export const FILTER_BY_TYPE_FATALITY = 'FILTER_BY_TYPE_FATALITY'; export const FILTER_BY_NO_INJURY_FATALITY = 'FILTER_BY_NO_INJURY_FATALITY'; export const FILTER_BY_CONTRIBUTING_FACTOR = 'FILTER_BY_CONTRIBUTING_FACTOR'; export const CRASHES_ALL_REQUEST = 'CRASHES_ALL_REQUEST'; export const CRASHES_ALL_SUCCESS = 'CRASHES_ALL_SUCCESS'; export const CRASHES_ALL_ERROR = 'CRASHES_ALL_ERROR'; export const CONTRIBUTING_FACTORS_REQUEST = 'CONTRIBUTING_FACTORS_REQUEST'; export const CONTRIBUTING_FACTORS_SUCCESS = 'CONTRIBUTING_FACTORS_SUCCESS'; export const CONTRIBUTING_FACTORS_ERROR = 'CONTRIBUTING_FACTORS_ERROR';
export const START_DATE_CHANGE = 'START_DATE_CHANGE'; export const END_DATE_CHANGE = 'END_DATE_CHANGE'; export const FILTER_BY_AREA = 'FILTER_BY_AREA'; export const FILTER_BY_IDENTIFIER = 'FILTER_BY_IDENTIFIER'; export const FILTER_BY_TYPE_INJURY = 'FILTER_BY_TYPE_INJURY'; export const FILTER_BY_TYPE_FATALITY = 'FILTER_BY_TYPE_HARM'; export const FILTER_BY_NO_INJURY_FATALITY = 'FILTER_BY_NO_INJURY_FATALITY'; export const FILTER_BY_CONTRIBUTING_FACTOR = 'FILTER_BY_CONTRIBUTING_FACTOR'; export const CRASHES_ALL_REQUEST = 'CRASHES_ALL_REQUEST'; export const CRASHES_ALL_SUCCESS = 'CRASHES_ALL_SUCCESS'; export const CRASHES_ALL_ERROR = 'CRASHES_ALL_ERROR'; export const CONTRIBUTING_FACTORS_REQUEST = 'CONTRIBUTING_FACTORS_REQUEST'; export const CONTRIBUTING_FACTORS_SUCCESS = 'CONTRIBUTING_FACTORS_SUCCESS'; export const CONTRIBUTING_FACTORS_ERROR = 'CONTRIBUTING_FACTORS_ERROR';
Rename 'config' service to 'options'
#!/usr/bin/env python from __future__ import print_function import os import sys import gevent import gevent.wsgi import simplejson as json from butler import service from butler.options import Options from butler.routing import Dispatcher default_config_path = \ os.path.expanduser(os.path.join('~', '.config', 'butler', 'butler.cfg')) def load_config(path): try: with open(path, 'r') as config_file: return Options(json.load(config_file)) except (IOError, TypeError, ValueError) as e: print(e, file=sys.stderr) def serve(config_path): options = load_config(config_path) services = list(service.find_all('butler.services')) services.append(service.static('options', options)) delegates = service.start(services) address = options.options('server').str('address', '127.0.0.1:8000') server = gevent.wsgi.WSGIServer(address, Dispatcher(delegates)) server.serve_forever() def main(): config_path = default_config_path if len(sys.argv) > 1: config_path = sys.argv[1] serve(config_path)
#!/usr/bin/env python from __future__ import print_function import os import sys import gevent import gevent.wsgi import simplejson as json from butler import service from butler.options import Options from butler.routing import Dispatcher default_config_path = \ os.path.expanduser(os.path.join('~', '.config', 'butler', 'butler.cfg')) def load_config(path): try: with open(path, 'r') as config_file: return Options(json.load(config_file)) except (IOError, TypeError, ValueError) as e: print(e, file=sys.stderr) def serve(config_path): options = load_config(config_path) services = list(service.find_all('butler.services')) services.append(service.static('config', options)) delegates = service.start(services) address = options.options('server').str('address', '127.0.0.1:8000') server = gevent.wsgi.WSGIServer(address, Dispatcher(delegates)) server.serve_forever() def main(): config_path = default_config_path if len(sys.argv) > 1: config_path = sys.argv[1] serve(config_path)
Define __repr__ for pdtools Camera class.
import base64 import requests import six class Camera(object): def __init__(self, host): self.host = host def __repr__(self): return "Camera({})".format(self.host) def get_image(self): """ Get an image from the camera. Returns image data as a BytesIO/StringIO object. """ url = "http://{}/image.jpg".format(self.host) encoded = base64.b64encode('admin:'.encode('utf-8')).decode('ascii') headers = { 'Authorization': 'Basic ' + encoded } result = requests.get(url, headers=headers) if result.ok: return six.BytesIO(result.content) else: return None
import base64 import requests import six class Camera(object): def __init__(self, host): self.host = host def get_image(self): """ Get an image from the camera. Returns image data as a BytesIO/StringIO object. """ url = "http://{}/image.jpg".format(self.host) encoded = base64.b64encode('admin:'.encode('utf-8')).decode('ascii') headers = { 'Authorization': 'Basic ' + encoded } result = requests.get(url, headers=headers) if result.ok: return six.BytesIO(result.content) else: return None
Make sure to kill JVM on exit
"""Methods related to starting and stopping the Java Gateway""" from py4j.java_gateway import JavaGateway import os def _find_lolo_jar(): """Attempt to automatically find a jar file for Lolo Returns: (string) Path to the Jar file """ # TODO: Make this not hardcoded -lw return os.path.join(os.path.dirname(__file__), '..', '..', 'target', 'lolo-1.0.2.jar') def get_java_gateway(reuse=True): """Get a JavaGateway with Lolo on the class path Args: reuse (bool): Whether to reuse an already-existing gateway (TBD) Returns: (JavaGateway) A launched JavaGateway instance """ # TODO: Implement a way to prevent having to launch a new JVM every time lolo_path = _find_lolo_jar() # TODO: Find a way to get the path to scala (might just detect if on Windows vs Linux _gateway = JavaGateway.launch_gateway(classpath=os.path.pathsep.join([ os.path.abspath(lolo_path)]), java_path="scala.bat", die_on_exit=True) return _gateway JavaGateway()
"""Methods related to starting and stopping the Java Gateway""" from py4j.java_gateway import JavaGateway import os def _find_lolo_jar(): """Attempt to automatically find a jar file for Lolo Returns: (string) Path to the Jar file """ # TODO: Make this not hardcoded -lw return os.path.join(os.path.dirname(__file__), '..', '..', 'target', 'lolo-1.0.2.jar') def get_java_gateway(reuse=True): """Get a JavaGateway with Lolo on the class path Args: reuse (bool): Whether to reuse an already-existing gateway (TBD) Returns: (JavaGateway) A launched JavaGateway instance """ # TODO: Implement a way to prevent having to launch a new JVM every time lolo_path = _find_lolo_jar() # TODO: Find a way to get the path to scala (might just detect if on Windows vs Linux _gateway = JavaGateway.launch_gateway(classpath=os.path.pathsep.join([ os.path.abspath(lolo_path)]), java_path="scala.bat") return _gateway JavaGateway()
Fix name of step method of a behat test
<?php namespace Bauhaus\Container; require __DIR__ . '/../bootstrap.php'; class RegistrableContainerUserContext extends ContainerUserBaseContext { /** * @When I register an item with label :label and value :value */ public function iRegisterANewItemWithLabelAndValue($label, $value) { $this->container->register($label, $value); } /** * @When I try to register an item with label :label already taken */ public function iTryToRegisterAnItemWithLabelAlreadyTaken($label) { try { $this->container->register($label, 'someValue'); } catch (\Exception $e) { $this->outcome = $e; } } }
<?php namespace Bauhaus\Container; require __DIR__ . '/../bootstrap.php'; class RegistrableContainerUserContext extends ContainerUserBaseContext { /** * @When I register an item with label :label and value :value */ public function iRegisterANewItemWithLabelAndValue($label, $value) { $this->container->register($label, $value); } /** * @When I try to register an item with label :label already taken */ public function iTryToRegisterAnItemWithLabelAndValue($label) { try { $this->container->register($label, 'someValue'); } catch (\Exception $e) { $this->outcome = $e; } } }
Use shorter localIdentName for css-loader
var path = require('path') var ExtractTextPlugin = require('extract-text-webpack-plugin') var DIST = path.join(__dirname, 'dist') var SRC = path.join(__dirname, 'src') function styleLoaders (loaders) { if (process.env.NODE_ENV === 'production') { return ExtractTextPlugin.extract(loaders[0], loaders.slice(1).join('!')) } return loaders.join('!') } module.exports = { output: { path: DIST, filename: 'app.js', publicPath: '/' }, module: { loaders: [{ test: /\.js$/, loader: 'babel', include: SRC }, { test: /\.css$/, loader: styleLoaders(['style', 'css?modules&sourceMap&localIdentName=[hash:base64:3]', 'postcss']), include: SRC }, { test: /\.css$/, loader: styleLoaders(['style?insertAt=top', 'css']), include: path.join(__dirname, 'node_modules', 'normalize.css') }] } }
var path = require('path') var ExtractTextPlugin = require('extract-text-webpack-plugin') var DIST = path.join(__dirname, 'dist') var SRC = path.join(__dirname, 'src') function styleLoaders (loaders) { if (process.env.NODE_ENV === 'production') { return ExtractTextPlugin.extract(loaders[0], loaders.slice(1).join('!')) } return loaders.join('!') } module.exports = { output: { path: DIST, filename: 'app.js', publicPath: '/' }, module: { loaders: [{ test: /\.js$/, loader: 'babel', include: SRC }, { test: /\.css$/, loader: styleLoaders(['style', 'css?modules&sourceMap', 'postcss']), include: SRC }, { test: /\.css$/, loader: styleLoaders(['style?insertAt=top', 'css']), include: path.join(__dirname, 'node_modules', 'normalize.css') }] } }
Add and implement function for second rule
/* Puzzle input - check /input/day5.js */ var input = require('./input/day5.js'); /* Variables */ // Split input by new line character ("\n") var strings = input.split('\n'); /* Functions */ // Function to return the vowel count function getVowelCount(string){ var count = 0; for (var i = 0; i < string.length; i++) { var character = string[i]; if (character === 'a' || character === 'e' || character === 'i' || character === 'o' || character === 'u') { count++; } } return count; } // Function to check a string for duplicate occurances of one of it's letters function checkDuplicateLetters(string){ for (var i = 0; i < string.length; i++) { var letter = string[i]; var regExp = new RegExp(letter + letter, 'g'); if (string.match(regExp)) { return true; } } return false; } var niceStrings = strings; // For each gift in puzzle input for (var i = 0; i < strings.length; i++) { // Split each dimension line in each parts (width, heigth, length) var currentString = strings[i]; // Check if currentString has at least three vowels if (getVowelCount(currentString) < 3) { niceStrings.splice(niceStrings.indexOf(currentString), 1); } // Check if there are any duplicate letters if (!checkDuplicateLetters(currentString)) { niceStrings.splice(niceStrings.indexOf(currentString), 1); } }; console.log(niceStrings.length);
/* Puzzle input - check /input/day5.js */ var input = require('./input/day5.js'); /* Variables */ // Split input by new line character ("\n") var strings = input.split('\n'); /* Functions */ // Function to return the vowel count function getVowelCount(string){ var count = 0; for (var i = 0; i < string.length; i++) { var character = string[i]; if (character === 'a' || character === 'e' || character === 'i' || character === 'o' || character === 'u') { count++; } } return count; } var niceStrings = strings; // For each gift in puzzle input for (var i = 0; i < strings.length; i++) { // Split each dimension line in each parts (width, heigth, length) var currentString = strings[i]; // Check if currentString has at least three vowels if (getVowelCount(currentString) < 3) { niceStrings.splice(niceStrings.indexOf(currentString), 1); } }; console.log(niceStrings);
Fix a case where AttrMorph was being extended
import Ember from "ember-metal/core"; import DOMHelper from "dom-helper"; import o_create from 'ember-metal/platform/create'; var HTMLBarsAttrMorph = DOMHelper.prototype.AttrMorphClass; export var styleWarning = '' + 'Binding style attributes may introduce cross-site scripting vulnerabilities; ' + 'please ensure that values being bound are properly escaped. For more information, ' + 'including how to disable this warning, see ' + 'http://emberjs.com/deprecations/v1.x/#toc_binding-style-attributes.'; function EmberAttrMorph(element, attrName, domHelper, namespace) { HTMLBarsAttrMorph.call(this, element, attrName, domHelper, namespace); this.streamUnsubscribers = null; } var proto = EmberAttrMorph.prototype = o_create(HTMLBarsAttrMorph.prototype); proto.HTMLBarsAttrMorph$setContent = HTMLBarsAttrMorph.prototype.setContent; proto._deprecateEscapedStyle = function EmberAttrMorph_deprecateEscapedStyle(value) { Ember.warn( styleWarning, (function(name, value, escaped) { // SafeString if (value && value.toHTML) { return true; } if (name !== 'style') { return true; } return !escaped; }(this.attrName, value, this.escaped)) ); }; proto.setContent = function EmberAttrMorph_setContent(value) { this._deprecateEscapedStyle(value); this.HTMLBarsAttrMorph$setContent(value); }; export default EmberAttrMorph;
import Ember from "ember-metal/core"; import DOMHelper from "dom-helper"; import o_create from 'ember-metal/platform/create'; var HTMLBarsAttrMorph = DOMHelper.prototype.AttrMorphClass; export var styleWarning = '' + 'Binding style attributes may introduce cross-site scripting vulnerabilities; ' + 'please ensure that values being bound are properly escaped. For more information, ' + 'including how to disable this warning, see ' + 'http://emberjs.com/deprecations/v1.x/#toc_binding-style-attributes.'; function EmberAttrMorph(element, attrName, domHelper, namespace) { HTMLBarsAttrMorph.call(this, element, attrName, domHelper, namespace); } var proto = EmberAttrMorph.prototype = o_create(HTMLBarsAttrMorph.prototype); proto.HTMLBarsAttrMorph$setContent = HTMLBarsAttrMorph.prototype.setContent; proto._deprecateEscapedStyle = function EmberAttrMorph_deprecateEscapedStyle(value) { Ember.warn( styleWarning, (function(name, value, escaped) { // SafeString if (value && value.toHTML) { return true; } if (name !== 'style') { return true; } return !escaped; }(this.attrName, value, this.escaped)) ); }; proto.setContent = function EmberAttrMorph_setContent(value) { this._deprecateEscapedStyle(value); this.HTMLBarsAttrMorph$setContent(value); }; export default EmberAttrMorph;
Update service worker URLs to cache
let CACHE_NAME = 'order-splitter-cache-%%GULP_INJECT_VERSION%%'; let urlsToCache = ['/', '/styles.css', '/all.min.js']; self.addEventListener('install', function(event) { event.waitUntil( caches.open(CACHE_NAME) .then(function(cache) { console.log('Opened cache'); return cache.addAll(urlsToCache); }) ); }); self.addEventListener('activate', function(event) { let cacheWhiteList = [CACHE_NAME]; event.waitUntil( caches.keys().then(function(keyList) { return Promise.all( keyList.filter(function(key) { return cacheWhiteList.indexOf(key) === -1; }).map(function(key) { return caches.delete(key); }) ); }) ); }); self.addEventListener('fetch', function(event) { event.respondWith( caches.match(event.request) .then(function(response) { // Cache hit - return response if (response) { return response; } return fetch(event.request); }) ); });
let CACHE_NAME = 'order-splitter-cache-%%GULP_INJECT_VERSION%%'; let urlsToCache = ['/', '/main.js']; self.addEventListener('install', function(event) { event.waitUntil( caches.open(CACHE_NAME) .then(function(cache) { console.log('Opened cache'); return cache.addAll(urlsToCache); }) ); }); self.addEventListener('activate', function(event) { let cacheWhiteList = [CACHE_NAME]; event.waitUntil( caches.keys().then(function(keyList) { return Promise.all( keyList.filter(function(key) { return cacheWhiteList.indexOf(key) === -1; }).map(function(key) { return caches.delete(key); }) ); }) ); }); self.addEventListener('fetch', function(event) { event.respondWith( caches.match(event.request) .then(function(response) { // Cache hit - return response if (response) { return response; } return fetch(event.request); }) ); });
Fix Add MW Deployment not working The correct variable holding the reference to the file is `filePath` instead of just `file`. (transferred from ManageIQ/manageiq@a6b7e937a1d155cc9fb426cfb6511588f3968aa8)
ManageIQ.angular.app.controller('mwAddDeploymentController', MwAddDeploymentController); MwAddDeploymentController.$inject = ['$scope', '$http', 'miqService']; function MwAddDeploymentController($scope, $http, miqService) { $scope.$on('mwAddDeploymentEvent', function(event, data) { var fd = new FormData(); fd.append('file', data.filePath); fd.append('id', data.serverId); fd.append('enabled', data.enableDeployment); fd.append('runtimeName', data.runtimeName); $http.post('/middleware_server/add_deployment', fd, { transformRequest: angular.identity, headers: {'Content-Type': undefined} }) .then( function() { // success miqService.miqFlash('success', 'Deployment "' + data.runtimeName + '" has been initiated on this server.'); }, function() { // error miqService.miqFlash('error', 'Unable to deploy "' + data.runtimeName + '" on this server.'); }) .finally(function() { angular.element("#modal_d_div").modal('hide'); miqService.sparkleOff(); }); }); }
ManageIQ.angular.app.controller('mwAddDeploymentController', MwAddDeploymentController); MwAddDeploymentController.$inject = ['$scope', '$http', 'miqService']; function MwAddDeploymentController($scope, $http, miqService) { $scope.$on('mwAddDeploymentEvent', function(event, data) { var fd = new FormData(); fd.append('file', data.file); fd.append('id', data.serverId); fd.append('enabled', data.enableDeployment); fd.append('runtimeName', data.runtimeName); $http.post('/middleware_server/add_deployment', fd, { transformRequest: angular.identity, headers: {'Content-Type': undefined} }) .then( function() { // success miqService.miqFlash('success', 'Deployment "' + data.runtimeName + '" has been initiated on this server.'); }, function() { // error miqService.miqFlash('error', 'Unable to deploy "' + data.runtimeName + '" on this server.'); }) .finally(function() { angular.element("#modal_d_div").modal('hide'); miqService.sparkleOff(); }); }); }
Fix sdk restarted true bug
/* * Copyright (c) 2016 Applivery * * 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.applivery.applvsdklib.domain.appconfig.update; import com.applivery.applvsdklib.AppliverySdk; /** * Created by Sergio Martinez Rodriguez * Date 11/1/16. */ public class AppConfigChecker { private final LastConfigReader lastConfigReader; public AppConfigChecker(LastConfigReader lastConfigReader) { this.lastConfigReader = lastConfigReader; } public boolean shouldCheckAppConfigForUpdate() { if (AppliverySdk.isSdkFirstTime()) { AppliverySdk.setSdkFirstTimeFalse(); AppliverySdk.setSdkRestartedFalse(); return false; } if (AppliverySdk.isSdkRestarted()) { AppliverySdk.setSdkRestartedFalse(); return true; } if (lastConfigReader.notExistsLastConfig()) { return true; } return AppliverySdk.getCheckForUpdatesBackground(); } }
/* * Copyright (c) 2016 Applivery * * 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.applivery.applvsdklib.domain.appconfig.update; import com.applivery.applvsdklib.AppliverySdk; /** * Created by Sergio Martinez Rodriguez * Date 11/1/16. */ public class AppConfigChecker { private final LastConfigReader lastConfigReader; public AppConfigChecker(LastConfigReader lastConfigReader) { this.lastConfigReader = lastConfigReader; } public boolean shouldCheckAppConfigForUpdate() { if (AppliverySdk.isSdkFirstTime()) { AppliverySdk.setSdkFirstTimeFalse(); return false; } if (AppliverySdk.isSdkRestarted()) { AppliverySdk.setSdkRestartedFalse(); return true; } if (lastConfigReader.notExistsLastConfig()) { return true; } return AppliverySdk.getCheckForUpdatesBackground(); } }
Use an actual url for backpack host so storage doesnt explode
import path from 'path'; import SeleniumHelper from '../helpers/selenium-helper'; const { clickText, getDriver, getLogs, loadUri } = new SeleniumHelper(); const uri = path.resolve(__dirname, '../../build/index.html'); let driver; describe('Working with the how-to library', () => { beforeAll(() => { driver = getDriver(); }); afterAll(async () => { await driver.quit(); }); test('Backpack is "Coming Soon" without backpack host param', async () => { await loadUri(uri); // Check that the backpack header is visible and wrapped in a coming soon tooltip await clickText('Backpack', '*[@data-for="backpack-tooltip"]'); const logs = await getLogs(); await expect(logs).toEqual([]); }); test('Backpack can be expanded with backpack host param', async () => { await loadUri(`${uri}?backpack_host=https://backpack.scratch.mit.edu`); // Try activating the backpack from the costumes tab to make sure it isn't pushed off await clickText('Costumes'); // Check that the backpack header is visible and wrapped in a coming soon tooltip await clickText('Backpack'); // Not wrapped in tooltip await clickText('Backpack is empty'); // Make sure it can expand, is empty const logs = await getLogs(); await expect(logs).toEqual([]); }); });
import path from 'path'; import SeleniumHelper from '../helpers/selenium-helper'; const { clickText, getDriver, getLogs, loadUri } = new SeleniumHelper(); const uri = path.resolve(__dirname, '../../build/index.html'); let driver; describe('Working with the how-to library', () => { beforeAll(() => { driver = getDriver(); }); afterAll(async () => { await driver.quit(); }); test('Backpack is "Coming Soon" without backpack host param', async () => { await loadUri(uri); // Check that the backpack header is visible and wrapped in a coming soon tooltip await clickText('Backpack', '*[@data-for="backpack-tooltip"]'); const logs = await getLogs(); await expect(logs).toEqual([]); }); test('Backpack can be expanded with backpack host param', async () => { await loadUri(`${uri}?backpack_host=some-value`); // Try activating the backpack from the costumes tab to make sure it isn't pushed off await clickText('Costumes'); // Check that the backpack header is visible and wrapped in a coming soon tooltip await clickText('Backpack'); // Not wrapped in tooltip await clickText('Backpack is empty'); // Make sure it can expand, is empty const logs = await getLogs(); await expect(logs).toEqual([]); }); });
Change auth on team invite request to check if the user is team admin rather that system admin
<?php namespace {{App\}}Http\Requests; use Auth; use Illuminate\Foundation\Http\FormRequest; class UserInviteRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { if (Auth::user()->isTeamAdmin($this->route('id'))) { return true; } return false; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'email' => 'required', ]; } }
<?php namespace {{App\}}Http\Requests; use Auth; use Illuminate\Foundation\Http\FormRequest; class UserInviteRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { if (Auth::user()->can('admin')) { return true; } return false; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'email' => 'required', ]; } }
Simplify main method, wait until status logger completes Hint: It never will.
import logging from flist import account_login, start_chat, opcode import asyncio from sys import argv logger = logging.getLogger('status_watcher') logging.getLogger('').setLevel('DEBUG') async def log_status_async(status_provider): async for message in status_provider: logger.info("%(character)s is %(status)s: %(statusmsg)s", message) async def connect(account, password, character_name): account = await account_login(account, password) character = account.get_character(character_name) chat = await start_chat(character) return chat async def status_logger(): logger.info("Starting chat.") chat = await connect(argv[1], argv[2], argv[3]) logger.info("Attaching log_status method.") status_provider = chat.watch(opcode.STATUS) await log_status_async(status_provider) if __name__ == '__main__': logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s') logger.setLevel(logging.INFO) asyncio.get_event_loop().run_until_complete(status_logger())
import logging from flist import account_login, start_chat, opcode import asyncio logger = logging.getLogger('status_watcher') logging.getLogger('').setLevel('DEBUG') async def log_status_async(status_provider): async for message in status_provider: logger.info("%(character)s is %(status)s: %(statusmsg)s", message) async def connect(account, password, character_name): account = await account_login(account, password) character = account.get_character(character_name) logger.info("Starting chat.") chat = await start_chat(character) logger.info("Attaching log_status method.") status_provider = chat.watch(opcode.STATUS) await log_status_async(status_provider) if __name__ == '__main__': logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s') logger.setLevel(logging.INFO) from sys import argv coroutine = connect(argv[1], argv[2], argv[3]) asyncio.get_event_loop().run_until_complete(coroutine)
Fix lint to work with absolute paths (tslint VS Code plugin)
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const Lint = require("tslint"); // These files aren't part of the debug adapters and should probably be separated // into another folder at some point. const excludedPaths = ["src/debug/flutter_run.ts", "src/debug/flutter_test.ts"] class Rule extends Lint.Rules.AbstractRule { apply(sourceFile) { if (sourceFile.fileName.indexOf("src/debug/") !== -1 && excludedPaths.indexOf(sourceFile.fileName) === -1) { return this.applyWithWalker(new NoVsCodeInDebuggers(sourceFile, this.getOptions())); } } } Rule.FAILURE_STRING = "Do not import vscode into debug adapters as they may be run in a separate process to VS Code."; class NoVsCodeInDebuggers extends Lint.RuleWalker { visitImportDeclaration(node) { if (node.moduleSpecifier.text === "vscode") { this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING)); } } } exports.Rule = Rule;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const Lint = require("tslint"); // These files aren't part of the debug adapters and should probably be separated // into another folder at some point. const excludedPaths = ["src/debug/flutter_run.ts", "src/debug/flutter_test.ts"] class Rule extends Lint.Rules.AbstractRule { apply(sourceFile) { if (sourceFile.fileName.indexOf("src/debug/") === 0 && excludedPaths.indexOf(sourceFile.fileName) === -1) { return this.applyWithWalker(new NoVsCodeInDebuggers(sourceFile, this.getOptions())); } } } Rule.FAILURE_STRING = "Do not import vscode into debug adapters as they may be run in a separate process to VS Code."; class NoVsCodeInDebuggers extends Lint.RuleWalker { visitImportDeclaration(node) { if (node.moduleSpecifier.text === "vscode") { this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING)); } } } exports.Rule = Rule;
Include script-src unsafe-eval to allow underscore templating Long term, we should pre-compile with webpack to avoid needing this
# define flask extensions in separate file, to resolve import dependencies from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() from flask_caching import Cache cache = Cache() from flask_assets import Environment assets = Environment() from flask_babel import Babel babel = Babel() from flask_mail import Mail mail = Mail() from flask_login import LoginManager login_manager = LoginManager() from flask_restless import APIManager rest = APIManager() from flask_wtf.csrf import CSRFProtect csrf = CSRFProtect() from flask_store import Store store = Store() from flask_rq2 import RQ rq = RQ() from flask_talisman import Talisman CALLPOWER_CSP = { 'default-src':'\'self\'', 'script-src':['\'self\'', '\'unsafe-inline\'', '\'unsafe-eval\'', 'cdnjs.cloudflare.com', 'media.twiliocdn.com'], 'style-src': ['\'self\'', '\'unsafe-inline\'', 'fonts.googleapis.com'], 'font-src': ['\'self\'', 'fonts.gstatic.com'], } # unsafe-inline needed to render <script> tags without nonce # unsafe-eval needed to run bootstrap templates talisman = Talisman()
# define flask extensions in separate file, to resolve import dependencies from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() from flask_caching import Cache cache = Cache() from flask_assets import Environment assets = Environment() from flask_babel import Babel babel = Babel() from flask_mail import Mail mail = Mail() from flask_login import LoginManager login_manager = LoginManager() from flask_restless import APIManager rest = APIManager() from flask_wtf.csrf import CSRFProtect csrf = CSRFProtect() from flask_store import Store store = Store() from flask_rq2 import RQ rq = RQ() from flask_talisman import Talisman CALLPOWER_CSP = { 'default-src':'\'self\'', 'script-src':['\'self\'', '\'unsafe-inline\'', 'cdnjs.cloudflare.com', 'media.twiliocdn.com'], 'style-src': ['\'self\'', '\'unsafe-inline\'', 'fonts.googleapis.com'], 'font-src': ['\'self\'', 'fonts.gstatic.com'], } talisman = Talisman()
Update Command: ping - added heartbeat ping, removed performance-now usage
const Command = require('../Command'); class PingCommand extends Command { constructor(bot) { super(bot); this.props.help = { name: 'ping', description: 'ping, pong', usage: 'ping', }; } run(msg) { const startTime = msg.createdTimestamp; return msg.channel.sendMessage(`⏱ Pinging...`).then(message => { const endTime = message.createdTimestamp; let difference = (endTime - startTime).toFixed(0); if (difference > 1000) difference = (difference / 1000).toFixed(0); let differenceText = (endTime - startTime) > 999 ? 's' : 'ms'; return message.edit(`⏱ Ping, Pong! The message round-trip took ${difference} ${differenceText}. The heartbeat ping is ${this.bot.ping.toFixed(0)}ms`); }); } } module.exports = PingCommand;
const now = require('performance-now'); const Command = require('../Command'); class PingCommand extends Command { constructor(bot) { super(bot); this.props.help = { name: 'ping', description: 'ping, pong', usage: 'ping', }; } run(msg) { const startTime = now(); return msg.channel.sendMessage(`⏱ Pinging...`).then(message => { const endTime = now(); let difference = (endTime - startTime).toFixed(0); if (difference > 1000) difference = (difference / 1000).toFixed(0); let differenceText = (endTime - startTime) > 999 ? 's' : 'ms'; return message.edit(`⏱ Ping, Pong! Took ${difference} ${differenceText}`); }); } } module.exports = PingCommand;
Add "production" target for gulp for production use
var gulp = require('gulp'), connect = require('gulp-connect'), proxy = require('http-proxy-middleware'); gulp.task('connect', function () { connect.server({ port: 4200, host: "0.0.0.0", livereload: true, middleware: function (connect, opt) { return [ proxy('http://www.radio-browser.info/webservice', { changeOrigin: true }) ]; } }); }); gulp.task('production', function () { connect.server({ port: 4200, host: "0.0.0.0", middleware: function (connect, opt) { return [ proxy('http://www.radio-browser.info/webservice', { changeOrigin: true }) ]; } }); }); gulp.task('reload', function () { gulp.src('./*.html') .pipe(connect.reload()); }); gulp.task('watch', function () { gulp.watch([ './controllers/**/*', './css/**/*', './partials/**/*', './services/**/*', './templates/**/*', './*.html', './*.js' ], [ 'reload' ]); }); gulp.task('default', [ 'connect', 'watch' ]);
var gulp = require('gulp'), connect = require('gulp-connect'), proxy = require('http-proxy-middleware'); gulp.task('connect', function () { connect.server({ port: 4200, host: "0.0.0.0", livereload: true, middleware: function (connect, opt) { return [ proxy('http://www.radio-browser.info/webservice', { changeOrigin: true }) ]; } }); }); gulp.task('reload', function () { gulp.src('./*.html') .pipe(connect.reload()); }); gulp.task('watch', function () { gulp.watch([ './controllers/**/*', './css/**/*', './partials/**/*', './services/**/*', './templates/**/*', './*.html', './*.js' ], [ 'reload' ]); }); gulp.task('default', [ 'connect', 'watch' ]);
Update for compatibility with python 3
#!/usr/bin/python import pymongo import bson import time import sys from mongo_connector import util mongo_url = 'mongodb://localhost:27017' if len(sys.argv) == 1: print "First argument is mongodb connection string, i.e. localhost:27017. Assuming localhost:27017..." if len(sys.argv) >= 2: mongo_url = sys.argv[1] client = pymongo.MongoClient(mongo_url) rs_name = client.admin.command('ismaster')['setName'] print('Found Replica Set name: {}'.format(str(rs_name))) print('Now checking for the latest oplog entry...') oplog = client.local.oplog.rs last_oplog = oplog.find().sort('$natural', pymongo.DESCENDING).limit(-1).next() print('Found the last oplog ts: {}'.format(str(last_oplog['ts']))) last_ts = util.bson_ts_to_long(last_oplog['ts']) out_str='["{}", {}]'.format(str(rs_name), str(last_ts) ) print('Writing all to file oplog.timestamp.last in the format required for mongo-connector') f = open('./oplog.timestamp.last', 'w') f.write(out_str) f.close() print('All done!')
#!/usr/bin/python import pymongo import bson import time import sys from mongo_connector import util mongo_url = 'mongodb://localhost:27017' if len(sys.argv) == 1: print "First argument is mongodb connection string, i.e. localhost:27017. Assuming localhost:27017..." if len(sys.argv) >= 2: mongo_url = sys.argv[1] client = pymongo.MongoClient(mongo_url) rs_name = client.admin.command('ismaster')['setName'] print 'Found Replica Set name: {}'.format(str(rs_name)) print 'Now checking for the latest oplog entry...' oplog = client.local.oplog.rs last_oplog = oplog.find().sort('$natural', pymongo.DESCENDING).limit(-1).next() print 'Found the last oplog ts: {}'.format(str(last_oplog['ts'])) last_ts = util.bson_ts_to_long(last_oplog['ts']) out_str='["{}", {}]'.format(str(rs_name), str(last_ts) ) print 'Writing all to file oplog.timestamp.last in the format required for mongo-connector' f = open('./oplog.timestamp.last', 'w') f.write(out_str) f.close() print 'All done!'
Update URL to work correctly.
import * as types from './ActionTypes' import axios from 'axios' export function addPattern(name, pattern) { return { type: types.ADD_PATTERN, name: name, pattern: pattern } } export function selectPattern(pattern) { return { type: types.SELECT_PATTERN, name: pattern } } export function deselectPattern(pattern) { return { type: types.DESELECT_PATTERN, name: pattern } } export function changeText(text) { return function(dispatch) { dispatch(requestData(text)) } } function requestData() { return { type: types.REQUEST_DATA } } function receiveData(json) { return { type: types.RECEIVE_DATA, data: json } } function receiveError(json) { return { type: types.RECEIVE_ERROR, data: json } } export function evaluateText(pattern, text) { return function(dispatch) { dispatch(requestData()) return axios.post('http://api.riveter.site/v1/process/', { pattern: pattern, textContent: text }) .then(function(data) { dispatch(receiveData(data)) }) .catch(function(err) { dispatch(receiveError(err)) }) } }
import * as types from './ActionTypes' import axios from 'axios' export function addPattern(name, pattern) { return { type: types.ADD_PATTERN, name: name, pattern: pattern } } export function selectPattern(pattern) { return { type: types.SELECT_PATTERN, name: pattern } } export function deselectPattern(pattern) { return { type: types.DESELECT_PATTERN, name: pattern } } export function changeText(text) { return function(dispatch) { dispatch(requestData(text)) } } function requestData() { return { type: types.REQUEST_DATA } } function receiveData(json) { return { type: types.RECEIVE_DATA, data: json } } function receiveError(json) { return { type: types.RECEIVE_ERROR, data: json } } export function evaluateText(pattern, text) { return function(dispatch) { dispatch(requestData()) return axios.post('api.riveter.site/v1/process/', { pattern: pattern, textContent: text }) .then(function(data) { dispatch(receiveData(data)) }) .catch(function(err) { dispatch(receiveError(err)) }) } }
Make override more global, not just within patch scope
# After this function, any futher calls to import RPi.GPIO # will instead import .gpio.Gpio instead def patch_fake_gpio(): print('Warning, not in RPi, using mock GPIO') # Idea taken from RPLCD who commented it as being from: # reddit.com/r/Python/comments/5eddp5/mock_testing_rpigpio import mock from .gpio import Gpio as FakeGpio MockRPi = mock.MagicMock() MockRPi.GPIO = FakeGpio() modules = { 'RPi': MockRPi, 'RPi.GPIO': MockRPi.GPIO, } sys.modules.update(modules) is_active = True # Do the test if we have RPi.GPIO or not ON_RPI = True try: import RPi.GPIO except ImportError: ON_RPI = False if not ON_RPI: patch_fake_gpio() # now that the patching is done, we can import RPLCD anywhere
# After this function, any futher calls to import RPi.GPIO # will instead import .gpio.Gpio instead def patch_fake_gpio(): print('Warning, not in RPi, using mock GPIO') # Idea taken from RPLCD who commented it as being from: # reddit.com/r/Python/comments/5eddp5/mock_testing_rpigpio import mock from .gpio import Gpio as FakeGpio MockRPi = mock.MagicMock() MockRPi.GPIO = FakeGpio() modules = { 'RPi': MockRPi, 'RPi.GPIO': MockRPi.GPIO, } patcher = mock.patch.dict('sys.modules', modules) patcher.start() # Do the test if we have RPi.GPIO or not ON_RPI = True try: import RPi.GPIO except ImportError: ON_RPI = False if not ON_RPI: patch_fake_gpio() # now that the patching is done, we can import RPLCD anywhere
Put sub-index immediately after limit on query
var r = require('rethinkdb'); // Number of seconds after which Reddit will archive an article // (180 days): https://github.com/reddit/reddit/commit/b7b24d2e9fa06ba37ea78e0275dce86d95158e64 var archiveLimit = 180 * 24 * 60 * 60; exports.mostUrgentSubject = r.table('subjects') .between(r.now().sub(archiveLimit),r.now(),{index:'article_created'}) .orderBy(r.desc(function(subject){ var staleness = subject('last_checked').sub(r.now()); var age = subject('article_created').sub(r.now()); return staleness.div(age); })) .limit(1)(0) .merge(function(subject){ return { forfeits: r.table('forfeits').getAll( subject('name'),{index: 'subject'}) .filter(function(forfeit){ return r.not(forfeit('withdrawn').default(false))}) .merge(function(forfeit){ return { reply_klaxons: r.table('klaxons').getAll( forfeit('id'),{index:'forfeits'}) .map(function(klaxon){return klaxon('parent')('id')}) .coerceTo('array') }; }).coerceTo('array') }; }) .default(null);
var r = require('rethinkdb'); // Number of seconds after which Reddit will archive an article // (180 days): https://github.com/reddit/reddit/commit/b7b24d2e9fa06ba37ea78e0275dce86d95158e64 var archiveLimit = 180 * 24 * 60 * 60; exports.mostUrgentSubject = r.table('subjects') .between(r.now().sub(archiveLimit),r.now(),{index:'article_created'}) .orderBy(r.desc(function(subject){ var staleness = subject('last_checked').sub(r.now()); var age = subject('article_created').sub(r.now()); return staleness.div(age); })).limit(1).merge(function(subject){ return { forfeits: r.table('forfeits').getAll( subject('name'),{index: 'subject'}) .filter(function(forfeit){ return r.not(forfeit('withdrawn').default(false))}) .merge(function(forfeit){ return { reply_klaxons: r.table('klaxons').getAll( forfeit('id'),{index:'forfeits'}) .map(function(klaxon){return klaxon('parent')('id')}) .coerceTo('array') }; }).coerceTo('array') }; })(0).default(null);
Allow click-drag on polygons to still move the map around
/** * * Displaying popups * */ MapPopup = { map: null, layer: null, init: function(m, l) { this.map = m; this.layer = l; m.addControl(new OpenLayers.Control.SelectFeature(l, {id: 'selector', onSelect: MapPopup.createPopup, onUnselect: MapPopup.destroyPopup })); m.getControl('selector').activate(); m.getControl('selector').handlers.feature.stopDown = false; // Allow click-drag on polygons to move the map }, createPopup: function(feature) { feature.popup = new OpenLayers.Popup.FramedCloud("pop", feature.geometry.getBounds().getCenterLonLat(), null, '<h3><a href="' + feature.attributes.url + '">' + feature.attributes.title + '</a></h3>' + '<p>created by <a href="' + feature.attributes.created_by_url + '">' + feature.attributes.created_by + '</p>', null, true, function() { MapPopup.map.getControl('selector').unselectAll(); } ); map.addPopup(feature.popup); }, destroyPopup: function(feature) { feature.popup.destroy(); feature.popup = null; } }
/** * * Displaying popups * */ MapPopup = { map: null, layer: null, init: function(m, l) { this.map = m; this.layer = l; m.addControl(new OpenLayers.Control.SelectFeature(l, {id: 'selector', onSelect: MapPopup.createPopup, onUnselect: MapPopup.destroyPopup })); m.getControl('selector').activate(); }, createPopup: function(feature) { feature.popup = new OpenLayers.Popup.FramedCloud("pop", feature.geometry.getBounds().getCenterLonLat(), null, '<h3><a href="' + feature.attributes.url + '">' + feature.attributes.title + '</a></h3>' + '<p>created by <a href="' + feature.attributes.created_by_url + '">' + feature.attributes.created_by + '</p>', null, true, function() { MapPopup.map.getControl('selector').unselectAll(); } ); map.addPopup(feature.popup); }, destroyPopup: function(feature) { feature.popup.destroy(); feature.popup = null; } }
[confirm] Rename handlers to math confirmation popin props.
import React, {Component, PropTypes} from 'react'; import ReactDOM from 'react-dom'; import {component as ConfirmationModal} from '../../application/confirmation-popin'; import Connect from '../../behaviours/store/connect'; import {application} from 'focus-core'; const {builtInStore: applicationStore} = application; const propTypes = { isVisible: PropTypes.bool, ConfirmContentComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.string]), handleCancel: PropTypes.func.isRequired, handleConfirm: PropTypes.func.isRequired }; const defaultProps = { isVisible: false, ConfirmContentComponent: null }; @Connect( [{store: applicationStore, properties: ['confirmConfig']}], () => { const {isVisible = false, Content: ConfirmContentComponent = null, handleCancel: cancelHandler, handleConfirm: confirmHandler} = applicationStore.getConfirmConfig() || {}; return {isVisible, ConfirmContentComponent, cancelHandler, confirmHandler}; } ) class ConfirmWrapper extends Component { render() { console.log('confirm wrapper', this.props); const {isVisible, ConfirmContentComponent, cancelHandler, confirmHandler} = this.props; return isVisible ? <ConfirmationModal open={true} cancelHandler={cancelHandler} confirmHandler={confirmHandler}>{ConfirmContentComponent ? <ConfirmContentComponent /> : null}</ConfirmationModal> : null; } } ConfirmWrapper.propTypes = propTypes; ConfirmWrapper.defaultProps = defaultProps; ConfirmWrapper.displayName = 'ConfirmWrapper'; export default ConfirmWrapper;
import React, {Component, PropTypes} from 'react'; import ReactDOM from 'react-dom'; import {component as ConfirmationModal} from '../../application/confirmation-popin'; import Connect from '../../behaviours/store/connect'; import {application} from 'focus-core'; const {builtInStore: applicationStore} = application; const propTypes = { isVisible: PropTypes.bool, ConfirmContentComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.string]), handleCancel: PropTypes.func.isRequired, handleConfirm: PropTypes.func.isRequired }; const defaultProps = { isVisible: false, ConfirmContentComponent: null }; @Connect( [{store: applicationStore, properties: ['confirmConfig']}], () => { const {isVisible = false, Content: ConfirmContentComponent = null, handleCancel, handleConfirm} = applicationStore.getConfirmConfig() || {}; const exp = {isVisible, ConfirmContentComponent, handleCancel, handleConfirm}; return exp; } ) class ConfirmWrapper extends Component { render() { console.log('confirm wrapper') const {isVisible, ConfirmContentComponent, handleCancel, handleConfirm} = this.props; return isVisible ? <ConfirmationModal open={true} handleCancel={handleCancel} handleConfirm={handleConfirm}>{ConfirmContentComponent ? <ConfirmContentComponent /> : <div>Hello</div>}</ConfirmationModal> : null; } } ConfirmWrapper.propTypes = propTypes; ConfirmWrapper.defaultProps = defaultProps; ConfirmWrapper.displayName = 'ConfirmWrapper'; export default ConfirmWrapper;
Add Null check and give decent debug message if COLUMN env var cannot be parsed.
/* * Copyright 2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.internal.console; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class UnixConsoleMetaData implements ConsoleMetaData { public static final Logger LOGGER = LoggerFactory.getLogger(UnixConsoleMetaData.class); public int getCols() { final String columns = System.getenv("COLUMNS"); if (columns != null) { try { return Integer.parseInt(columns); } catch (NumberFormatException ex) { LOGGER.debug("Cannot parse COLUMNS environment variable to get console width. Value: '%s'", columns); } } return 0; } }
/* * Copyright 2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.internal.console; public class UnixConsoleMetaData implements ConsoleMetaData { public int getCols() { final String width = System.getenv("COLUMNS"); try{ return Integer.parseInt(width); }catch(NumberFormatException ex){ return 0; } } }
Simplify test for controller_map key within $config['view_manager'].
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Mvc\Service; use ArrayAccess; use Zend\ServiceManager\FactoryInterface; use Zend\Mvc\View\Http\InjectTemplateListener; use Zend\ServiceManager\ServiceLocatorInterface; class InjectTemplateListenerFactory implements FactoryInterface { /** * Create and return an InjectTemplateListener instance. * * @param ServiceLocatorInterface $serviceLocator * @return InjectTemplateListener */ public function createService(ServiceLocatorInterface $serviceLocator) { $listener = new InjectTemplateListener(); $config = $serviceLocator->get('Config'); if (isset($config['view_manager']['controller_map']) && (is_array($config['view_manager']['controller_map'])) ) { $listener->setControllerMap($config['view_manager']['controller_map']); } return $listener; } }
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Mvc\Service; use ArrayAccess; use Zend\ServiceManager\FactoryInterface; use Zend\Mvc\View\Http\InjectTemplateListener; use Zend\ServiceManager\ServiceLocatorInterface; class InjectTemplateListenerFactory implements FactoryInterface { /** * Create and return an InjectTemplateListener instance. * * @param ServiceLocatorInterface $serviceLocator * @return InjectTemplateListener */ public function createService(ServiceLocatorInterface $serviceLocator) { $listener = new InjectTemplateListener(); $config = $serviceLocator->get('Config'); if (isset($config['view_manager']) && (is_array($config['view_manager']) || $config['view_manager'] instanceof ArrayAccess) && isset($config['view_manager']['controller_map']) && (is_array($config['view_manager']['controller_map'])) ) { $listener->setControllerMap($config['view_manager']['controller_map']); } return $listener; } }
Add Arabic and Japanese support for Personality Insights
/* * Copyright 2015 IBM Corp. All Rights Reserved. * * 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.ibm.watson.developer_cloud.personality_insights.v2.model; import com.google.gson.annotations.SerializedName; /** * Personality Insights supported languages for {@link Profile}s. */ public enum AcceptLanguage { /** english. */ @SerializedName("en") ENGLISH("en"), /** spanish. */ @SerializedName("es") SPANISH("es"), /** arabic. */ @SerializedName("ar") ARABIC("ar"), /** japanese */ @SerializedName("ja") JAPANESE("ja"); private final String text; /** * @param text */ private AcceptLanguage(final String text) { this.text = text; } /* * (non-Javadoc) * * @see java.lang.Enum#toString() */ @Override public String toString() { return text; } }
/* * Copyright 2015 IBM Corp. All Rights Reserved. * * 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.ibm.watson.developer_cloud.personality_insights.v2.model; import com.google.gson.annotations.SerializedName; /** * Personality Insights supported languages for {@link Profile}s. */ public enum AcceptLanguage { /** english. */ @SerializedName("en") ENGLISH("en"), /** spanish. */ @SerializedName("es") SPANISH("es"); private final String text; /** * @param text */ private AcceptLanguage(final String text) { this.text = text; } /* * (non-Javadoc) * * @see java.lang.Enum#toString() */ @Override public String toString() { return text; } }
Comment out projects tab note that will not apply to Expo iOS yet fbshipit-source-id: 86b1d43
import { User as UserManager } from 'xdl'; import chalk from 'chalk'; import log from './log'; export default async function printRunInstructionsAsync() { let user = await UserManager.getCurrentUserAsync(); // If no user, we are offline and can't connect if (user) { log.newLine(); log(chalk.bold('Instructions to open this project on a physical device')); log(`${chalk.underline('Android devices')}: scan the above QR code.`); log( `${chalk.underline('iOS devices')}: run ${chalk.bold( 'exp send -s <your-phone-number-or-email>' )} to send the URL to your device.` ); // NOTE(brentvatne) Uncomment this when we update iOS client // log( // `Alternatively, sign in to your account (${chalk.bold( // user.username // )}) in the latest version of the Expo client on your iOS or Android device. Your projects will automatically appear in the "Projects" tab.` // ); } log.newLine(); log(chalk.bold('Instructions to open this project on a simulator')); log( `If you already have the simulator installed, run ${chalk.bold('exp ios')} or ${chalk.bold( 'exp android' )} in this project directory in another terminal window.` ); log.newLine(); }
import { User as UserManager } from 'xdl'; import chalk from 'chalk'; import log from './log'; export default async function printRunInstructionsAsync() { let user = await UserManager.getCurrentUserAsync(); // If no user, we are offline and can't connect if (user) { log.newLine(); log(chalk.bold('Instructions to open this project on a physical device')); log(`${chalk.underline('Android devices')}: scan the above QR code.`); log( `${chalk.underline('iOS devices')}: run ${chalk.bold( 'exp send -s <your-phone-number-or-email>' )} to send the URL to your device.` ); log( `Alternatively, sign in to your account (${chalk.bold( user.username )}) in the latest version of the Expo client on your iOS or Android device. Your projects will automatically appear in the "Projects" tab.` ); } log.newLine(); log(chalk.bold('Instructions to open this project on a simulator')); log( `If you already have the simulator installed, run ${chalk.bold('exp ios')} or ${chalk.bold( 'exp android' )} in this project directory in another terminal window.` ); log.newLine(); }
Add json tags to BackupSchedule
package brain import ( "github.com/BytemarkHosting/bytemark-client/lib/prettyprint" "io" ) // BackupSchedule represents a schedule to take backups on. It is represented as a start date in YYYY-MM-DD hh:mm:ss format (and assuming UK timezones of some kind.) type BackupSchedule struct { StartDate string `json:"start_at"` Interval int `json:"interval_seconds"` } // PrettyPrint outputs a nicely-formatted human-readable version of the schedule to the given writer. // All the detail levels are the same. func (sched BackupSchedule) PrettyPrint(wr io.Writer, detail prettyprint.DetailLevel) error { scheduleTpl := ` {{ define "schedule_sgl" }}{{ printf "Every %d seconds starting from %s" .Interval .StartDate }}{{ end }} {{ define "schedule_medium" }}{{ template "schedule_sgl" . }}{{ end }} {{ define "schedule_full" }}{{ template "schedule_medium" . }}{{ end }} ` return prettyprint.Run(wr, scheduleTpl, "schedule"+string(detail), sched) }
package brain import ( "github.com/BytemarkHosting/bytemark-client/lib/prettyprint" "io" ) // BackupSchedule represents a schedule to take backups on. It is represented as a start date in YYYY-MM-DD hh:mm:ss format (and assuming UK timezones of some kind.) type BackupSchedule struct { StartDate string Interval int } // PrettyPrint outputs a nicely-formatted human-readable version of the schedule to the given writer. // All the detail levels are the same. func (sched BackupSchedule) PrettyPrint(wr io.Writer, detail prettyprint.DetailLevel) error { scheduleTpl := ` {{ define "schedule_sgl" }}{{ printf "Every %d seconds starting from %s" .Interval .StartDate }}{{ end }} {{ define "schedule_medium" }}{{ template "schedule_sgl" . }}{{ end }} {{ define "schedule_full" }}{{ template "schedule_medium" . }}{{ end }} ` return prettyprint.Run(wr, scheduleTpl, "schedule"+string(detail), sched) }
Add out directory to path to new sqlite lookup
import os from app.lookups import base as lookups from app.drivers.base import BaseDriver class LookupDriver(BaseDriver): def __init__(self, **kwargs): super().__init__(**kwargs) self.lookupfn = kwargs.get('lookup', None) self.initialize_lookup() def initialize_lookup(self): if self.lookupfn is not None: self.lookup = lookups.get_lookup(self.lookupfn, self.lookuptype) else: # FIXME MUST be a set or mzml lookup? here is place to assert # correct lookuptype! self.lookupfn = os.path.join(self.outdir, 'msstitcher_lookup.sqlite') self.lookup = lookups.create_new_lookup(self.lookupfn) self.lookup.add_tables() def run(self): self.create_lookup()
from app.lookups import base as lookups from app.drivers.base import BaseDriver class LookupDriver(BaseDriver): def __init__(self, **kwargs): super().__init__(**kwargs) self.lookupfn = kwargs.get('lookup', None) self.initialize_lookup() def initialize_lookup(self): if self.lookupfn is not None: self.lookup = lookups.get_lookup(self.lookupfn, self.lookuptype) else: # FIXME MUST be a set or mzml lookup? here is place to assert # correct lookuptype! self.lookupfn = 'msstitcher_lookup.sqlite' self.lookup = lookups.create_new_lookup(self.lookupfn) self.lookup.add_tables() def run(self): self.create_lookup()
Read from the tags array when saving
const config = require('collections-online/lib/config'); const cip = require('../services/cip'); const CROWD_TAGS = '{73be3a90-a8ef-4a42-aa8f-d16ca4f55e0a}'; function saveToCip(catalog, id, values) { return cip.setFieldValues(catalog, id, 'web', values) .then(function(response) { if (response.statusCode !== 200) { throw new Error('Failed to set the field values'); } }); } module.exports.save = (metadata) => { // Save it using the CIP var values = {}; values[CROWD_TAGS] = metadata.tags.join(','); return saveToCip(metadata.collection, metadata.id, values).then(function() { return metadata; }); } module.exports.updateIndex = (metadata) => { const es = require('collections-online/lib/services/elasticsearch'); // TODO: Consider that elasticsearch might not be the only way to update the // document index. var indexingState = { es: es, index: config.types.asset.index }; var transformations = [ require('../indexing/transformations/tag-hierarchy') ]; // The CIP specific indexing code requires a catalog instead of collection metadata.catalog = metadata.collection; const indexAsset = require('../indexing/processing/asset'); return indexAsset(indexingState, metadata, transformations); }
const config = require('collections-online/lib/config'); const cip = require('../services/cip'); const CROWD_TAGS = '{73be3a90-a8ef-4a42-aa8f-d16ca4f55e0a}'; function saveToCip(catalog, id, values) { return cip.setFieldValues(catalog, id, 'web', values) .then(function(response) { if (response.statusCode !== 200) { throw new Error('Failed to set the field values'); } }); } module.exports.save = (metadata) => { var values = {}; values[CROWD_TAGS] = metadata.tags_crowd.join(','); return saveToCip(metadata.collection, metadata.id, values).then(function() { return metadata; }); } module.exports.updateIndex = (metadata) => { const es = require('collections-online/lib/services/elasticsearch'); // TODO: Consider that elasticsearch might not be the only way to update the // document index. var indexingState = { es: es, index: config.types.asset.index }; var transformations = [ require('../indexing/transformations/tag-hierarchy') ]; // The CIP specific indexing code requires a catalog instead of collection metadata.catalog = metadata.collection; const indexAsset = require('../indexing/processing/asset'); return indexAsset(indexingState, metadata, transformations); }
Fix Mustache compiler to default null values to empty strings, not throw exception.
/* * Copyright 2015-2015 Groupon, Inc * Copyright 2015-2015 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.billing.plugin.notification.templates; import java.util.Map; import com.samskivert.mustache.Mustache; import com.samskivert.mustache.Template; public class MustacheTemplateEngine implements TemplateEngine { @Override public String executeTemplateText(final String templateText, final Map<String, Object> data) { final Template template = Mustache.compiler().nullValue("").compile(templateText); return template.execute(data); } }
/* * Copyright 2015-2015 Groupon, Inc * Copyright 2015-2015 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.billing.plugin.notification.templates; import java.util.Map; import com.samskivert.mustache.Mustache; import com.samskivert.mustache.Template; public class MustacheTemplateEngine implements TemplateEngine { @Override public String executeTemplateText(final String templateText, final Map<String, Object> data) { final Template template = Mustache.compiler().compile(templateText); return template.execute(data); } }
Use @task decorator in taskset example
from locust import HttpUser, TaskSet, task, between class WebsiteUser(HttpUser): """ Example of the ability of inline nested TaskSet classes """ host = "http://127.0.0.1:8089" wait_time = between(2, 5) @task class TopLevelTaskSet(TaskSet): @task class IndexTaskSet(TaskSet): @task(10) def index(self): self.client.get("/") @task(1) def stop(self): self.interrupt() @task def stats(self): self.client.get("/stats/requests")
from locust import HttpUser, TaskSet, task, between class WebsiteUser(HttpUser): """ Example of the ability of inline nested TaskSet classes """ host = "http://127.0.0.1:8089" wait_time = between(2, 5) class TopLevelTaskSet(TaskSet): @task class IndexTaskSet(TaskSet): @task(10) def index(self): self.client.get("/") @task(1) def stop(self): self.interrupt() @task def stats(self): self.client.get("/stats/requests") tasks = [TopLevelTaskSet]
Add request counter to logging
let PROTO_PATH = __dirname + "/wkrpt401.proto" let grpc = require('grpc'); let proto = grpc.load(PROTO_PATH).wkrpt401; var requestCount = 0 function getBestPersonality(call, callback) { let userData = call.request; let name = userData.name; let level = userData.level; var maxPersonalityName = ""; var maxPersonalityValue = -1; for (var i in userData.personality) { let personalityName = userData.personality[i].name; let personalityValue = userData.personality[i].amount; if (personalityValue > maxPersonalityValue) { maxPersonalityName = personalityName; maxPersonalityValue = personalityValue; } } let response = "The best personality attribute for " + name + " (Lv. " + level + ") is " + maxPersonalityName + " @ " + maxPersonalityValue; requestCount++ console.log("getBestPersonality called with response '" + response + "'" + " (request #" + requestCount + ")"); callback(null, {response: response}); } function main() { var server = new grpc.Server(); server.addProtoService(proto.UserManager.service, {getBestPersonality: getBestPersonality}); server.bind("localhost:50051", grpc.ServerCredentials.createInsecure()); server.start(); console.log("WKRPT401 gRPC server starting."); } main();
let PROTO_PATH = __dirname + "/wkrpt401.proto" let grpc = require('grpc'); let proto = grpc.load(PROTO_PATH).wkrpt401; function getBestPersonality(call, callback) { let userData = call.request; let name = userData.name; let level = userData.level; var maxPersonalityName = ""; var maxPersonalityValue = -1; for (var i in userData.personality) { let personalityName = userData.personality[i].name; let personalityValue = userData.personality[i].amount; if (personalityValue > maxPersonalityValue) { maxPersonalityName = personalityName; maxPersonalityValue = personalityValue; } } let response = "The best personality attribute for " + name + " (Lv. " + level + ") is " + maxPersonalityName + " @ " + maxPersonalityValue; console.log("getBestPersonality called with response '" + response + "'"); callback(null, {response: response}); } function main() { var server = new grpc.Server(); server.addProtoService(proto.UserManager.service, {getBestPersonality: getBestPersonality}); server.bind("localhost:50051", grpc.ServerCredentials.createInsecure()); server.start(); console.log("WKRPT401 gRPC server starting."); } main();
Fix metajson field save issue
/* * Axelor Business Solutions * * Copyright (C) 2018 Axelor (<http://axelor.com>). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * 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/>. */ package com.axelor.studio.db.repo; import com.axelor.meta.db.MetaJsonField; import com.axelor.meta.db.repo.MetaJsonFieldRepository; import com.axelor.studio.db.AppBuilder; public class MetaJsonFieldRepo extends MetaJsonFieldRepository { @Override public MetaJsonField save(MetaJsonField metajsonField) { AppBuilder appBuilder = metajsonField.getAppBuilder(); if (appBuilder != null) { metajsonField.setIncludeIf("__config__.app.isApp('" + appBuilder.getCode() + "')"); } return super.save(metajsonField); } }
/* * Axelor Business Solutions * * Copyright (C) 2018 Axelor (<http://axelor.com>). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * 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/>. */ package com.axelor.studio.db.repo; import com.axelor.meta.db.MetaJsonField; import com.axelor.meta.db.repo.MetaJsonFieldRepository; import com.axelor.studio.db.AppBuilder; public class MetaJsonFieldRepo extends MetaJsonFieldRepository { @Override public MetaJsonField save(MetaJsonField metajsonField) { AppBuilder appBuilder = metajsonField.getAppBuilder(); if (appBuilder != null) { metajsonField.setIncludeIf("__config__.app.isApp('" + appBuilder.getCode() + "')"); } return metajsonField; } }
Update : try/except in destructurate greatly enhances performances on mass read/write
from collections import Sequence # Enums beautiful python implementation # Used like this : # Numbers = enum('ZERO', 'ONE', 'TWO') # >>> Numbers.ZERO # 0 # >>> Numbers.ONE # 1 # Found here: http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python def enum(*sequential, **named): enums = dict(zip(sequential, range(len(sequential))), **named) return type('Enum', (), enums) class Singleton(type): def __init__(cls, name, bases, dict): super(Singleton, cls).__init__(name, bases, dict) cls.instance = None def __call__(cls, *args, **kw): if cls.instance is None: cls.instance = super(Singleton, cls).__call__(*args, **kw) return cls.instance def __del__(cls, *args, **kw): cls.instance is None class DestructurationError(Exception): pass def destructurate(container): try: return container[0], container[1:] except (KeyError, AttributeError): raise DestructurationError("Can't destructurate a non-sequence container")
from collections import Sequence # Enums beautiful python implementation # Used like this : # Numbers = enum('ZERO', 'ONE', 'TWO') # >>> Numbers.ZERO # 0 # >>> Numbers.ONE # 1 # Found here: http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python def enum(*sequential, **named): enums = dict(zip(sequential, range(len(sequential))), **named) return type('Enum', (), enums) class Singleton(type): def __init__(cls, name, bases, dict): super(Singleton, cls).__init__(name, bases, dict) cls.instance = None def __call__(cls, *args, **kw): if cls.instance is None: cls.instance = super(Singleton, cls).__call__(*args, **kw) return cls.instance def __del__(cls, *args, **kw): cls.instance is None def destructurate(container): class DestructurationError(Exception): pass if isinstance(container, Sequence): return container[0], container[1:] else: raise DestructurationError("Can't destructurate a non-sequence container") return container
Fix missing comma by Ximik
/* Vietnamese translation for the jQuery Timepicker Addon */ /* Written by Nguyen Dinh Trung */ (function($) { $.timepicker.regional['vi'] = { timeOnlyTitle: 'Chọn giờ', timeText: 'Thời gian', hourText: 'Giờ', minuteText: 'Phút', secondText: 'Giây', millisecText: 'Phần nghìn giây', timezoneText: 'Múi giờ', currentText: 'Hiện thời', closeText: 'Đóng', timeFormat: 'h:m', amNames: ['SA', 'AM', 'A'], pmNames: ['CH', 'PM', 'P'], ampm: false }; $.timepicker.setDefaults($.timepicker.regional['vi']); })(jQuery);
/* Vietnamese translation for the jQuery Timepicker Addon */ /* Written by Nguyen Dinh Trung */ (function($) { $.timepicker.regional['vi'] = { timeOnlyTitle: 'Chọn giờ', timeText: 'Thời gian', hourText: 'Giờ', minuteText: 'Phút', secondText: 'Giây', millisecText: 'Phần nghìn giây', timezoneText: 'Múi giờ', currentText: 'Hiện thời', closeText: 'Đóng' timeFormat: 'h:m', amNames: ['SA', 'AM', 'A'], pmNames: ['CH', 'PM', 'P'], ampm: false }; $.timepicker.setDefaults($.timepicker.regional['vi']); })(jQuery);
Sort map list: last opened first
// Copyright (c) 2017, CodeBoy. All rights reserved. // // This Source Code Form is subject to the terms of the // license that can be found in the LICENSE file. package model import ( "time" ) // MapInfo is info struct for FileMap. type MapInfo struct { ID int `json:"id"` Title string `json:"title"` Base string `json:"base"` File string `json:"file"` Opened time.Time `json:"opened"` } // MapInfos is a collection of MapInfo pointers. type MapInfos []MapInfo // Implementation of sort.Interface for MapInfos. func (slice MapInfos) Len() int { return len(slice) } func (slice MapInfos) Less(i, j int) bool { return slice[i].Opened.After(slice[j].Opened) } func (slice MapInfos) Swap(i, j int) { slice[i], slice[j] = slice[j], slice[i] }
// Copyright (c) 2017, CodeBoy. All rights reserved. // // This Source Code Form is subject to the terms of the // license that can be found in the LICENSE file. package model import ( "time" ) // MapInfo is info struct for FileMap. type MapInfo struct { ID int `json:"id"` Title string `json:"title"` Base string `json:"base"` File string `json:"file"` Opened time.Time `json:"opened"` } // MapInfos is a collection of MapInfo pointers. type MapInfos []MapInfo // Implementation of sort.Interface for MapInfos. func (slice MapInfos) Len() int { return len(slice) } func (slice MapInfos) Less(i, j int) bool { return slice[i].Opened.Before(slice[j].Opened) } func (slice MapInfos) Swap(i, j int) { slice[i], slice[j] = slice[j], slice[i] }
Correct logic for loading analytics
(function() { if (document.location.hostname !== "josephduffy.co.uk") { // Don't load analytics for noanalytics.josephduffy.co.uk or onion service return; } var _paq = window._paq || []; /* tracker methods like "setCustomDimension" should be called before "trackPageView" */ _paq.push(["disableCookies"]); _paq.push(['trackPageView']); _paq.push(['enableLinkTracking']); (function() { var u="https://analytics.josephduffy.co.uk/"; _paq.push(['setTrackerUrl', u+'matomo.php']); _paq.push(['setSiteId', '1']); var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s); })(); })();
(function() { if (document.location.hostname === "josephduffy.co.uk") { // Don't load analytics for noanalytics.josephduffy.co.uk or onion service return; } var _paq = window._paq || []; /* tracker methods like "setCustomDimension" should be called before "trackPageView" */ _paq.push(["disableCookies"]); _paq.push(['trackPageView']); _paq.push(['enableLinkTracking']); (function() { var u="https://analytics.josephduffy.co.uk/"; _paq.push(['setTrackerUrl', u+'matomo.php']); _paq.push(['setSiteId', '1']); var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s); })(); })();
Add Id to stats service
"use strict"; //Load dependencies var applicationStorage = process.require("core/applicationStorage"); /** * Insert a stat object * @param tier * @param raid * @param stat * @param callback */ module.exports.insertOne = function (tier, raid, stats, callback) { var collection = applicationStorage.mongo.collection("progress_stats"); var obj = {tier: tier, raid: raid, stats: stats} collection.insertOne(obj, function (error) { callback(error); }); }; /** * Return the last stat (max 200) * @param raid * @param callback */ module.exports.getStats = function (tier, raid, limit, callback) { var collection = applicationStorage.mongo.collection("progress_stats"); collection.find({tier: tier, raid: raid}, {stats:1,_id:1}) .sort({_id: 1}) .limit(limit) .toArray(function (error, stats) { console.log(stats); callback(error, stats); }); };
"use strict"; //Load dependencies var applicationStorage = process.require("core/applicationStorage"); /** * Insert a stat object * @param tier * @param raid * @param stat * @param callback */ module.exports.insertOne = function (tier, raid, stats, callback) { var collection = applicationStorage.mongo.collection("progress_stats"); var obj = {tier: tier, raid: raid, stats: stats} collection.insertOne(obj, function (error) { callback(error); }); }; /** * Return the last stat (max 200) * @param raid * @param callback */ module.exports.getStats = function (tier, raid, limit, callback) { var collection = applicationStorage.mongo.collection("progress_stats"); collection.find({tier: tier, raid: raid}, {stats:1}) .sort({_id: 1}) .limit(limit) .toArray(function (error, stats) { console.log(stats); callback(error, stats); }); };
Fix e2e test on headquarter metadata
const { expect } = require('chai') const { metadata } = require('../../../../../src/lib/urls') describe('Metadata', () => { it('endpoint should return headquarter type', () => { cy.request(metadata.headquarterType()).as('headquarterType') cy.get('@headquarterType').then((response) => { expect(response.status).to.equal(200) expect(JSON.stringify(response.body)).to.equal( JSON.stringify([ { id: '3e6debb4-1596-40c5-aa25-f00da0e05af9', name: 'ukhq', disabled_on: null, }, { id: 'eb59eaeb-eeb8-4f54-9506-a5e08773046b', name: 'ehq', disabled_on: null, }, { id: '43281c5e-92a4-4794-867b-b4d5f801e6f3', name: 'ghq', disabled_on: null, }, ]) ) }) }) })
const { expect } = require('chai') const { metadata } = require('../../../../../src/lib/urls') describe('Metadata', () => { it('endpoint should return headquarter type', () => { cy.request(metadata.headquarterType()).as('headquarterType') cy.get('@headquarterType').then((response) => { expect(response.status).to.equal(200) expect(response.body).to.equal( JSON.stringify([ { id: '3e6debb4-1596-40c5-aa25-f00da0e05af9', name: 'ukhq', disabled_on: null, }, { id: 'eb59eaeb-eeb8-4f54-9506-a5e08773046b', name: 'ehq', disabled_on: null, }, { id: '43281c5e-92a4-4794-867b-b4d5f801e6f3', name: 'ghq', disabled_on: null, }, ]) ) }) }) })
Change to enable one store per driver
var express = require("express"); var bodyParser = require("body-parser"); var databox_directory = require("./utils/databox_directory.js"); var timeseriesRouter = require('./timeseries.js'); var keyValueRouter = require('./keyvalue.js'); var actuateRouter = require('./actuate.js'); var app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: true})); var DATABOX_LOCAL_NAME = process.env.DATABOX_LOCAL_NAME; //TODO app.use(Macaroon checker); app.get("/status", function(req, res) { res.send("active"); }); app.use('/api/actuate',actuateRouter(app)); app.use('/:var(api/data|api/ts)?',timeseriesRouter(app)); app.use('/api/key',keyValueRouter(app)); //Websocket connection to live stream data var server = require('http').createServer(app); var WebSocketServer = require('ws').Server app.wss = new WebSocketServer({ server: server }) app.broadcastDataOverWebSocket = require('./broadcastDataOverWebSocket.js')(app) databox_directory.register_datastore(DATABOX_LOCAL_NAME, ':8080/api') .then( (ids)=>{ server.listen(8080); }) .catch((err) => { console.log(err) }); module.exports = app;
var express = require("express"); var bodyParser = require("body-parser"); var databox_directory = require("./utils/databox_directory.js"); var timeseriesRouter = require('./timeseries.js'); var keyValueRouter = require('./keyvalue.js'); var actuateRouter = require('./actuate.js'); var app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: true})); //TODO app.use(Macaroon checker); app.get("/status", function(req, res) { res.send("active"); }); app.use('/api/actuate',actuateRouter(app)); app.use('/:var(api/data|api/ts)?',timeseriesRouter(app)); app.use('/api/key',keyValueRouter(app)); //Websocket connection to live stream data var server = require('http').createServer(app); var WebSocketServer = require('ws').Server app.wss = new WebSocketServer({ server: server }) app.broadcastDataOverWebSocket = require('./broadcastDataOverWebSocket.js')(app) databox_directory.register_datastore('databox-store-blob', ':8080/api') .then( (ids)=>{ server.listen(8080); }) .catch((err) => { console.log(err) }); module.exports = app;
Set XHR properties between open() and send() Fixes IE11 compatibility. Thanks @bkonetzny for pointing it out. Fixes: https://github.com/sindresorhus/public-ip/issues/16
'use strict'; const isIp = require('is-ip'); const defaults = { timeout: 5000 }; const urls = { v4: 'https://ipv4.icanhazip.com/', v6: 'https://ipv6.icanhazip.com/' }; function queryHttps(version, opts) { return new Promise((resolve, reject) => { const doReject = () => reject(new Error('Couldn\'t find your IP')); const xhr = new XMLHttpRequest(); xhr.onload = () => { const ip = xhr.responseText.trim(); if (!ip || !isIp[version](ip)) { doReject(); } resolve(ip); }; xhr.open('GET', urls[version]); xhr.timeout = opts.timeout; xhr.onerror = doReject; xhr.ontimeout = doReject; xhr.send(); }); } module.exports.v4 = opts => { opts = Object.assign({}, defaults, opts); return queryHttps('v4', opts); }; module.exports.v6 = opts => { opts = Object.assign({}, defaults, opts); return queryHttps('v6', opts); };
'use strict'; const isIp = require('is-ip'); const defaults = { timeout: 5000 }; const urls = { v4: 'https://ipv4.icanhazip.com/', v6: 'https://ipv6.icanhazip.com/' }; function queryHttps(version, opts) { return new Promise((resolve, reject) => { const doReject = () => reject(new Error('Couldn\'t find your IP')); const xhr = new XMLHttpRequest(); xhr.timeout = opts.timeout; xhr.onerror = doReject; xhr.ontimeout = doReject; xhr.onload = () => { const ip = xhr.responseText.trim(); if (!ip || !isIp[version](ip)) { doReject(); } resolve(ip); }; xhr.open('GET', urls[version]); xhr.send(); }); } module.exports.v4 = opts => { opts = Object.assign({}, defaults, opts); return queryHttps('v4', opts); }; module.exports.v6 = opts => { opts = Object.assign({}, defaults, opts); return queryHttps('v6', opts); };
Add missing outputs to wordcount_mem topology
from collections import Counter from redis import StrictRedis from streamparse import Bolt class WordCountBolt(Bolt): outputs = ['word', 'count'] def initialize(self, conf, ctx): self.counter = Counter() self.total = 0 def _increment(self, word, inc_by): self.counter[word] += inc_by self.total += inc_by def process(self, tup): word = tup.values[0] self._increment(word, 10 if word == "dog" else 1) if self.total % 1000 == 0: self.logger.info("counted %i words", self.total) self.emit([word, self.counter[word]]) class RedisWordCountBolt(Bolt): outputs = ['word', 'count'] def initialize(self, conf, ctx): self.redis = StrictRedis() self.total = 0 def _increment(self, word, inc_by): self.total += inc_by return self.redis.zincrby("words", word, inc_by) def process(self, tup): word = tup.values[0] count = self._increment(word, 10 if word == "dog" else 1) if self.total % 1000 == 0: self.logger.info("counted %i words", self.total) self.emit([word, count])
from collections import Counter from redis import StrictRedis from streamparse import Bolt class WordCountBolt(Bolt): outputs = ['word', 'count'] def initialize(self, conf, ctx): self.counter = Counter() self.total = 0 def _increment(self, word, inc_by): self.counter[word] += inc_by self.total += inc_by def process(self, tup): word = tup.values[0] self._increment(word, 10 if word == "dog" else 1) if self.total % 1000 == 0: self.logger.info("counted %i words", self.total) self.emit([word, self.counter[word]]) class RedisWordCountBolt(Bolt): def initialize(self, conf, ctx): self.redis = StrictRedis() self.total = 0 def _increment(self, word, inc_by): self.total += inc_by return self.redis.zincrby("words", word, inc_by) def process(self, tup): word = tup.values[0] count = self._increment(word, 10 if word == "dog" else 1) if self.total % 1000 == 0: self.logger.info("counted %i words", self.total) self.emit([word, count])
Allow syntax errors to pass up since users should never see any. This will help with debugging. Right now it just tells you that pywal needs python 3.5 or newer. Merge remote-tracking branch 'origin/syntax-errors' into syntax-errors
"""wal - setup.py""" import setuptools try: import pywal except ImportError: print("error: pywal requires Python 3.5 or greater.") quit(1) try: import pypandoc LONG_DESC = pypandoc.convert("README.md", "rst") except (IOError, ImportError, RuntimeError): LONG_DESC = open('README.md').read() VERSION = pywal.__version__ DOWNLOAD = "https://github.com/dylanaraps/pywal/archive/%s.tar.gz" % VERSION setuptools.setup( name="pywal", version=VERSION, author="Dylan Araps", author_email="dylan.araps@gmail.com", description="Generate and change colorschemes on the fly", long_description=LONG_DESC, license="MIT", url="https://github.com/dylanaraps/pywal", download_url=DOWNLOAD, classifiers=[ "Environment :: X11 Applications", "License :: OSI Approved :: MIT License", "Operating System :: POSIX :: Linux", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", ], packages=["pywal"], entry_points={"console_scripts": ["wal=pywal.__main__:main"]}, python_requires=">=3.5", test_suite="tests", include_package_data=True)
"""wal - setup.py""" import setuptools try: import pywal except (ImportError, SyntaxError): print("error: pywal requires Python 3.5 or greater.") quit(1) try: import pypandoc LONG_DESC = pypandoc.convert("README.md", "rst") except(IOError, ImportError, RuntimeError): LONG_DESC = open('README.md').read() VERSION = pywal.__version__ DOWNLOAD = "https://github.com/dylanaraps/pywal/archive/%s.tar.gz" % VERSION setuptools.setup( name="pywal", version=VERSION, author="Dylan Araps", author_email="dylan.araps@gmail.com", description="Generate and change colorschemes on the fly", long_description=LONG_DESC, license="MIT", url="https://github.com/dylanaraps/pywal", download_url=DOWNLOAD, classifiers=[ "Environment :: X11 Applications", "License :: OSI Approved :: MIT License", "Operating System :: POSIX :: Linux", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", ], packages=["pywal"], entry_points={ "console_scripts": ["wal=pywal.__main__:main"] }, python_requires=">=3.5", test_suite="tests", include_package_data=True )
Add missing _configure to OracleDbContainer Additionally, fix Oracle example.
from testcontainers.core.generic import DbContainer class OracleDbContainer(DbContainer): """ Oracle database container. Example ------- :: with OracleDbContainer() as oracle: e = sqlalchemy.create_engine(oracle.get_connection_url()) result = e.execute("select 1 from dual") """ def __init__(self, image="wnameless/oracle-xe-11g-r2:latest"): super(OracleDbContainer, self).__init__(image=image) self.container_port = 1521 self.with_exposed_ports(self.container_port) self.with_env("ORACLE_ALLOW_REMOTE", "true") def get_connection_url(self): return super()._create_connection_url( dialect="oracle", username="system", password="oracle", port=self.container_port, db_name="xe" ) def _configure(self): pass
from testcontainers.core.generic import DbContainer class OracleDbContainer(DbContainer): """ Oracle database container. Example ------- :: with OracleDbContainer(): e = sqlalchemy.create_engine(oracle.get_connection_url()) result = e.execute("select 1 from dual") """ def __init__(self, image="wnameless/oracle-xe-11g-r2:latest"): super(OracleDbContainer, self).__init__(image=image) self.container_port = 1521 self.with_exposed_ports(self.container_port) self.with_env("ORACLE_ALLOW_REMOTE", "true") def get_connection_url(self): return super()._create_connection_url( dialect="oracle", username="system", password="oracle", port=self.container_port, db_name="xe" )
Add stopLocalVideo if the user does not support getUserMedia
require(["UserMedia", "VideoWrapper"], function(UserMedia, VideoWrapper) { "use strict"; var startButton = document.getElementById("startButton"); startButton.onclick = startLocalVideo; var videoWrapper = new VideoWrapper(document.getElementById('localVideo')); var userMedia = new UserMedia(videoWrapper); function startLocalVideo() { startButton.innerHTML = "Stop"; startButton.onclick = stopLocalVideo; if (userMedia.hasGetUserMedia()) { console.log('Good to go!'); userMedia.queryCamera(); } else { window.alert('getUserMedia() is not compatible in your browser'); stopLocalVideo(); } } function stopLocalVideo() { startButton.innerHTML = "Start"; startButton.onclick = startLocalVideo; userMedia.stopMedia(); } });
require(["UserMedia", "VideoWrapper"], function(UserMedia, VideoWrapper) { "use strict"; var startButton = document.getElementById("startButton"); startButton.onclick = startLocalVideo; var videoWrapper = new VideoWrapper(document.getElementById('localVideo')); var userMedia = new UserMedia(videoWrapper); function startLocalVideo() { startButton.innerHTML = "Stop"; startButton.onclick = stopLocalVideo; if (userMedia.hasGetUserMedia()) { console.log('Good to go!'); userMedia.queryCamera(); } else { window.alert('getUserMedia() is not compatible in your browser'); } } function stopLocalVideo() { startButton.innerHTML = "Start"; startButton.onclick = startLocalVideo; userMedia.stopMedia(); } });
Fix enemy factory since world is now using vector2
package revert.Entities; import java.awt.Point; import com.kgp.util.Vector2; import revert.AI.EnemyAi; import revert.MainScene.World; public class EnemyFactory { Vector2[] spawnPoints; World world; public EnemyFactory(World world, Vector2... spawns) { this.spawnPoints = spawns; this.world = world; } /** * Create a data set array * @param size * @return */ public int[][] createWave(int size) { int[][] wave = new int[size][]; for (int i = 0; i < size; i++) { Vector2 loc = spawnPoints[(int)(Math.random()*spawnPoints.length)]; int[] n = {(int)loc.x, (int)loc.y, (int)(Math.random()*3)}; wave[i] = n; } return wave; } public Enemy generateEnemy(int type) { Enemy e = new Enemy(world, world.getPlayer()); EnemyAi ai = null; if (type == 0) { //ai = new PassiveAi(); } else { System.out.println("No enemy type corresponds to value: " + type + ". Instantiating basic enemy"); } e.setAI(ai); return e; } }
package revert.Entities; import java.awt.Point; import revert.AI.EnemyAi; import revert.MainScene.World; public class EnemyFactory { Point[] spawnPoints; World world; public EnemyFactory(World world, Point... spawns) { this.spawnPoints = spawns; this.world = world; } /** * Create a data set array * @param size * @return */ public int[][] createWave(int size) { int[][] wave = new int[size][]; for (int i = 0; i < size; i++) { Point loc = spawnPoints[(int)(Math.random()*spawnPoints.length)]; int[] n = {loc.x, loc.y, (int)(Math.random()*3)}; wave[i] = n; } return wave; } public Enemy generateEnemy(int type) { Enemy e = new Enemy(world, world.getPlayer()); EnemyAi ai = null; if (type == 0) { //ai = new PassiveAi(); } else { System.out.println("No enemy type corresponds to value: " + type + ". Instantiating basic enemy"); } e.setAI(ai); return e; } }
Test script now against default python version.
#!/usr/bin/env python import os import time from expjobs.helpers import run_class class DummyWorker(object): param = 2 def set_out_path_and_name(self, path, name): self.out_path = path self.out_name = name def run(self): print('Running {}...'.format(self.param)) time.sleep(.01) out_file = os.path.join(self.out_path, self.out_name + '.result') with open(out_file, 'w+') as f: f.write('Done.') @classmethod def load_from_serialized(cls, cfg): worker = cls() with open(cfg, 'r+') as f: cls.param = int(f.read()) return worker run_class(DummyWorker)
#!/usr/bin/env python2 import os import time from expjobs.helpers import run_class class DummyWorker(object): param = 2 def set_out_path_and_name(self, path, name): self.out_path = path self.out_name = name def run(self): print('Running {}...'.format(self.param)) time.sleep(.01) out_file = os.path.join(self.out_path, self.out_name + '.result') with open(out_file, 'w+') as f: f.write('Done.') @classmethod def load_from_serialized(cls, cfg): worker = cls() with open(cfg, 'r+') as f: cls.param = int(f.read()) return worker run_class(DummyWorker)
Store timer as variable instead of state
import React, { Children, Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import LoadingView from '../loading-view/LoadingView'; import { appStateSelector } from '../_selectors/AppStateSelectors'; /** * Note: The loading view is tightly coupled with the auto-signin flow of apps, * If we render children before connected === true, auto sign-in will fail */ @connect(appStateSelector) export default class AppStateProvider extends Component { componentWillMount() { this.timer = window.setTimeout(this.showMessageForSlowConnection.bind(this), 4000); } componentWillUnmount() { window.clearTimeout(this.timer); } showMessageForSlowConnection() { this.setState({ showMessage: true }); } static propTypes = { children: PropTypes.object.isRequired, connected: PropTypes.bool.isRequired, }; render() { const { connected, children } = this.props; const loadingText = 'Taking too long to load, check connection.'; const showMessage = this.state && this.state.showMessage; const loadingView = <LoadingView showMessage={showMessage} text={loadingText} />; return Children.only(connected ? children : loadingView); } }
import React, { Children, Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import LoadingView from '../loading-view/LoadingView'; import { appStateSelector } from '../_selectors/AppStateSelectors'; /** * Note: The loading view is tightly coupled with the auto-signin flow of apps, * If we render children before connected === true, auto sign-in will fail */ @connect(appStateSelector) export default class AppStateProvider extends Component { componentWillMount() { this.setState({ timer: window.setTimeout(this.showMessageForSlowConnection.bind(this), 4000) }); } componentWillUnmount() { window.clearTimeout(this.state.timer); } showMessageForSlowConnection() { this.setState({ showMessage: true }); } static propTypes = { children: PropTypes.object.isRequired, connected: PropTypes.bool.isRequired, }; render() { const { connected, children } = this.props; const loadingText = 'Taking too long to load, check connection.'; const showMessage = this.state && this.state.showMessage; const loadingView = <LoadingView showMessage={showMessage} text={loadingText} />; return Children.only(connected ? children : loadingView); } }
Fix bug where shipping wasn't included in payment amount with cartridge handler
from cartridge.shop.checkout import CheckoutError from commweb.exc import PaymentDeclinedError from commweb.purchase import Purchase def cartridge_payment_handler(request, order_form, order): trans_id = 'WFS_%d' % order.id p = Purchase(order.total, trans_id, order_form.cleaned_data['card_number'], order_form.cleaned_data['card_expiry_year'][2:4], order_form.cleaned_data['card_expiry_month'], order_form.cleaned_data['card_ccv']) try: p.process() return trans_id except PaymentDeclinedError, e: raise CheckoutError('Payment declined: %s' % str(e))
from cartridge.shop.checkout import CheckoutError from cartridge.shop.models import Cart from commweb.exc import PaymentDeclinedError from commweb.purchase import Purchase def cartridge_payment_handler(request, order_form, order): cart = Cart.objects.from_request(request) trans_id = 'WFS_%d' % order.id p = Purchase(cart.total_price(), trans_id, order_form.cleaned_data['card_number'], order_form.cleaned_data['card_expiry_year'][2:4], order_form.cleaned_data['card_expiry_month'], order_form.cleaned_data['card_ccv']) try: p.process() return trans_id except PaymentDeclinedError, e: raise CheckoutError('Payment declined: %s' % str(e))
Test whitespace in pretty printing tests.
from os import walk, sep, chdir, pardir from os.path import split, join, abspath from glob import glob # System path separator (usually slash or backslash) sepd = {"sep": sep} # Files having at least one of these in their path will be excluded EXCLUDE = set([ "%(sep)sthirdparty%(sep)s" % sepd, # "%(sep)sprinting%(sep)spretty%(sep)s" % sepd, ]) def test_no_trailing_whitespace(): message = "File contains trailing whitespace: %s, line %s." base_path = split(__file__)[0] base_path += sep + pardir + sep + pardir # go to sympy/ base_path = abspath(base_path) for root, dirs, files in walk(base_path): for fname in glob(join(root, "*.py")): if filter(lambda ex: ex in fname, EXCLUDE): continue file = open(fname, "r") try: for idx, line in enumerate(file): if line.endswith(" \n"): assert False, message % (fname, idx+1) finally: file.close()
from os import walk, sep, chdir, pardir from os.path import split, join, abspath from glob import glob # System path separator (usually slash or backslash) sepd = {"sep": sep} # Files having at least one of these in their path will be excluded EXCLUDE = set([ "%(sep)sthirdparty%(sep)s" % sepd, "%(sep)sprinting%(sep)spretty%(sep)s" % sepd, ]) def test_no_trailing_whitespace(): message = "File contains trailing whitespace: %s, line %s." base_path = split(__file__)[0] base_path += sep + pardir + sep + pardir # go to sympy/ base_path = abspath(base_path) for root, dirs, files in walk(base_path): for fname in glob(join(root, "*.py")): if filter(lambda ex: ex in fname, EXCLUDE): continue file = open(fname, "r") try: for idx, line in enumerate(file): if line.endswith(" \n"): assert False, message % (fname, idx+1) finally: file.close()
Fix for String MetaProps facet searches
package alien4cloud.metaproperty; import com.google.common.collect.Lists; import org.elasticsearch.index.query.ExistsQueryBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.mapping.IFacetBuilderHelper; import org.elasticsearch.mapping.TermsFilterBuilderHelper; import org.elasticsearch.search.aggregations.AggregationBuilder; import org.elasticsearch.search.aggregations.AggregationBuilders; import org.elasticsearch.search.aggregations.bucket.missing.MissingAggregationBuilder; import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder; import java.util.List; class MetaPropertyAggregationBuilderHelper extends TermsFilterBuilderHelper implements IFacetBuilderHelper { private final int size; MetaPropertyAggregationBuilderHelper(String nestedPath,String esFieldName) { super(false,nestedPath,esFieldName ); this.size = 10; } @Override public List<AggregationBuilder> buildFacets() { TermsAggregationBuilder termsBuilder = AggregationBuilders.terms(getEsFieldName()).field(getEsFieldName()+".keyword").size(size); MissingAggregationBuilder missingBuilder = AggregationBuilders.missing("missing_" + getEsFieldName()).field(getEsFieldName()+".keyword"); return Lists.newArrayList(termsBuilder, missingBuilder); } @Override public QueryBuilder buildFilter(final String key, final String... values) { return super.buildFilter(key + ".keyword",values); } }
package alien4cloud.metaproperty; import com.google.common.collect.Lists; import org.elasticsearch.mapping.IFacetBuilderHelper; import org.elasticsearch.mapping.TermsFilterBuilderHelper; import org.elasticsearch.search.aggregations.AggregationBuilder; import org.elasticsearch.search.aggregations.AggregationBuilders; import org.elasticsearch.search.aggregations.bucket.missing.MissingAggregationBuilder; import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder; import java.util.List; class MetaPropertyAggregationBuilderHelper extends TermsFilterBuilderHelper implements IFacetBuilderHelper { private final int size; MetaPropertyAggregationBuilderHelper(String nestedPath,String esFieldName) { super(false,nestedPath,esFieldName); this.size = 10; } @Override public List<AggregationBuilder> buildFacets() { TermsAggregationBuilder termsBuilder = AggregationBuilders.terms(getEsFieldName()).field(getEsFieldName()+".keyword").size(size); MissingAggregationBuilder missingBuilder = AggregationBuilders.missing("missing_" + getEsFieldName()).field(getEsFieldName()+".keyword"); return Lists.newArrayList(termsBuilder, missingBuilder); } }
Write last shutdown time when we shutdown
import os import time import sys import signal import subprocess from muzicast.const import BASEDIR, WEB_PORT from muzicast.config import GlobalConfig from muzicast.web import app print 'Running', os.getpid(), os.getppid() class Runner(object): def run(self): self.streamer = subprocess.Popen([sys.executable, os.path.join(BASEDIR, 'streamer.py')]) self.scanner = subprocess.Popen([sys.executable, os.path.join(BASEDIR, 'collection/__init__.py')]) print 'Started streamer PID %d'%self.streamer.pid print 'Started scanner PID %d'%self.scanner.pid signal.signal(signal.SIGINT, self.shutdown) signal.signal(signal.SIGTERM, self.shutdown) app.run('0.0.0.0', WEB_PORT, debug=True, use_reloader=False) #app.run('0.0.0.0', WEB_PORT, debug=False, use_reloader=False) def shutdown(self, signum, frame): self.streamer.terminate() self.scanner.terminate() config = GlobalConfig() config['last_shutdown_time'] = int(time.time()) config.save() sys.exit(0) if __name__ == '__main__': r = Runner() r.run()
import os import time import sys import signal import subprocess from muzicast.const import BASEDIR, WEB_PORT from muzicast.web import app print 'Running', os.getpid(), os.getppid() class Runner(object): def run(self): self.streamer = subprocess.Popen([sys.executable, os.path.join(BASEDIR, 'streamer.py')]) self.scanner = subprocess.Popen([sys.executable, os.path.join(BASEDIR, 'collection/__init__.py')]) print 'Started streamer PID %d'%self.streamer.pid print 'Started scanner PID %d'%self.scanner.pid signal.signal(signal.SIGINT, self.shutdown) signal.signal(signal.SIGTERM, self.shutdown) app.run('0.0.0.0', WEB_PORT, debug=True, use_reloader=False) #app.run('0.0.0.0', WEB_PORT, debug=False, use_reloader=False) def shutdown(self, signum, frame): self.streamer.terminate() self.scanner.terminate() sys.exit(0) if __name__ == '__main__': r = Runner() r.run()
Change port number to 8000
'use strict'; /** * Module dependencies. */ var express = require('express'); var routes = require('./routes'); var memos = require('./routes/memos'); var http = require('http'); var path = require('path'); var app = express(); // all environments app.set('port', process.env.PORT || 8000); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(express.favicon()); // app.use(express.logger('dev')); app.use(express.json()); app.use(express.urlencoded()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); // development only if ('development' === app.get('env')) { app.use(express.errorHandler()); } app.get('/', routes.index); app.get('/memos/*', memos.list); app.get('/memos', memos.list); app.get('/files/*', memos.get); var server = http.createServer(app); server.listen(app.get('port'), function () { console.log('Express server listening on port ' + app.get('port')); }); var io = require('socket.io').listen(server, {'log level': 0}); memos.start(io);
'use strict'; /** * Module dependencies. */ var express = require('express'); var routes = require('./routes'); var memos = require('./routes/memos'); var http = require('http'); var path = require('path'); var app = express(); // all environments app.set('port', process.env.PORT || 3000); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(express.favicon()); // app.use(express.logger('dev')); app.use(express.json()); app.use(express.urlencoded()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); // development only if ('development' === app.get('env')) { app.use(express.errorHandler()); } app.get('/', routes.index); app.get('/memos/*', memos.list); app.get('/memos', memos.list); app.get('/files/*', memos.get); var server = http.createServer(app); server.listen(app.get('port'), function () { console.log('Express server listening on port ' + app.get('port')); }); var io = require('socket.io').listen(server, {'log level': 0}); memos.start(io);
Add rasterization microbenchmark for silk Add rasterize_and_record_micro_key_silk_cases for keeping track of rasterization and recording performance of silk content. This mirrors the existing rasterize_and_record_key_silk_cases benchmark and will potentially allow us to remove it if this microbenchmark produces less noisy data. BUG=339517 Review URL: https://codereview.chromium.org/177253003 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@253403 0039d316-1c4b-4281-b951-d872f2087c98
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from measurements import rasterize_and_record_micro from telemetry import test @test.Disabled('android', 'linux') class RasterizeAndRecordMicroTop25(test.Test): """Measures rasterize and record performance on the top 25 web pages. http://www.chromium.org/developers/design-documents/rendering-benchmarks""" test = rasterize_and_record_micro.RasterizeAndRecordMicro page_set = 'page_sets/top_25.json' class RasterizeAndRecordMicroKeyMobileSites(test.Test): """Measures rasterize and record performance on the key mobile sites. http://www.chromium.org/developers/design-documents/rendering-benchmarks""" test = rasterize_and_record_micro.RasterizeAndRecordMicro page_set = 'page_sets/key_mobile_sites.json' class RasterizeAndRecordMicroKeySilkCases(test.Test): """Measures rasterize and record performance on the silk sites. http://www.chromium.org/developers/design-documents/rendering-benchmarks""" test = rasterize_and_record_micro.RasterizeAndRecordMicro page_set = 'page_sets/key_silk_cases.json'
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from measurements import rasterize_and_record_micro from telemetry import test @test.Disabled('android', 'linux') class RasterizeAndRecordMicroTop25(test.Test): """Measures rasterize and record performance on the top 25 web pages. http://www.chromium.org/developers/design-documents/rendering-benchmarks""" test = rasterize_and_record_micro.RasterizeAndRecordMicro page_set = 'page_sets/top_25.json' class RasterizeAndRecordMicroKeyMobileSites(test.Test): """Measures rasterize and record performance on the key mobile sites. http://www.chromium.org/developers/design-documents/rendering-benchmarks""" test = rasterize_and_record_micro.RasterizeAndRecordMicro page_set = 'page_sets/key_mobile_sites.json'
Tweak nccmp to be more spack-compatible. - Spack doesn't set F90, but it confuses the nccmp build. Just remove it from the environment. - TODO: should build environment unset this variable?
from spack import * class Nccmp(Package): """Compare NetCDF Files""" homepage = "http://nccmp.sourceforge.net/" url = "http://downloads.sourceforge.net/project/nccmp/nccmp-1.8.2.0.tar.gz" version('1.8.2.0', '81e6286d4413825aec4327e61a28a580') depends_on('netcdf') def install(self, spec, prefix): # Configure says: F90 and F90FLAGS are replaced by FC and # FCFLAGS respectively in this configure, please unset # F90/F90FLAGS and set FC/FCFLAGS instead and rerun configure # again. env.pop('F90', None) env.pop('F90FLAGS', None) configure('--prefix=%s' % prefix) make() make("check") make("install")
from spack import * import os class Nccmp(Package): """Compare NetCDF Files""" homepage = "http://nccmp.sourceforge.net/" url = "http://downloads.sourceforge.net/project/nccmp/nccmp-1.8.2.0.tar.gz" version('1.8.2.0', '81e6286d4413825aec4327e61a28a580') depends_on('netcdf') def install(self, spec, prefix): # Configure says: F90 and F90FLAGS are replaced by FC and # FCFLAGS respectively in this configure, please unset # F90/F90FLAGS and set FC/FCFLAGS instead and rerun configure # again. os.environ['FC'] = os.environ['F90'] del os.environ['F90'] try: os.environ['FCFLAGS'] = os.environ['F90FLAGS'] del os.environ['F90FLAGS'] except KeyError: # There are no flags pass configure('--prefix=%s' % prefix) make() make("check") make("install")
Add method to get all data
<?php namespace Avh\DataHandler; class DataHandler { protected $registry; /** * Class constructor * * @param AttributeBagInterface $registry */ public function __construct(AttributeBagInterface $registry) { $this->registry = $registry; } /** * Clear the registry */ public function clear() { $this->registry->clear(); } /** * Get data from the registry */ public function get($key, $default = null) { return $this->registry->get($key, $default); } public function has($key) { return $this->registry->has($key); } /** * Save data to the registry */ public function set($key, $value) { $this->registry->set($key, $value); return $this; } /** * Gett all data * * @return array */ public function all() { return $this->registry->all(); } }
<?php namespace Avh\DataHandler; class DataHandler { protected $registry; /** * Class constructor * * @param AttributeBagInterface $registry */ public function __construct(AttributeBagInterface $registry) { $this->registry = $registry; } /** * Clear the registry */ public function clear() { $this->registry->clear(); } /** * Get data from the registry */ public function get($key, $default = null) { return $this->registry->get($key, $default); } public function has($key) { return $this->registry->has($key); } /** * Save data to the registry */ public function set($key, $value) { $this->registry->set($key, $value); return $this; } }
Update wording on path of the image.
from django.db import models from django_extensions.db.fields import ( AutoSlugField, CreationDateTimeField, ModificationDateTimeField) from us_ignite.advertising import managers class Advert(models.Model): PUBLISHED = 1 DRAFT = 2 REMOVED = 3 STATUS_CHOICES = ( (PUBLISHED, 'Published'), (DRAFT, 'Draft'), (REMOVED, 'Removed'), ) name = models.CharField(max_length=255) slug = AutoSlugField(populate_from='name') status = models.IntegerField(choices=STATUS_CHOICES, default=DRAFT) url = models.URLField(max_length=500) image = models.ImageField(upload_to="featured") is_featured = models.BooleanField( default=False, help_text='Marking this Advert as featured will publish' ' it and show it on the site.') created = CreationDateTimeField() modified = ModificationDateTimeField() # managers: objects = models.Manager() published = managers.AdvertPublishedManager() class Meta: ordering = ('-is_featured', '-created') def __unicode__(self): return self.name
from django.db import models from django_extensions.db.fields import ( AutoSlugField, CreationDateTimeField, ModificationDateTimeField) from us_ignite.advertising import managers class Advert(models.Model): PUBLISHED = 1 DRAFT = 2 REMOVED = 3 STATUS_CHOICES = ( (PUBLISHED, 'Published'), (DRAFT, 'Draft'), (REMOVED, 'Removed'), ) name = models.CharField(max_length=255) slug = AutoSlugField(populate_from='name') status = models.IntegerField(choices=STATUS_CHOICES, default=DRAFT) url = models.URLField(max_length=500) image = models.ImageField(upload_to="ads") is_featured = models.BooleanField( default=False, help_text='Marking this Advert as featured will publish' ' it and show it on the site.') created = CreationDateTimeField() modified = ModificationDateTimeField() # managers: objects = models.Manager() published = managers.AdvertPublishedManager() class Meta: ordering = ('-is_featured', '-created') def __unicode__(self): return self.name