text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix pep8 to pass super checks
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2012 Daniel Reis # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'Project Issue with Department', 'version': '1.1', "category": "Project Management", 'description': """\ Add Department field to Project Issues. Selecting a Project for an issue will automatically populate this with the Project's defined Department. """, 'author': 'Daniel Reis', 'website': 'daniel.reis@securitas.pt', 'depends': [ 'project_issue', 'project_department', ], 'update_xml': [ 'project_issue_view.xml', 'security/ir.model.access.csv', ], 'installable': True, 'application': False, 'auto_install': True, }
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2012 Daniel Reis # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'Project Issue with Department', 'version': '1.1', "category": "Project Management", 'description': """\ Add Department field to Project Issues. Selecting a Project for an issue will automatically populate this with the Project's defined Department. """, 'author': 'Daniel Reis', 'website': 'daniel.reis@securitas.pt', 'depends': [ 'project_issue', 'project_department', ], 'update_xml': [ 'project_issue_view.xml', 'security/ir.model.access.csv', ], 'installable': True, 'application': False, 'auto_install': True, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
Insert the current directory to the front of sys.path -- and remove it at the end. This fixes a problem where python Lib/test/test_import.py failed while "make test" succeeded.
from test_support import TESTFN import os import random import sys sys.path.insert(0, os.curdir) source = TESTFN + ".py" pyc = TESTFN + ".pyc" pyo = TESTFN + ".pyo" f = open(source, "w") print >> f, "# This will test Python's ability to import a .py file" a = random.randrange(1000) b = random.randrange(1000) print >> f, "a =", a print >> f, "b =", b f.close() try: try: mod = __import__(TESTFN) except ImportError, err: raise ValueError, "import from .py failed: %s" % err if mod.a != a or mod.b != b: print a, "!=", mod.a print b, "!=", mod.b raise ValueError, "module loaded (%s) but contents invalid" % mod finally: os.unlink(source) try: try: reload(mod) except ImportError, err: raise ValueError, "import from .pyc/.pyo failed: %s" % err finally: try: os.unlink(pyc) except os.error: pass try: os.unlink(pyo) except os.error: pass del sys.path[0]
from test_support import TESTFN import os import random source = TESTFN + ".py" pyc = TESTFN + ".pyc" pyo = TESTFN + ".pyo" f = open(source, "w") print >> f, "# This will test Python's ability to import a .py file" a = random.randrange(1000) b = random.randrange(1000) print >> f, "a =", a print >> f, "b =", b f.close() try: try: mod = __import__(TESTFN) except ImportError, err: raise ValueError, "import from .py failed: %s" % err if mod.a != a or mod.b != b: print a, "!=", mod.a print b, "!=", mod.b raise ValueError, "module loaded (%s) but contents invalid" % mod finally: os.unlink(source) try: try: reload(mod) except ImportError, err: raise ValueError, "import from .pyc/.pyo failed: %s" % err finally: try: os.unlink(pyc) except os.error: pass try: os.unlink(pyo) except os.error: pass
Convert Unix path to Windows path in jshint command (in node_modules) Story #103
'use strict'; var exec = require('child_process').exec; var path = require('path'); function fail() { process.stdout.write( 'Style check failed (see the above output).\n' + 'If you still wish to commit your code, run git commit -n to skip this check.\n' ); process.exit(1); } exec('git diff --staged --name-status', function (error, stdout, stderr) { if (error) { process.stdout.write(stderr + '\nCould not get list of modified files: ' + error); fail(); } var expression = /^[MA]\s+([\w-\\\/]+\.js)$/gm; var files = []; var match; while (match = expression.exec(stdout)) { files.push(match[1]); } if (files.length === 0) { process.exit(0); } var command = path.resolve('./node_modules/.bin/jshint'); var child = exec(command + ' --reporter=tools/jshint-reporter.js ' + files.join(' ')); child.stdout.on('data', function (data) { process.stdout.write(data); }); child.stderr.on('data', function (data) { process.stderr.write(data); }); child.on('exit', function (code) { if (code !== 0) { fail(); } else { process.exit(0); } }); });
'use strict'; var exec = require('child_process').exec; function fail() { process.stdout.write( 'Style check failed (see the above output).\n' + 'If you still wish to commit your code, run git commit -n to skip this check.\n' ); process.exit(1); } exec('git diff --staged --name-status', function (error, stdout, stderr) { if (error) { process.stdout.write(stderr + '\nCould not get list of modified files: ' + error); fail(); } var expression = /^[MA]\s+([\w-\\\/]+\.js)$/gm; var files = []; var match; while (match = expression.exec(stdout)) { files.push(match[1]); } if (files.length === 0) { process.exit(0); } var child = exec('node_modules/.bin/jshint --reporter=tools/jshint-reporter.js ' + files.join(' ')); child.stdout.on('data', function (data) { process.stdout.write(data); }); child.stderr.on('data', function (data) { process.stderr.write(data); }); child.on('exit', function (code) { if (code !== 0) { fail(); } else { process.exit(0); } }); });
Use get_or_create to avoid duplicate objects
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations import uuid from cla_common.constants import RESEARCH_CONTACT_VIA def create_default_contact_for_research_methods(apps, schema_editor): ContactResearchMethods = apps.get_model("legalaid", "ContactResearchMethod") for value, name in RESEARCH_CONTACT_VIA: ContactResearchMethods.objects.get_or_create(method=value, defaults={"reference": uuid.uuid4()}) def rollback_default_contact_for_research_methods(apps, schema_editor): pass class Migration(migrations.Migration): dependencies = [("legalaid", "0021_auto_20190515_1042")] operations = [ migrations.RunPython( create_default_contact_for_research_methods, rollback_default_contact_for_research_methods ) ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations import uuid from cla_common.constants import RESEARCH_CONTACT_VIA def create_default_contact_for_research_methods(apps, schema_editor): ContactResearchMethods = apps.get_model("legalaid", "ContactResearchMethod") for value, name in RESEARCH_CONTACT_VIA: ContactResearchMethods.objects.create(method=value, reference=uuid.uuid4()).save() def rollback_default_contact_for_research_methods(apps, schema_editor): pass class Migration(migrations.Migration): dependencies = [("legalaid", "0021_auto_20190515_1042")] operations = [ migrations.RunPython( create_default_contact_for_research_methods, rollback_default_contact_for_research_methods ) ]
Fix for new version of slack change span.message_content to div.messagee_content
$(function() { // https://github.com/naugtur/insertionQuery var anime_watch = function(selector, callback) { var guid = selector.replace(/[^a-zA-Z0-9]+/g, "_") +"_"+ ((new Date()).getTime()); $("<style/>").html([ "@-webkit-keyframes {guid} { from { clip: rect(auto, auto, auto, auto); } to { clip: rect(auto, auto, auto, auto); } }", "@keyframes {guid} { from { clip: rect(auto, auto, auto, auto); } to { clip: rect(auto, auto, auto, auto); } }", "{selector} { animation-duration: 0.001s; animation-name: {guid}; -webkit-animation-duration: 0.001s; -webkit-animation-name: {guid}; }" ].join("\n").replace(/\{guid\}/g, guid).replace(/\{selector\}/g, selector)).appendTo("head"); var eventHandler = function(event) { if (event.animationName === guid || event.WebkitAnimationName === guid) { callback.call(event.target, event.target); } } document.addEventListener("animationstart", eventHandler, false); document.addEventListener("webkitAnimationStart", eventHandler, false); }; // Watches the animation event and parses li if they are inserted anime_watch("div.message_content", function(div) { $(div).parseIssueTrackerNumbers(); }); });
$(function() { // https://github.com/naugtur/insertionQuery var anime_watch = function(selector, callback) { var guid = selector.replace(/[^a-zA-Z0-9]+/g, "_") +"_"+ ((new Date()).getTime()); $("<style/>").html([ "@-webkit-keyframes {guid} { from { clip: rect(auto, auto, auto, auto); } to { clip: rect(auto, auto, auto, auto); } }", "@keyframes {guid} { from { clip: rect(auto, auto, auto, auto); } to { clip: rect(auto, auto, auto, auto); } }", "{selector} { animation-duration: 0.001s; animation-name: {guid}; -webkit-animation-duration: 0.001s; -webkit-animation-name: {guid}; }" ].join("\n").replace(/\{guid\}/g, guid).replace(/\{selector\}/g, selector)).appendTo("head"); var eventHandler = function(event) { if (event.animationName === guid || event.WebkitAnimationName === guid) { callback.call(event.target, event.target); } } document.addEventListener("animationstart", eventHandler, false); document.addEventListener("webkitAnimationStart", eventHandler, false); }; // Watches the animation event and parses li if they are inserted anime_watch("span.message_content", function(span) { $(span).parseIssueTrackerNumbers(); }); });
Add an example for a nonstrict named parameter method
/** * Copyright 2010-2014 Ralph Schaer <ralphschaer@gmail.com> * * 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 ch.rasc.extdirectspring.demo.named; import java.util.List; import java.util.Map; import org.springframework.stereotype.Service; import ch.ralscha.extdirectspring.annotation.ExtDirectMethod; import ch.ralscha.extdirectspring.annotation.ExtDirectMethodType; @Service public class NamedService { @ExtDirectMethod(value = ExtDirectMethodType.SIMPLE_NAMED, group = "named") public String showDetails(List<Business> bo, String firstName, String lastName, int age) { bo.forEach(System.out::println); return String.format("Hi %s %s, you are %d years old.", firstName, lastName, age); } @ExtDirectMethod(value = ExtDirectMethodType.SIMPLE_NAMED, group = "named") public boolean nonStrict(Map<String,Object> parameters) { parameters.forEach((k,v)->System.out.println(k+"-->"+v)); return true; } }
/** * Copyright 2010-2014 Ralph Schaer <ralphschaer@gmail.com> * * 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 ch.rasc.extdirectspring.demo.named; import java.util.List; import org.springframework.stereotype.Service; import ch.ralscha.extdirectspring.annotation.ExtDirectMethod; import ch.ralscha.extdirectspring.annotation.ExtDirectMethodType; @Service public class NamedService { @ExtDirectMethod(value = ExtDirectMethodType.SIMPLE_NAMED, group = "named") public String showDetails(List<Business> bo, String firstName, String lastName, int age) { bo.forEach(System.out::println); return String.format("Hi %s %s, you are %d years old.", firstName, lastName, age); } }
Fix _time_to_micros bug. It was calling time.time() when it should use its own argument.
""" Utility functions """ import random import time from . import constants def _service_url_from_hostport(secure, host, port): """ Create an appropriate service URL given the parameters. `secure` should be a bool. """ if secure: protocol = 'https://' else: protocol = 'http://' return ''.join([protocol, host, ':', str(port), '/_rpc/v1/reports/binary']) def _generate_guid(): """ Construct a guid - random 64 bit integer converted to a string. """ return str(random.getrandbits(64)) def _now_micros(): """ Get the current time in microseconds since the epoch. """ return _time_to_micros(time.time()) def _time_to_micros(t): """ Convert a time.time()-style timestamp to microseconds. """ return long(round(t * constants.SECONDS_TO_MICRO)) def _merge_dicts(*dict_args): """Destructively merges dictionaries, returns None instead of an empty dictionary. Elements of dict_args can be None. Keys in latter dicts override those in earlier ones. """ result = {} for dictionary in dict_args: if dictionary: result.update(dictionary) return result if result else None
""" Utility functions """ import random import time from . import constants def _service_url_from_hostport(secure, host, port): """ Create an appropriate service URL given the parameters. `secure` should be a bool. """ if secure: protocol = 'https://' else: protocol = 'http://' return ''.join([protocol, host, ':', str(port), '/_rpc/v1/reports/binary']) def _generate_guid(): """ Construct a guid - random 64 bit integer converted to a string. """ return str(random.getrandbits(64)) def _now_micros(): """ Get the current time in microseconds since the epoch. """ return _time_to_micros(time.time()) def _time_to_micros(t): """ Convert a time.time()-style timestamp to microseconds. """ return long(round(time.time() * constants.SECONDS_TO_MICRO)) def _merge_dicts(*dict_args): """Destructively merges dictionaries, returns None instead of an empty dictionary. Elements of dict_args can be None. Keys in latter dicts override those in earlier ones. """ result = {} for dictionary in dict_args: if dictionary: result.update(dictionary) return result if result else None
Make naming the destination file work
''' Minion side functions for salt-ftp ''' import os def recv(files, dest): ''' Used with salt-ftp, pass the files dict, and the destination ''' if not os.path.isdir(dest) or not os.path.isdir(os.path.dirname(dest)): return 'Destination not available' ret = {} for path, data in files.items(): final = '' if os.path.basename(path) == os.path.basename(dest)\ and not os.path.isdir(dest): final = dest elif os.path.isdir(dest): final = os.path.join(dest, os.path.basename(path)) elif os.path.isdir(os.path.dirname(dest)): final = dest else: return 'Destination not available' try: open(final, 'w+').write(data) ret[final] = True except IOError: ret[final] = False return ret
''' Minion side functions for salt-ftp ''' import os def recv(files, dest): ''' Used with salt-ftp, pass the files dict, and the destination ''' if not os.path.isdir(dest) or not os.path.isdir(os.path.dirname(dest)): return 'Destination not available' ret = {} for path, data in files.items(): final = '' if os.path.basename(path) == os.path.basename(dest)\ and not os.path.isdir(dest): final = dest elif os.path.isdir(dest): final = os.path.join(dest, os.path.basename(path)) else: return 'Destination not available' try: open(final, 'w+').write(data) ret[final] = True except IOError: ret[final] = False return ret
Fix args to list. Args is a tuple, list takes a tuple
#!/usr/bin/env python from genes.posix.traits import only_posix from genes.process.commands import run @only_posix() def chgrp(path, group): run(['chgrp', group, path]) @only_posix() def chown(path, user): run(['chown', user, path]) @only_posix() def groupadd(*args): run(['groupadd'] + list(args)) @only_posix() def ln(*args): run(['ln'] + list(args)) @only_posix() def mkdir(path, mode=None): if mode: run(['mkdir', '-m', mode, path]) else: run(['mkdir', path]) @only_posix() def useradd(*args): # FIXME: this is a bad way to do things # FIXME: sigh. this is going to be a pain to make it idempotent run(['useradd'] + list(args)) @only_posix() def usermod(*args): # FIXME: this is a bad way to do things run(['usermod'] + list(args))
#!/usr/bin/env python from genes.posix.traits import only_posix from genes.process.commands import run @only_posix() def chgrp(path, group): run(['chgrp', group, path]) @only_posix() def chown(path, user): run(['chown', user, path]) @only_posix() def groupadd(*args): run(['groupadd'] + list(*args)) @only_posix() def ln(*args): run(['ln'] + list(*args)) @only_posix() def mkdir(path, mode=None): if mode: run(['mkdir', '-m', mode, path]) else: run(['mkdir', path]) @only_posix() def useradd(*args): # FIXME: this is a bad way to do things # FIXME: sigh. this is going to be a pain to make it idempotent run(['useradd'] + list(*args)) @only_posix() def usermod(*args): # FIXME: this is a bad way to do things run(['usermod'] + list(*args))
Add discord entry to config file
<?php return [ /* |-------------------------------------------------------------------------- | Third Party Services |-------------------------------------------------------------------------- | | This file is for storing the credentials for third party services such | as Stripe, Mailgun, SparkPost and others. This file provides a sane | default location for this type of information, allowing packages | to have a conventional place to find your various credentials. | */ 'mailgun' => [ 'domain' => env('MAILGUN_DOMAIN'), 'secret' => env('MAILGUN_SECRET'), ], 'ses' => [ 'key' => env('SES_KEY'), 'secret' => env('SES_SECRET'), 'region' => 'us-east-1', ], 'sparkpost' => [ 'secret' => env('SPARKPOST_SECRET'), ], 'stripe' => [ 'model' => App\User::class, 'key' => env('STRIPE_KEY'), 'secret' => env('STRIPE_SECRET'), ], 'discord' => [ 'client_id' => env('DISCORD_KEY'), 'client_secret' => env('DISCORD_SECRET'), 'redirect' => env('DISCORD_REDIRECT_URI') ], ];
<?php return [ /* |-------------------------------------------------------------------------- | Third Party Services |-------------------------------------------------------------------------- | | This file is for storing the credentials for third party services such | as Stripe, Mailgun, SparkPost and others. This file provides a sane | default location for this type of information, allowing packages | to have a conventional place to find your various credentials. | */ 'mailgun' => [ 'domain' => env('MAILGUN_DOMAIN'), 'secret' => env('MAILGUN_SECRET'), ], 'ses' => [ 'key' => env('SES_KEY'), 'secret' => env('SES_SECRET'), 'region' => 'us-east-1', ], 'sparkpost' => [ 'secret' => env('SPARKPOST_SECRET'), ], 'stripe' => [ 'model' => App\User::class, 'key' => env('STRIPE_KEY'), 'secret' => env('STRIPE_SECRET'), ], ];
Fix bug in football module caching
angular.module('notificationApp.footballController', []). controller('footballController', function($scope, $interval, $timeout, footballFactory) { $scope.currentTeam = footballFactory.getCurrentTeam(); $scope.rowClick = function(inputTeam) { $scope.currentTeam = inputTeam; footballFactory.setCurrentTeam(inputTeam); $scope.updateFixtures(); }; $scope.getCSSClass = function(inputTeam){ return footballFactory.getCSSClass(inputTeam); } $scope.updateLeagueTable = function() { footballFactory.getLeagueTable().then(function(response) { $scope.leagueTableData = response.data; }); }; $scope.updateFixtures = function() { if (!$scope.currentTeam) return; footballFactory.getFixtures($scope.currentTeam).then(function(response) { $scope.fixtureStatus = footballFactory.getNextFixtureString(response); }); }; $scope.updateFixtures(); $scope.updateLeagueTable(); $interval(function() { footballFactory.clearCache(); $scope.updateFixtures(); $scope.updateLeagueTable(); }, 43200000); });
angular.module('notificationApp.footballController', []). controller('footballController', function($scope, $interval, $timeout, footballFactory) { $scope.currentTeam = footballFactory.getCurrentTeam(); $scope.rowClick = function(inputTeam) { $scope.currentTeam = inputTeam; footballFactory.setCurrentTeam(inputTeam); $scope.updateFixtures(); }; $scope.getCSSClass = function(inputTeam){ return footballFactory.getCSSClass(inputTeam); } $scope.updateLeagueTable = function() { footballFactory.getLeagueTable().then(function(response) { $scope.leagueTableData = response.data; }); }; $scope.updateFixtures = function() { if (!$scope.currentTeam) return; footballFactory.getFixtures($scope.currentTeam).then(function(response) { $scope.fixtureStatus = footballFactory.getNextFixtureString(response); }); }; $scope.updateFixtures(); $scope.updateLeagueTable(); $interval(function() { footballFactory.clearCache($scope.currentTeam); $scope.updateFixtures(); $scope.updateLeagueTable(); }, 43200000); });
Update Siddhi quick start guide link
/** * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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. */ define(function () { "use strict"; // JS strict mode /** * Constants used by the tool - editor */ var constants = { INITIAL_SOURCE_INSTRUCTIONS: "@App:name(\"SiddhiApp\")\n@App:description(\"Description of the plan\")\n\n" + "-- Please refer to https://siddhi.io/en/v5.0/docs/quick-start/ " + "on getting started with Siddhi editor. \n\n" }; return constants; });
/** * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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. */ define(function () { "use strict"; // JS strict mode /** * Constants used by the tool - editor */ var constants = { INITIAL_SOURCE_INSTRUCTIONS: "@App:name(\"SiddhiApp\")\n@App:description(\"Description of the plan\")\n\n" + "-- Please refer to https://docs.wso2.com/display/SP400/Quick+Start+Guide " + "on getting started with SP editor. \n\n" }; return constants; });
Decompress downloaded files from disk, not in memory
#!/usr/bin/env python3 import ftplib import gzip import os import sys host = 'ftp.ncdc.noaa.gov' base = '/pub/data/noaa' retries = 3 ftp = ftplib.FTP(host) ftp.login() for line in sys.stdin: (year, filename) = line.strip().split() for i in range(retries): sys.stderr.write('reporter:status:Processing file %s/%s (FTP attempt %d of %d)\n' % (year, filename, i + 1, retries)) try: ftp.retrbinary('RETR %s/%s/%s' % (base, year, filename), open(filename, 'wb').write) except ftplib.all_errors as error: sys.stderr.write('%s\n' % error) continue count = 0 for record in gzip.open(filename, 'rb'): print('%s\t%s' % (year, record.decode('ISO-8859-1').strip())) count += 1 sys.stderr.write('reporter:counter:NCDC Download,%s,%d\n' % (year, count)) os.remove(filename) break else: ftp.quit() sys.exit(1) ftp.quit()
#!/usr/bin/env python3 import ftplib import gzip import sys host = 'ftp.ncdc.noaa.gov' base = '/pub/data/noaa' retries = 3 ftp = ftplib.FTP(host) ftp.login() for line in sys.stdin: (year, filename) = line.strip().split() for i in range(retries): sys.stderr.write('reporter:status:Processing file %s/%s (FTP attempt %d of %d)\n' % (year, filename, i + 1, retries)) data = bytearray() try: ftp.retrbinary('RETR %s/%s/%s' % (base, year, filename), data.extend) except ftplib.all_errors as error: sys.stderr.write('%s\n' % error) continue records = gzip.decompress(data).decode('ISO-8859-1').split('\n')[0:-1] for record in records: print('%s\t%s' % (year, record)) sys.stderr.write('reporter:counter:NCDC Download,%s,%d\n' % (year, len(records))) break else: ftp.quit() sys.exit(1) ftp.quit()
Improve internal flow of code / increase efficiency
var fs = require('fs'); var mime = require('mime'); module.exports = function(app, routes) { // loop through routes for (var index in routes) { // closure: route is the HTTP request route, path is the file path (function (route, path) { app.get(route, function(req, res) { // create a readable stream var stream = fs.createReadStream(path, {encoding: 'utf8'}); stream .once('error', function() { res.status(500).end('Server error.'); console.error('ERROR (staticize): Could not open readable stream to ' + path); }) .once('readable', function() { // create headers var headers = { 'Content-Type': mime.lookup(path) }; // write head then pipe response res.writeHead(200, headers); stream.pipe(res); }); }); })(index, routes[index]); } };
var fs = require('fs'); var mime = require('mime'); module.exports = function(app, routes) { // loop through routes for (var index in routes) { // route: index, file location: routes[index] (function (indexRoute) { app.get(indexRoute, function(req, res) { fs.readFile(routes[indexRoute], function(err, data) { if (err) { console.log('ERROR: Could not read file (' + err + ').'); res.status(500); return; } // get the mime type var mimeType = mime.lookup(routes[indexRoute]); res.status(200).set('Content-Type', mimeType).send(data); }); }); })(index); } };
Fix syntax error in PHP 5
<?php namespace Bugsnag\BugsnagLaravel\Tests; use Bugsnag\BugsnagLaravel\BugsnagServiceProvider; use GrahamCampbell\TestBench\AbstractPackageTestCase; abstract class AbstractTestCase extends AbstractPackageTestCase { /** * Get the service provider class. * * @param \Illuminate\Contracts\Foundation\Application $app * * @return string */ protected function getServiceProviderClass($app) { return BugsnagServiceProvider::class; } /** * Get the value of the given property on the given object. * * @param object $object * @param string $property * * @return mixed */ protected function getProperty($object, $property) { $propertyAccessor = function ($property) { return $this->{$property}; }; return call_user_func($propertyAccessor->bindTo($object, $object), $property); } }
<?php namespace Bugsnag\BugsnagLaravel\Tests; use Bugsnag\BugsnagLaravel\BugsnagServiceProvider; use GrahamCampbell\TestBench\AbstractPackageTestCase; abstract class AbstractTestCase extends AbstractPackageTestCase { /** * Get the service provider class. * * @param \Illuminate\Contracts\Foundation\Application $app * * @return string */ protected function getServiceProviderClass($app) { return BugsnagServiceProvider::class; } /** * Get the value of the given property on the given object. * * @param object $object * @param string $property * * @return mixed */ protected function getProperty($object, $property) { $propertyAccessor = function ($property) { return $this->{$property}; }; return $propertyAccessor->bindTo($object, $object)($property); } }
Add logging for SSH commands Change-Id: I620bfe5b796e82ae408477752d1547bd8d39a644
package com.cgi.eoss.ftep.clouds.service; import lombok.extern.log4j.Log4j2; import net.schmizz.sshj.SSHClient; import net.schmizz.sshj.connection.channel.direct.Session; import net.schmizz.sshj.transport.verification.PromiscuousVerifier; import java.io.Closeable; import java.io.IOException; /** */ @Log4j2 public class SSHSession implements Closeable { private final SSHClient sshClient; public SSHSession(String host, String username, String privateKey, String publicKey) throws IOException { sshClient = new SSHClient(); sshClient.addHostKeyVerifier(new PromiscuousVerifier()); sshClient.connect(host); sshClient.authPublickey(username, sshClient.loadKeys(privateKey, publicKey, null)); } public CommandResponse exec(String cmd) throws IOException { try (Session session = sshClient.startSession()) { CommandResponse commandResponse = new CommandResponse(session.exec(cmd)); LOG.debug("Exit status: {}, output: {} for command {}", commandResponse.getExitStatus(), commandResponse.getOutput(), cmd); return commandResponse; } } @Override public void close() throws IOException { this.sshClient.disconnect(); } }
package com.cgi.eoss.ftep.clouds.service; import net.schmizz.sshj.SSHClient; import net.schmizz.sshj.connection.channel.direct.Session; import net.schmizz.sshj.transport.verification.PromiscuousVerifier; import java.io.Closeable; import java.io.IOException; /** */ public class SSHSession implements Closeable { private final SSHClient sshClient; public SSHSession(String host, String username, String privateKey, String publicKey) throws IOException { sshClient = new SSHClient(); sshClient.addHostKeyVerifier(new PromiscuousVerifier()); sshClient.connect(host); sshClient.authPublickey(username, sshClient.loadKeys(privateKey, publicKey, null)); } public CommandResponse exec(String cmd) throws IOException { try (Session session = sshClient.startSession()) { return new CommandResponse(session.exec(cmd)); } } @Override public void close() throws IOException { this.sshClient.disconnect(); } }
Change settings for normal light.
#!/usr/bin/env python """Test Raspberry Pi camera!""" # http://picamera.readthedocs.org/en/release-1.10/index.html import picamera import sys from fractions import Fraction from time import sleep filename = sys.argv[1] camera = picamera.PiCamera() camera.vflip = True camera.hflip = True ## Low light #camera.framerate = Fraction(1, 6) #camera.shutter_speed = 4000000 #camera.iso = 1600 print "sleep" sleep(2) print "go" ## I don't use this: #camera.exposure_mode = 'off' ## Defaults # camera.sharpness = 0 # camera.contrast = 0 # camera.brightness = 50 # camera.saturation = 0 # camera.ISO = 0 # camera.video_stabilization = False # camera.exposure_compensation = 0 # camera.exposure_mode = 'auto' # camera.meter_mode = 'average' # camera.awb_mode = 'auto' # camera.image_effect = 'none' # camera.color_effects = None # camera.rotation = 0 # camera.hflip = False # camera.vflip = False # camera.crop = (0.0, 0.0, 1.0, 1.0) camera.capture(filename)
#!/usr/bin/env python """Test Raspberry Pi camera!""" # http://picamera.readthedocs.org/en/release-1.10/index.html import picamera import sys from fractions import Fraction from time import sleep filename = sys.argv[1] camera = picamera.PiCamera() camera.vflip = True camera.hflip = True camera.framerate = Fraction(1, 6) camera.shutter_speed = 4000000 #camera.exposure_mode = 'off' camera.iso = 1600 print "sleep" sleep(4) print "go" # camera.sharpness = 0 # camera.contrast = 0 # camera.brightness = 50 # camera.saturation = 0 # camera.ISO = 0 # camera.video_stabilization = False # camera.exposure_compensation = 0 # camera.exposure_mode = 'auto' # camera.meter_mode = 'average' # camera.awb_mode = 'auto' # camera.image_effect = 'none' # camera.color_effects = None # camera.rotation = 0 # camera.hflip = False # camera.vflip = False # camera.crop = (0.0, 0.0, 1.0, 1.0) camera.capture(filename)
Fix missing message in ValidationError
from django.contrib.auth import authenticate from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers class AuthTokenSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, attrs): username = attrs.get('username') password = attrs.get('password') if username and password: user = authenticate(username=username, password=password) if user: if not user.is_active: msg = _('User account is disabled.') raise serializers.ValidationError(msg) attrs['user'] = user return attrs else: msg = _('Unable to login with provided credentials.') raise serializers.ValidationError(msg) else: msg = _('Must include "username" and "password"') raise serializers.ValidationError(msg)
from django.contrib.auth import authenticate from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers class AuthTokenSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, attrs): username = attrs.get('username') password = attrs.get('password') if username and password: user = authenticate(username=username, password=password) if user: if not user.is_active: msg = _('User account is disabled.') raise serializers.ValidationError() attrs['user'] = user return attrs else: msg = _('Unable to login with provided credentials.') raise serializers.ValidationError(msg) else: msg = _('Must include "username" and "password"') raise serializers.ValidationError(msg)
Fix bug in building rendering
import colors from '../colors'; export const initialState = { rendering: { wall: {}, flatRoof: {}, brickRoof: {}, field: {} } } const materialInstances = {}; for (let material of ["wall", "flatRoof", "brickRoof", "field"]) { materialInstances[material] = new Float32Array([0.0, 0.0, 0.0, 1.0, 0.0, ...colors[material]]); } export function render(state, _setState) { const layers = ["wall", "flatRoof", "brickRoof", "field"].map(material => ({ decal: false, batches: Object.values(state.landUse.rendering[material]).map(housePart => ({ mesh: housePart, instances: materialInstances[material] })) }) ); return [layers, [], []]; }
import colors from '../colors'; export const initialState = { rendering: { wall: {}, flatRoof: {}, brickRoof: {}, field: {} } } const materialInstances = ["wall", "flatRoof", "brickRoof", "field"].map(material => new Float32Array([0.0, 0.0, 0.0, 1.0, 0.0, ...colors[material]]) ); export function render(state, _setState) { const layers = ["wall", "flatRoof", "brickRoof", "field"].map(material => ({ decal: false, batches: Object.values(state.landUse.rendering[material]).map(housePart => ({ mesh: housePart, instances: materialInstances[material] })) }) ); return [layers, [], []]; }
Set defaultProp for Accordion's children
// @flow import React, { Component, type Node } from 'react'; import { Provider } from 'mobx-react'; import { createAccordionStore } from '../accordionStore/accordionStore'; type AccordionProps = { accordion: boolean, children: Node, // activeItems: Array<string | number>, className: string, onChange: Function, }; class Accordion extends Component<AccordionProps, *> { static defaultProps = { accordion: true, onChange: () => {}, className: 'accordion', activeItems: [], children: null, }; accordionStore = createAccordionStore({ accordion: this.props.accordion, onChange: this.props.onChange, }); render() { const { className, children } = this.props; const { accordion } = this.accordionStore; return ( <Provider accordionStore={this.accordionStore}> <div role={accordion ? 'tablist' : null} className={className}> {children} </div> </Provider> ); } } export default Accordion;
// @flow import React, { Component, type Node } from 'react'; import { Provider } from 'mobx-react'; import { createAccordionStore } from '../accordionStore/accordionStore'; type AccordionProps = { accordion: boolean, children: Node, // activeItems: Array<string | number>, className: string, onChange: Function, }; class Accordion extends Component<AccordionProps, *> { static defaultProps = { accordion: true, onChange: () => {}, className: 'accordion', activeItems: [], }; accordionStore = createAccordionStore({ accordion: this.props.accordion, onChange: this.props.onChange, }); render() { const { className, children } = this.props; const { accordion } = this.accordionStore; return ( <Provider accordionStore={this.accordionStore}> <div role={accordion ? 'tablist' : null} className={className}> {children} </div> </Provider> ); } } export default Accordion;
Update speaker population command to set popit_url instead of popit_id
import logging from django.core.management.base import NoArgsCommand from django.conf import settings from popit import PopIt from speeches.models import Speaker logger = logging.getLogger(__name__) class Command(NoArgsCommand): help = 'Populates the database with people from Popit' def handle_noargs(self, **options): api = PopIt(instance = settings.POPIT_INSTANCE, hostname = settings.POPIT_HOSTNAME, api_version = settings.POPIT_API_VERSION) results = api.person.get() for person in results['results']: logger.warn('Processing: {0}'.format(person['meta']['api_url'])) speaker, created = Speaker.objects.get_or_create(popit_url=person['meta']['api_url']) logger.warn('Person was created? {0}'.format(created)) logger.warn('Persons id in the spoke db is: {0}'.format(speaker.id)) # we ignore created for now, just always set the name speaker.name = person['name'] speaker.save();
from django.core.management.base import NoArgsCommand from django.conf import settings from popit import PopIt from speeches.models import Speaker class Command(NoArgsCommand): help = 'Populates the database with people from Popit' def handle_noargs(self, **options): api = PopIt(instance = settings.POPIT_INSTANCE, hostname = settings.POPIT_HOSTNAME, api_version = settings.POPIT_API_VERSION) results = api.person.get() for person in results['results']: speaker, created = Speaker.objects.get_or_create(popit_id=person['_id']) # we ignore created for now, just always set the name speaker.name = person['name'] speaker.save();
Add template section for page menu.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title><?php echo (isset($page_title)) ? $page_title . ' - ' . lang('website_name') : lang('website_name'); ?></title> <base href="<?php echo base_url(); ?>" /> <link rel="shortcut icon" href="<?php echo base_url('favicon.ico'); ?>" /> <?php echo $head?> <?php echo $css?> <?php echo $js?> </head> <body> <div class="container"> <?php echo $this->load->view('header'); ?> <section id="main"> <?php if (isset($page_menu)): ?> <?php echo $page_menu; ?> <?php endif; ?> <?php if (isset($page_title)): ?> <header class="page-header"> <h1><?php echo $page_title; ?></h1> </header> <?php endif; ?> <?php echo $messages?> <?php echo $content?> </section> <?php echo $this->load->view('footer'); ?> </div> </body> </html>
<?php $website_name = (isset($page_title)) ? $page_title . ' - ' . lang('website_name') : lang('website_name'); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title><?php echo $website_name; ?></title> <base href="<?php echo base_url(); ?>" /> <link rel="shortcut icon" href="<?php echo base_url('favicon.ico'); ?>" /> <?php echo $head?> <?php echo $css?> <?php echo $js?> </head> <body> <div class="container"> <?php echo $this->load->view('header'); ?> <section id="main"> <?php if (isset($page_title)): ?> <header class="page-header"> <h1><?php echo $page_title; ?></h1> </header> <?php endif; ?> <?php echo $messages?> <?php echo $content?> </section> <?php echo $this->load->view('footer'); ?> </div> </body> </html>
Fix data races in internal.Timer tests
package internal_test import ( "sync/atomic" "testing" "time" "github.com/instana/go-sensor/autoprofile/internal" "github.com/stretchr/testify/assert" ) func TestTimer_Restart(t *testing.T) { var fired int64 timer := internal.NewTimer(0, 20*time.Millisecond, func() { atomic.AddInt64(&fired, 1) }) time.Sleep(30 * time.Millisecond) timer.Stop() assert.EqualValues(t, 1, atomic.LoadInt64(&fired)) time.Sleep(50 * time.Millisecond) assert.EqualValues(t, 1, atomic.LoadInt64(&fired)) } func TestTimer_Sleep(t *testing.T) { var fired int64 timer := internal.NewTimer(0, 20*time.Millisecond, func() { atomic.AddInt64(&fired, 1) }) time.Sleep(30 * time.Millisecond) timer.Stop() assert.EqualValues(t, 1, atomic.LoadInt64(&fired)) } func TestTimer_Sleep_Stopped(t *testing.T) { timer := internal.NewTimer(20*time.Millisecond, 0, func() { t.Error("stopped timer has fired") }) timer.Stop() time.Sleep(30 * time.Millisecond) }
package internal_test import ( "testing" "time" "github.com/instana/go-sensor/autoprofile/internal" "github.com/stretchr/testify/assert" ) func TestTimer_Restart(t *testing.T) { var fired int timer := internal.NewTimer(0, 20*time.Millisecond, func() { fired++ }) time.Sleep(30 * time.Millisecond) timer.Stop() assert.Equal(t, 1, fired) time.Sleep(50 * time.Millisecond) assert.Equal(t, 1, fired) } func TestTimer_Sleep(t *testing.T) { var fired int timer := internal.NewTimer(20*time.Millisecond, 0, func() { fired++ }) time.Sleep(30 * time.Millisecond) timer.Stop() assert.Equal(t, 1, fired) } func TestTimer_Sleep_Stopped(t *testing.T) { var fired int timer := internal.NewTimer(20*time.Millisecond, 0, func() { fired++ }) timer.Stop() time.Sleep(30 * time.Millisecond) assert.Equal(t, 0, fired) }
Replace localhost with the host the page was requested through.
/** * Created by Ryan Lamb on 9/16/16. */ define(function (require) { var mapEngine = require('MapClient/MapEngine/mapengine'); var mapData = require('MapData/mapdata'); var engine = new mapEngine.MapEngine(); engine.start(); var version = undefined; window.setInterval(function() { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(e) { if(xhr.readyState == 4) { var response = xhr.responseText; var data = mapData.fromJSON(JSON.parse(response)["map"]); if(version === undefined || version !== data.version) { version = data.version; console.log("New map version: " + version); engine.updateFromMap(data); } } }; var requestUrl = "http://" + window.location.host + "/getMap/test"; xhr.open('GET', requestUrl, true); xhr.send(); }, 1000); });
/** * Created by Ryan Lamb on 9/16/16. */ define(function (require) { var mapEngine = require('MapClient/MapEngine/mapengine'); var mapData = require('MapData/mapdata'); var engine = new mapEngine.MapEngine(); engine.start(); var version = undefined; window.setInterval(function() { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(e) { if(xhr.readyState == 4) { var response = xhr.responseText; var data = mapData.fromJSON(JSON.parse(response)["map"]); if(version === undefined || version !== data.version) { version = data.version; console.log("New map version: " + version); engine.updateFromMap(data); } } }; xhr.open('GET', "http://localhost:8081/getMap/test", true); xhr.send(); }, 1000); });
Update workingOn initial state so it matches empty state Former-commit-id: 299f828a4348abc930162dce36fae6bf46c50489 Former-commit-id: 040e5eded8b35b2792d28b398d085da28a18cd2c Former-commit-id: 9fc80277314d8a553b8148703be9fcb62832c20b
export const initialState = { user: { isAuthenticated: false, email: '', userType: '', isAdmin: false }, global: { workingOn: null }, rootPath: "/florence", teams: { active: {}, all: [], allIDsAndNames: [], users: [] }, datasets: { all: [], jobs: [] }, collections: { all: [], active: null, toDelete: {} }, notifications: [], preview: { selectedPage: null } };
export const initialState = { user: { isAuthenticated: false, email: '', userType: '', isAdmin: false }, global: { workingOn: {} }, rootPath: "/florence", teams: { active: {}, all: [], allIDsAndNames: [], users: [] }, datasets: { all: [], jobs: [] }, collections: { all: [], active: null, toDelete: {} }, notifications: [], preview: { selectedPage: null } };
Add toString() for invalid URL error
'use strict'; var querystring = require('querystring'); var shortener = require('../shortener'); var urlValidator = require('../urlValidator'); module.exports = (req, res, done) => { var shortUrlId, url; req.on('data', function (data) { let queryStr = data.toString(); url = querystring.parse(queryStr).link; shortUrlId = shortener.shorten(url); }); req.on('end', function () { if (!shortUrlId) { let blacklisted = urlValidator.isBlackListed(url); return done({ status: blacklisted ? 403 : 404, toString: function () { return blacklisted ? 'BLACKLISTED' : ''; } }); } res.writeHead(200, { 'Content-Type': 'text/plain', 'Content-Length': shortUrlId.length }); res.end(shortUrlId); }); };
'use strict'; var querystring = require('querystring'); var shortener = require('../shortener'); var urlValidator = require('../urlValidator'); module.exports = (req, res, done) => { var shortUrlId, url; req.on('data', function (data) { let queryStr = data.toString(); url = querystring.parse(queryStr).link; shortUrlId = shortener.shorten(url); }); req.on('end', function () { if (!shortUrlId) { return done({ status: urlValidator.isBlackListed(url) ? 403 : 404 }); } res.writeHead(200, { 'Content-Type': 'text/plain', 'Content-Length': shortUrlId.length }); res.end(shortUrlId); }); };
Test if debugger work in safari
/* eslint-disable no-undef */ import { fork, call, select } from 'redux-saga/effects'; import { isIos } from 'worona-deps'; import * as deps from '../deps'; function* redirectHome() { const contentType = yield select(deps.selectors.getContentType); if (contentType === 'Home') { const { type, category, page } = yield select( deps.selectorCreators.getSetting('theme', 'frontPage'), ); if (type === 'category') { yield call(deps.libs.push, `?cat=${category}`); } else if (type === 'page') { yield call(deps.libs.push, `?page_id=${page}`); } } } function hideIosStatusBar() { console.log(isIos); debugger; if (isIos && StatusBar) { StatusBar.hide(); console.log('hiden!'); } } export default function* starterProSagas() { yield [ fork(redirectHome), fork(hideIosStatusBar), ]; }
/* eslint-disable no-undef */ import { fork, call, select } from 'redux-saga/effects'; import { isIos } from 'worona-deps'; import * as deps from '../deps'; function* redirectHome() { const contentType = yield select(deps.selectors.getContentType); if (contentType === 'Home') { const { type, category, page } = yield select( deps.selectorCreators.getSetting('theme', 'frontPage'), ); if (type === 'category') { yield call(deps.libs.push, `?cat=${category}`); } else if (type === 'page') { yield call(deps.libs.push, `?page_id=${page}`); } } } function hideIosStatusBar() { console.log(isIos); console.log(StatusBar); if (isIos && StatusBar) { StatusBar.hide(); console.log('hiden!'); } } export default function* starterProSagas() { yield [ fork(redirectHome), fork(hideIosStatusBar), ]; }
Mark renderer test as flaky for mac tests
# coding: utf-8 ''' Integration tests for renderer functions ''' # Import Python Libs from __future__ import absolute_import, unicode_literals, print_function # Import Salt Testing libs from tests.support.case import ModuleCase from tests.support.helpers import flaky class TestJinjaRenderer(ModuleCase): ''' Validate that ordering works correctly ''' def test_dot_notation(self): ''' Test the Jinja dot-notation syntax for calling execution modules ''' ret = self.run_function('state.sls', ['jinja_dot_notation']) for state_ret in ret.values(): self.assertTrue(state_ret['result']) @flaky def test_salt_contains_function(self): ''' Test if we are able to check if a function exists inside the "salt" wrapper (AliasLoader) which is available on Jinja templates. ''' ret = self.run_function('state.sls', ['jinja_salt_contains_function']) for state_ret in ret.values(): self.assertTrue(state_ret['result'])
# coding: utf-8 ''' Integration tests for renderer functions ''' # Import Python Libs from __future__ import absolute_import, unicode_literals, print_function # Import Salt Testing libs from tests.support.case import ModuleCase class TestJinjaRenderer(ModuleCase): ''' Validate that ordering works correctly ''' def test_dot_notation(self): ''' Test the Jinja dot-notation syntax for calling execution modules ''' ret = self.run_function('state.sls', ['jinja_dot_notation']) for state_ret in ret.values(): self.assertTrue(state_ret['result']) def test_salt_contains_function(self): ''' Test if we are able to check if a function exists inside the "salt" wrapper (AliasLoader) which is available on Jinja templates. ''' ret = self.run_function('state.sls', ['jinja_salt_contains_function']) for state_ret in ret.values(): self.assertTrue(state_ret['result'])
Update sort order in order to fix tie to be under jackets
module.exports = [ { id: 'Hairstyles', required: false, sortOrder: 1 }, { id: 'Beards', required: false, sortOrder: 5 }, { id: 'Body', required: true, sortOrder: 0 }, { id: 'Glasses', required: false, sortOrder: 2 }, { id: 'Scarfes', required: false, sortOrder: 4 }, { id: 'Shirts', required: false, sortOrder: 1 }, { id: 'Tie', required: false, sortOrder: 2 }, { id: 'Eyes', required: true, sortOrder: 1, subColors: true }, { id: 'Jackets', required: false, sortOrder: 3 }, { id: 'Mouths', required: true, sortOrder: 1 } ];
module.exports = [ { id: 'Hairstyles', required: false, sortOrder: 1 }, { id: 'Beards', required: false, sortOrder: 4 }, { id: 'Body', required: true, sortOrder: 0 }, { id: 'Glasses', required: false, sortOrder: 2 }, { id: 'Scarfes', required: false, sortOrder: 3 }, { id: 'Shirts', required: false, sortOrder: 1 }, { id: 'Tie', required: false, sortOrder: 2 }, { id: 'Eyes', required: true, sortOrder: 1, subColors: true }, { id: 'Jackets', required: false, sortOrder: 1 }, { id: 'Mouths', required: true, sortOrder: 1 } ];
Correct sample with new qualified name of the class
# # Menu: Examples > Views > Py > Google Web View # Kudos: Paul Colton # License: EPL 1.0 # from org.eclipse.swt.browser import LocationListener from org.eclipse.eclipsemonkey.ui.views import GenericScriptableView from org.eclipse.ui import IWorkbenchPage class MyLocationListener(LocationListener): def changing(self, event): location = event.location # Print out the location to the console print "You clicked on: " + location def changed(self, event): pass page = window.getActivePage() view = page.showView( "org.eclipse.eclipsemonkey.ui.scriptableView.GenericScriptableView", "GoogleWebView", IWorkbenchPage.VIEW_VISIBLE) view.setViewTitle("Google") browser = view.getBrowser() browser.setUrl("http://www.google.com") browser.addLocationListener(MyLocationListener());
# # Menu: Examples > Views > Py > Google Web View # Kudos: Paul Colton # License: EPL 1.0 # from org.eclipse.swt.browser import LocationListener from org.eclipse.eclipsemonkey.ui.scriptableView import GenericScriptableView from org.eclipse.ui import IWorkbenchPage class MyLocationListener(LocationListener): def changing(self, event): location = event.location # Print out the location to the console print "You clicked on: " + location def changed(self, event): pass page = window.getActivePage() view = page.showView( "org.eclipse.eclipsemonkey.ui.scriptableView.GenericScriptableView", "GoogleWebView", IWorkbenchPage.VIEW_VISIBLE) view.setViewTitle("Google") browser = view.getBrowser() browser.setUrl("http://www.google.com") browser.addLocationListener(MyLocationListener());
Update affected Puppet action constructor to take in "config" argument.
from st2actions.runners.pythonrunner import Action from lib.puppet_client import PuppetHTTPAPIClient class PuppetBasePythonAction(Action): def __init__(self, config): super(PuppetBasePythonAction, self).__init__(config=config) self.client = self._get_client() def _get_client(self): master_config = self.config['master'] auth_config = self.config['auth'] client = PuppetHTTPAPIClient(master_hostname=master_config['hostname'], master_port=master_config['port'], client_cert_path=auth_config['client_cert_path'], client_cert_key_path=auth_config['client_cert_key_path'], ca_cert_path=auth_config['ca_cert_path']) return client
from st2actions.runners.pythonrunner import Action from lib.puppet_client import PuppetHTTPAPIClient class PuppetBasePythonAction(Action): def __init__(self): super(PupperBasePythonAction, self).__init__() self.client = self._get_client() def _get_client(self): master_config = self.config['master'] auth_config = self.config['auth'] client = PuppetHTTPAPIClient(master_hostname=master_config['hostname'], master_port=master_config['port'], client_cert_path=auth_config['client_cert_path'], client_cert_key_path=auth_config['client_cert_key_path'], ca_cert_path=auth_config['ca_cert_path']) return client
Add new items when button is pressed
package net.emteeware.emteeseason; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import static net.emteeware.emteeseason.R.id.SeriesList; public class MainActivity extends AppCompatActivity { ArrayList<String> items = new ArrayList<>(); ArrayAdapter<String> adapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); items.add( "Suits"); ListView listview = (ListView) findViewById(R.id.SeriesList); adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, items); listview.setAdapter(adapter); } public void addItems(View view) { items.add("Blue Bloods"); items.add("Sherlock"); adapter.notifyDataSetChanged(); } }
package net.emteeware.emteeseason; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import static net.emteeware.emteeseason.R.id.SeriesList; public class MainActivity extends AppCompatActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ListView listview = (ListView) findViewById(R.id.SeriesList); String[] items = new String[] {"Blue Bloods", "Marvel's Daredevil", "Suits"}; ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items); listview.setAdapter(adapter); } }
Check msg in a way that passes for all GDAL versions
# Testing use of cpl_errs import pytest import rasterio from rasterio.errors import RasterioIOError def test_io_error(tmpdir): """RasterioIOError is raised when a disk file can't be opened. Newlines are removed from GDAL error messages.""" with pytest.raises(RasterioIOError) as exc_info: rasterio.open(str(tmpdir.join('foo.tif'))) msg, = exc_info.value.args assert "\n" not in msg def test_io_error_env(tmpdir): with rasterio.drivers() as env: drivers_start = env.drivers() with pytest.raises(RasterioIOError): rasterio.open(str(tmpdir.join('foo.tif'))) assert env.drivers() == drivers_start def test_bogus_band_error(): with rasterio.open('tests/data/RGB.byte.tif') as src: assert src._has_band(4) is False
# Testing use of cpl_errs import pytest import rasterio from rasterio.errors import RasterioIOError def test_io_error(tmpdir): with pytest.raises(RasterioIOError) as exc_info: rasterio.open(str(tmpdir.join('foo.tif'))) msg, = exc_info.value.args assert msg.startswith("'{0}'".format(tmpdir.join('foo.tif'))) assert ("does not exist in the file system, and is not recognised as a " "supported dataset name.") in msg def test_io_error_env(tmpdir): with rasterio.drivers() as env: drivers_start = env.drivers() with pytest.raises(RasterioIOError): rasterio.open(str(tmpdir.join('foo.tif'))) assert env.drivers() == drivers_start def test_bogus_band_error(): with rasterio.open('tests/data/RGB.byte.tif') as src: assert src._has_band(4) is False
Support relative paths in bin/run_metric As a result of this patch, it will be possible to run: bin/run_metric MemoryMetric test_data/memory_dumps.json ^^^^^^^^^^^^^^^^^^^^^^^^^^^ instead of: bin/run_metric MemoryMetric $PWD/test_data/memory_dumps.json ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Review URL: https://codereview.chromium.org/1836283008
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os from perf_insights import map_single_trace from perf_insights import function_handle from perf_insights.mre import file_handle from perf_insights.mre import job as job_module _METRIC_MAP_FUNCTION_FILENAME = 'metric_map_function.html' _METRIC_MAP_FUNCTION_NAME = 'metricMapFunction' def _GetMetricsDir(): return os.path.dirname(os.path.abspath(__file__)) def _GetMetricRunnerHandle(metric): assert isinstance(metric, basestring) metrics_dir = _GetMetricsDir() metric_mapper_path = os.path.join(metrics_dir, _METRIC_MAP_FUNCTION_FILENAME) modules_to_load = [function_handle.ModuleToLoad(filename=metric_mapper_path)] map_function_handle = function_handle.FunctionHandle( modules_to_load, _METRIC_MAP_FUNCTION_NAME, {'metric': metric}) return job_module.Job(map_function_handle, None) def RunMetric(filename, metric, extra_import_options=None): url = 'file://' + os.path.abspath(filename) th = file_handle.URLFileHandle(filename, url) result = map_single_trace.MapSingleTrace( th, _GetMetricRunnerHandle(metric), extra_import_options) return result
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os from perf_insights import map_single_trace from perf_insights import function_handle from perf_insights.mre import file_handle from perf_insights.mre import job as job_module _METRIC_MAP_FUNCTION_FILENAME = 'metric_map_function.html' _METRIC_MAP_FUNCTION_NAME = 'metricMapFunction' def _GetMetricsDir(): return os.path.dirname(os.path.abspath(__file__)) def _GetMetricRunnerHandle(metric): assert isinstance(metric, basestring) metrics_dir = _GetMetricsDir() metric_mapper_path = os.path.join(metrics_dir, _METRIC_MAP_FUNCTION_FILENAME) modules_to_load = [function_handle.ModuleToLoad(filename=metric_mapper_path)] map_function_handle = function_handle.FunctionHandle( modules_to_load, _METRIC_MAP_FUNCTION_NAME, {'metric': metric}) return job_module.Job(map_function_handle, None) def RunMetric(filename, metric, extra_import_options=None): th = file_handle.URLFileHandle(filename, 'file://' + filename) result = map_single_trace.MapSingleTrace( th, _GetMetricRunnerHandle(metric), extra_import_options) return result
Remove errant char and pass in encoding to make readFileSync read as text and not a buffer
var fs = require('fs'); var path = require('path'); var stripComments = require('strip-json-comments'); if (process.argv.length < 3) { console.log("Usage: node charlie /path/to/object/schema"); console.log(" * Please see https://github.com/project-badass/charlie"); console.log(" * for information about the object schema file."); process.exit(1); } var schemaPath = path.normalize(process.argv[2]); var workingFolder = path.dirname(schemaPath); try { var schemaData = fs.readFileSync(schemaPath, { encoding : 'utf8'}); } catch (err) { console.log(err); console.log("Usage: node charlie /path/to/object/schema"); console.log(" * There was a problem reading your object schema."); console.log(" * Please verify the path and that the permissions"); console.log(" * allow this process to read the file."); console.log(" * Visit https://github.com/project-badass/charlie"); console.log(" * for information about the object schema file."); process.exit(1); } console.dir(schemaData);
var fs = require('fs'); var path = require('path'); var stripComments = require('strip-json-comments'); if (process.argv.length < 3) { console.log("Usage: node charlie /path/to/object/schema"); console.log(" * Please see https://github.com/project-badass/charlie"); console.log(" * for information about the object schema file."); process.exit(1); } var schemaPath = path.normalize(process.argv[2]); var workingFolder = path.dirname(schemaPath); try { var schemaData = fs.readFileSync(schemaPath)1; } catch (err) { console.log(err); console.log("Usage: node charlie /path/to/object/schema"); console.log(" * There was a problem reading your object schema."); console.log(" * Please verify the path and that the permissions"); console.log(" * allow this process to read the file."); console.log(" * Visit https://github.com/project-badass/charlie"); console.log(" * for information about the object schema file."); process.exit(1); } console.dir(schemaData);
Add fix issue with linux time
import dotProp from 'dot-prop-immutable' import * as types from './forecastDailyActionTypes' const initialState = { forecastDaily: { data: [], app: { locationId: 5128581 // nyc usa }, ui: {} } } const updateAppIsFetching = (state, action, value) => { return dotProp.set(state, 'forecastDaily.app.isFetching', value) } const updateData = (state, action) => { const { payload: { list } } = action const data = list.map(x => { return { date: new Date(x.dt * 1000).toString(), tempMin: x.temp.min, tempMax: x.temp.max, weatherDescription: x.weather[0].description } }) return dotProp.set(state, 'forecastDaily.data', data) } function forecastDailyReducer (state = initialState, action) { switch (action.type) { case types.GET_FORECAST_DAILY_PENDING: return updateAppIsFetching(state, action, true) case types.GET_FORECAST_DAILY_FULFILLED: updateAppIsFetching(state, action, false) return updateData(state, action) default: return state } } export default forecastDailyReducer
import dotProp from 'dot-prop-immutable' import * as types from './forecastDailyActionTypes' const initialState = { forecastDaily: { data: [], app: { locationId: 5128581 // nyc usa }, ui: {} } } const updateAppIsFetching = (state, action, value) => { return dotProp.set(state, 'forecastDaily.app.isFetching', value) } const updateData = (state, action) => { const { payload: { list } } = action const data = list.map(x => { return { date: new Date(x.dt).toString(), tempMin: x.temp.min, tempMax: x.temp.max, weatherDescription: x.weather[0].description } }) return dotProp.set(state, 'forecastDaily.data', data) } function forecastDailyReducer (state = initialState, action) { switch (action.type) { case types.GET_FORECAST_DAILY_PENDING: return updateAppIsFetching(state, action, true) case types.GET_FORECAST_DAILY_FULFILLED: updateAppIsFetching(state, action, false) return updateData(state, action) default: return state } } export default forecastDailyReducer
Add async attribute back to the install script
import React from "react"; const Template = ({ children }) => ( <html lang="en"> <head> <meta charSet="utf-8" /> <meta httpEquiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="author" content="Sylvain Boulade" /> <link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet" /> <link rel="stylesheet" href="main.css" /> <title>Sylvain {"'"}hihuz{"'"} Boulade</title> <link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon.png" /> <link rel="icon" type="image/png" href="favicon-32x32.png" sizes="32x32" /> <link rel="icon" type="image/png" href="favicon-16x16.png" sizes="16x16" /> <link rel="manifest" href="manifest.json" /> <meta name="theme-color" content="#333e4b" /> </head> <body> {children} <script src="install.js" async /> </body> </html> ); export default Template;
import React from "react"; const Template = ({ children }) => ( <html lang="en"> <head> <meta charSet="utf-8" /> <meta httpEquiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="author" content="Sylvain Boulade" /> <link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet" /> <link rel="stylesheet" href="main.css" /> <title>Sylvain {"'"}hihuz{"'"} Boulade</title> <link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon.png" /> <link rel="icon" type="image/png" href="favicon-32x32.png" sizes="32x32" /> <link rel="icon" type="image/png" href="favicon-16x16.png" sizes="16x16" /> <link rel="manifest" href="manifest.json" /> <meta name="theme-color" content="#333e4b" /> </head> <body> {children} <script src="install.js" /> </body> </html> ); export default Template;
Add page_size validator even if get.max_items is not set
<?php $pagination_custom_page_size = $this->configuration->getValue('get.pagination_custom_page_size'); $max_items = $this->configuration->getValue('get.max_items'); ?> /** * Returns the list of pagination validators * @return array an array of validators */ protected function getPaginationValidators() { $validators = array(); $validators['page'] = new sfValidatorInteger(array('min' => 1, 'required' => false)); <?php if ($pagination_custom_page_size): ?> $validators['page_size'] = new sfValidatorInteger(array( 'min' => 1, <?php if ($max_items > 0): ?> 'max' => <?php echo $max_items ?>, <?php endif; ?> 'required' => false )); <?php endif; ?> return $validators; }
<?php $pagination_custom_page_size = $this->configuration->getValue('get.pagination_custom_page_size'); $max_items = $this->configuration->getValue('get.max_items'); ?> /** * Returns the list of pagination validators * @return array an array of validators */ protected function getPaginationValidators() { $validators = array(); $validators['page'] = new sfValidatorInteger(array('min' => 1, 'required' => false)); <?php if ($pagination_custom_page_size && ($max_items > 0)): ?> $validators['page_size'] = new sfValidatorInteger(array( 'min' => 1, 'max' => <?php echo $max_items ?>, 'required' => false )); <?php endif; ?> return $validators; }
Put webhook custom data at root
"use strict"; var jade = require("jade"); var i18n = require("i18next"); var path = require("path"); var configuration = require("../server/utils/environment_configuration"); var mailgun = require("mailgun-js")({apiKey: configuration.emailApiKey, domain: configuration.emailApiUrl}); var templateWithModel = jade.compileFile(path.join(__dirname, "../views/emails/reminder.jade")); exports.send = function send(request, response) { var event = request.body.event; var recipientVariables = {}; var recipients = request.body.recipients.map(function (recipient) { recipientVariables[recipient.email] = recipient; return recipient.email; }); var data = { from: configuration.emailFrom, to: recipients, subject: i18n.t("app.reminder.subject") + " [" + event.name + "]", html: templateWithModel({t: i18n.t, event: event}), "recipient-variables": recipientVariables, "v:eventId": event.id, "v:participantId": "%recipient.id%" }; mailgun.messages().send(data) .then(function () { response.status(201).end(); }) .catch(function () { response.status(503).end(); }); };
"use strict"; var jade = require("jade"); var i18n = require("i18next"); var path = require("path"); var configuration = require("../server/utils/environment_configuration"); var mailgun = require("mailgun-js")({apiKey: configuration.emailApiKey, domain: configuration.emailApiUrl}); var templateWithModel = jade.compileFile(path.join(__dirname, "../views/emails/reminder.jade")); exports.send = function send(request, response) { var event = request.body.event; var recipientVariables = {}; var recipients = request.body.recipients.map(function (recipient) { recipientVariables[recipient.email] = recipient; return recipient.email; }); var data = { from: configuration.emailFrom, to: recipients, subject: i18n.t("app.reminder.subject") + " [" + event.name + "]", html: templateWithModel({t: i18n.t, event: event}), "recipient-variables": recipientVariables, "v:hook-data": {eventId: event.id, participantId: "%recipient.id%"} }; mailgun.messages().send(data) .then(function () { response.status(201).end(); }) .catch(function () { response.status(503).end(); }); };
Remove redundant data (error time and events)
ErrorModel = function (appId) { var self = this; this.appId = appId; this.errors = {}; this.startTime = Date.now(); } _.extend(ErrorModel.prototype, KadiraModel.prototype); ErrorModel.prototype.buildPayload = function() { var metrics = _.values(this.errors); this.startTime = Date.now(); this.errors = {}; return {errors: metrics}; }; ErrorModel.prototype.trackError = function(ex, trace) { var key = trace.type + ':' + ex.message; if(this.errors[key]) { this.errors[key].count++; } else { this.errors[key] = this._formatError(ex, trace); } }; ErrorModel.prototype._formatError = function(ex, trace) { var source = trace.type + ':' + trace.name; return { appId : this.appId, name : ex.message, source : source, startTime : trace.at, type : 'server', trace: trace, stack : [{stack: ex.stack}], count: 1, } };
ErrorModel = function (appId) { var self = this; this.appId = appId; this.errors = {}; this.startTime = Date.now(); } _.extend(ErrorModel.prototype, KadiraModel.prototype); ErrorModel.prototype.buildPayload = function() { var metrics = _.values(this.errors); this.startTime = Date.now(); this.errors = {}; return {errors: metrics}; }; ErrorModel.prototype.trackError = function(ex, trace) { var key = trace.type + ':' + ex.message; if(this.errors[key]) { this.errors[key].count++; } else { this.errors[key] = this._formatError(ex, trace); } }; ErrorModel.prototype._formatError = function(ex, trace) { var source = trace.type + ':' + trace.name; return { appId : this.appId, name : ex.message, source : source, startTime : trace.at, type : 'server', trace: trace, stack : [{at: trace.at, events: trace.events, stack: ex.stack}], count: 1, } };
Simplify and optimize the code git-svn-id: 14496471c1e7f47aed4ccd4e743787d9efef7a8c@586 2772adf2-ac07-0410-9d30-e29d8120292e
<?php require_once(dirname(__FILE__)."/../pfccommand.class.php"); class pfcCommand_connect extends pfcCommand { function run(&$xml_reponse, $clientid, $param, $sender, $recipient, $recipientid) { $c =& $this->c; $u =& $this->u; // disconnect last connected users from the server if necessary $container =& $c->getContainerInstance(); $disconnected_users = $container->removeObsoleteNick(NULL, $c->timeout); // setup some user meta $nickid = $u->nickid; // store the user ip $container->setMeta($_SERVER["REMOTE_ADDR"], "ip", "nickname", $nickid); // store the admin flag $container->setMeta($c->isadmin, "isadmin", "nickname", $nickid); // connect to the server $xml_reponse->addScript("pfc.handleResponse('connect', 'ok', '');"); return $clientid; } } ?>
<?php require_once(dirname(__FILE__)."/../pfccommand.class.php"); class pfcCommand_connect extends pfcCommand { function run(&$xml_reponse, $clientid, $param, $sender, $recipient, $recipientid) { $c =& $this->c; $u =& $this->u; // disconnect last connected users from the server if necessary $container =& $c->getContainerInstance(); $disconnected_users = $container->removeObsoleteNick(NULL, $c->timeout); // setup some user meta $nickid = $container->getNickId($u->nick); // store the user ip $container->setMeta($_SERVER["REMOTE_ADDR"], "ip", "nickname", $nickid); // store the admin flag $container->setMeta($c->isadmin, "isadmin", "nickname", $nickid); // connect to the server $xml_reponse->addScript("pfc.handleResponse('connect', 'ok', '');"); return $clientid; } } ?>
Change direction on game click
function Level(game, level) { this.game = game; this.remaining = level; this.interval = undefined; this.period = 4; this.intervalTime = 10; this.velocity = 2 * Math.PI / (1000 * this.period); this.forward = true; this.game.setRemaining(level); var me = this; this.game.board.on('click', function() { if (me.interval) { me.clicked(); } else { me.start(); } }); } Level.prototype.start = function() { var me = this; this.interval = setInterval(function() { me.redraw(); }, this.intervalTime); }; Level.prototype.clicked = function() { this.forward = !this.forward; this.remaining--; this.game.setRemaining(this.remaining); if (this.remaining === 0) { clearInterval(this.interval); this.interval = undefined; } }; Level.prototype.redraw = function() { this.game.arcCenter += this.velocity * this.intervalTime * (this.forward ? 1 : -1); this.game.arc.startAngle(this.game.arcCenter - this.game.arcWidth); this.game.arcEl .datum({endAngle: this.game.arcCenter + this.game.arcWidth}) .attr('d', this.game.arc); };
function Level(game, level) { this.game = game; this.level = level; this.interval = undefined; this.period = 4; this.intervalTime = 10; this.velocity = 2 * Math.PI / (1000 * this.period); this.game.setRemaining(level); var me = this; this.game.board.on('click', function() { if (me.interval) { me.clicked(); } else { me.start(); } }); } Level.prototype.start = function() { var me = this; this.interval = setInterval(function() { me.redraw(); }, this.intervalTime); }; Level.prototype.clicked = function() { console.log('Clicked'); }; Level.prototype.redraw = function() { this.game.arcCenter += this.velocity * this.intervalTime; this.game.arc.startAngle(this.game.arcCenter - this.game.arcWidth); this.game.arcEl .datum({endAngle: this.game.arcCenter + this.game.arcWidth}) .attr('d', this.game.arc); };
Use `ember-cli-babel` to resolve module paths
const Babel = require('broccoli-babel-transpiler'); const { resolveRelativeModulePath } = require('ember-cli-babel/lib/relative-module-paths'); const enifed = require('./transforms/transform-define'); const injectNodeGlobals = require('./transforms/inject-node-globals'); module.exports = function processModulesOnly(tree, strict = false) { let transformOptions = { noInterop: true }; // These options need to be exclusive for some reason, even the key existing // on the options hash causes issues. if (strict) { transformOptions.strict = true; } else { transformOptions.loose = true; } let options = { sourceMap: true, plugins: [ // ensures `@glimmer/compiler` requiring `crypto` works properly // in both browser and node-land injectNodeGlobals, ['module-resolver', { resolvePath: resolveRelativeModulePath }], ['transform-es2015-modules-amd', transformOptions], enifed, ], moduleIds: true, }; return new Babel(tree, options); };
const Babel = require('broccoli-babel-transpiler'); const resolveModuleSource = require('amd-name-resolver').moduleResolve; const enifed = require('./transforms/transform-define'); const injectNodeGlobals = require('./transforms/inject-node-globals'); module.exports = function processModulesOnly(tree, strict = false) { let transformOptions = { noInterop: true }; // These options need to be exclusive for some reason, even the key existing // on the options hash causes issues. if (strict) { transformOptions.strict = true; } else { transformOptions.loose = true; } let options = { sourceMap: true, plugins: [ // ensures `@glimmer/compiler` requiring `crypto` works properly // in both browser and node-land injectNodeGlobals, ['module-resolver', { resolvePath: resolveModuleSource }], ['transform-es2015-modules-amd', transformOptions], enifed, ], moduleIds: true, }; return new Babel(tree, options); };
Install latest oedialect version from GitHub instead from PyPi
#! /usr/bin/env python # coding: utf-8 from setuptools import find_packages, setup setup(name='egoio', author='NEXT ENERGY, Reiner Lemoine Institut gGmbH, ZNES', author_email='ulf.p.mueller@hs-flensburg.de', description='ego input/output repository', version='0.4.5', url='https://github.com/openego/ego.io', packages=find_packages(), license='GNU Affero General Public License v3.0', install_requires=[ 'geoalchemy2 >= 0.3.0, <= 0.4.1', 'sqlalchemy >= 1.0.11, <= 1.2.0', 'keyring >= 4.0', 'keyrings.alt', 'psycopg2', 'oedialect @ https://github.com/OpenEnergyPlatform/oedialect/archive/master.zip'], extras_require={ "sqlalchemy": 'postgresql'}, package_data={'tools': 'sqlacodegen_oedb.sh'} )
#! /usr/bin/env python # coding: utf-8 from setuptools import find_packages, setup setup(name='egoio', author='NEXT ENERGY, Reiner Lemoine Institut gGmbH, ZNES', author_email='ulf.p.mueller@hs-flensburg.de', description='ego input/output repository', version='0.4.5', url='https://github.com/openego/ego.io', packages=find_packages(), license='GNU Affero General Public License v3.0', install_requires=[ 'geoalchemy2 >= 0.3.0, <= 0.4.1', 'sqlalchemy >= 1.0.11, <= 1.2.0', 'keyring >= 4.0', 'keyrings.alt', 'psycopg2'], extras_require={ "sqlalchemy": 'postgresql'}, package_data={'tools': 'sqlacodegen_oedb.sh'} )
Add child_process.exec succeeds test case
/* global describe it */ 'use strict' const chai = require('chai') const chaiAsPromised = require('chai-as-promised') const requireInject = require('require-inject') const sinon = require('sinon') const sinonChai = require('sinon-chai') require('sinon-as-promised') chai.use(chaiAsPromised) chai.use(sinonChai) const expect = chai.expect describe('exec', function () { it('rejects if childProcess.exec fails', function () { const exec = sinon.stub().yields('some error') const stubs = { child_process: { exec } } const util = requireInject('../lib/util', stubs) return expect(util.exec('command')) .to.be.eventually.rejectedWith('some error') }) it('resolves if childProcess.exec succeeds', function () { const exec = sinon.stub().yields(null, 'stdout', 'stderr') const stubs = { child_process: { exec } } const util = requireInject('../lib/util', stubs) return expect(util.exec('command')).to.eventually.deep.equal({ command: 'command', stdout: 'stdout', stderr: 'stderr' }) }) })
/* global describe it */ 'use strict' const chai = require('chai') const chaiAsPromised = require('chai-as-promised') const requireInject = require('require-inject') const sinon = require('sinon') const sinonChai = require('sinon-chai') require('sinon-as-promised') chai.use(chaiAsPromised) chai.use(sinonChai) const expect = chai.expect describe('exec', function () { it('rejects if childProcess.exec fails', function () { const exec = sinon.stub().yields('some error') const stubs = { child_process: { exec } } const util = requireInject('../lib/util', stubs) return expect(util.exec('command')) .to.be.eventually.rejectedWith('some error') }) }) })
Fix pages containing multiple tab sets
jQuery(function($) { $('.tabify .tabs a').bind('click', function() { var href = $(this).attr('href'), tabify = $(this).closest('.tabify'), tabContent = tabify.find(href); tabify.find('.tabs a').removeClass('active'); // clear the active tabs tabify.find('.tabs a[href=' + href + ']').addClass('active'); // activate the clicked tab tabify.find('.tabContent').removeClass('active'); // clear the active content tabContent.addClass('active'); // show the clicked content // Change the hash without scrolling tabContent.attr('id', ''); window.location.hash = href; tabContent.attr('id', href.substr(1)); // remove the sharp return false; }); //| //| If there's a #tab in the URL, CLICK ON THAT TAB!!! //| if(window.location.hash) { $('.tabs a[href="' + window.location.hash + '"]').click(); } });
jQuery(function($) { $('.tabify .tabs a').bind('click', function() { var href = $(this).attr('href'); var tabContent = $(href); $('.tabify .tabs a').removeClass('active'); // clear the active tabs $('.tabify .tabs a[href=' + href + ']').addClass('active'); // activate the clicked tab $('.tabify .tabContent').removeClass('active'); // clear the active content tabContent.addClass('active'); // show the clicked content // Change the hash without scrolling tabContent.attr('id', ''); window.location.hash = href; tabContent.attr('id', href.substr(1)); // remove the sharp return false; }); //| //| If there's a #tab in the URL, CLICK ON THAT TAB!!! //| if(window.location.hash) { $('.tabs a[href="' + window.location.hash + '"]').click(); } });
Add extra missing items to the entity
from mangopaysdk.entities.entitybase import EntityBase class Card(EntityBase): """Card entity""" def __init__(self, id = None): self.UserId = None # MMYY self.ExpirationDate = None # first 6 and last 4 are real card numbers for example: 497010XXXXXX4414 self.Alias = None # The card provider, it could be CB, VISA, MASTERCARD, etc. self.CardProvider = None # CardType enum self.CardType = None self.Country = None self.Product = None self.BankCode = None # Boolean self.Active = None self.Currency = None # UNKNOWN, VALID, INVALID self.Validity = None return super(Card, self).__init__(id)
from mangopaysdk.entities.entitybase import EntityBase class Card(EntityBase): """Card entity""" def __init__(self, id = None): # MMYY self.ExpirationDate = None # first 6 and last 4 are real card numbers for example: 497010XXXXXX4414 self.Alias = None # The card provider, it could be CB, VISA, MASTERCARD, etc. self.CardProvider = None # CardType enum self.CardType = None self.Product = None self.BankCode = None # Boolean self.Active = None self.Currency = None # UNKNOWN, VALID, INVALID self.Validity = None return super(Card, self).__init__(id)
Remove errored state (lets rely on a single failure state)
from enum import Enum class Status(Enum): unknown = 0 queued = 1 in_progress = 2 finished = 3 collecting_results = 4 def __str__(self): return STATUS_LABELS[self] class Result(Enum): unknown = 0 passed = 1 failed = 2 skipped = 3 aborted = 5 timedout = 6 def __str__(self): return RESULT_LABELS[self] class Provider(Enum): unknown = 0 koality = 'koality' class Cause(Enum): unknown = 0 manual = 1 push = 2 retry = 3 def __str__(self): return CAUSE_LABELS[self] STATUS_LABELS = { Status.unknown: 'Unknown', Status.queued: 'Queued', Status.in_progress: 'In progress', Status.finished: 'Finished' } RESULT_LABELS = { Result.unknown: 'Unknown', Result.passed: 'Passed', Result.failed: 'Failed', Result.skipped: 'Skipped', Result.aborted: 'Aborted', Result.timedout: 'Timed out' } CAUSE_LABELS = { Cause.unknown: 'Unknown', Cause.manual: 'Manual', Cause.push: 'Code Push', Cause.retry: 'Retry', }
from enum import Enum class Status(Enum): unknown = 0 queued = 1 in_progress = 2 finished = 3 collecting_results = 4 def __str__(self): return STATUS_LABELS[self] class Result(Enum): unknown = 0 passed = 1 failed = 2 skipped = 3 errored = 4 aborted = 5 timedout = 6 def __str__(self): return RESULT_LABELS[self] class Provider(Enum): unknown = 0 koality = 'koality' class Cause(Enum): unknown = 0 manual = 1 push = 2 retry = 3 def __str__(self): return CAUSE_LABELS[self] STATUS_LABELS = { Status.unknown: 'Unknown', Status.queued: 'Queued', Status.in_progress: 'In progress', Status.finished: 'Finished' } RESULT_LABELS = { Result.unknown: 'Unknown', Result.passed: 'Passed', Result.failed: 'Failed', Result.skipped: 'Skipped', Result.errored: 'Errored', Result.aborted: 'Aborted', Result.timedout: 'Timed out' } CAUSE_LABELS = { Cause.unknown: 'Unknown', Cause.manual: 'Manual', Cause.push: 'Code Push', Cause.retry: 'Retry', }
Remove harmful disabling of scaling by user
<head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-capable" content="yes"> <link rel="apple-touch-icon-precomposed" href="{{ URL::asset('apple-touch-icon-precomposed.png') }}"> <meta property="og:title" content="iRail.be" /> <meta property="og:type" content="website" /> <meta property="og:url" content="https://irail.be" /> <meta property="og:image" content="{{ URL::asset('apple-touch-icon-precomposed.png') }}" /> <title>iRail.be</title> <link rel="shortcut icon" href="{{ URL::asset('favicon.ico') }}"/> <link rel="stylesheet" href="{{ URL::asset('builds/css/main.css') }}"> <link href='//fonts.googleapis.com/css?family=Source+Sans+Pro:400,700,400italic' rel='stylesheet' type='text/css'> <script src="{{ URL::asset('builds/js/scripts.js') }}"></script> </head>
<head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <meta name="mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-capable" content="yes"> <link rel="apple-touch-icon-precomposed" href="{{ URL::asset('apple-touch-icon-precomposed.png') }}"> <meta property="og:title" content="iRail.be" /> <meta property="og:type" content="website" /> <meta property="og:url" content="https://irail.be" /> <meta property="og:image" content="{{ URL::asset('apple-touch-icon-precomposed.png') }}" /> <title>iRail.be</title> <link rel="shortcut icon" href="{{ URL::asset('favicon.ico') }}"/> <link rel="stylesheet" href="{{ URL::asset('builds/css/main.css') }}"> <link href='//fonts.googleapis.com/css?family=Source+Sans+Pro:400,700,400italic' rel='stylesheet' type='text/css'> <script src="{{ URL::asset('builds/js/scripts.js') }}"></script> </head>
Support fatal errors in converter
<?php /** * Converts any PHP Error to ErrbitException * Extracted from the Errbit Error Handler, in case you want to use your own errorhandler, and convert errors to Exceptions. * @author deathowl <csergo.balint@ustream.tv> */ namespace Errbit\Utils; use Errbit\Errors\Error; use Errbit\Errors\Fatal; use Errbit\Errors\Notice; use Errbit\Errors\Warning; /** * Class Converter * @package Errbit\Utils */ class Converter { public static function createDefault() { return new self(); } /** * @param int $code * @param string $message * @param string $file * @param int $line * @param string $backtrace * * @return Error|Notice|Warning */ public function convert($code, $message, $file, $line, $backtrace) { switch ($code) { case E_NOTICE: case E_USER_NOTICE: $exception = new Notice($message, $line, $file, $backtrace); break; case E_WARNING: case E_USER_WARNING: $exception = new Warning($message, $line, $file, $backtrace); break; case E_RECOVERABLE_ERROR: case E_ERROR: case E_CORE_ERROR: $exception = new Fatal($message, $line, $file, $backtrace); break; case E_USER_ERROR: default: $exception = new Error($message, $line, $file, $backtrace); } return $exception; } }
<?php /** * Converts any PHP Error to ErrbitException * Extracted from the Errbit Error Handler, in case you want to use your own errorhandler, and convert errors to Exceptions. * @author deathowl <csergo.balint@ustream.tv> */ namespace Errbit\Utils; use Errbit\Errors\Error; use Errbit\Errors\Notice; use Errbit\Errors\Warning; /** * Class Converter * @package Errbit\Utils */ class Converter { public static function createDefault() { return new self(); } /** * @param int $code * @param string $message * @param string $file * @param int $line * @param string $backtrace * * @return Error|Notice|Warning */ public function convert($code, $message, $file, $line, $backtrace) { switch ($code) { case E_NOTICE: case E_USER_NOTICE: $exception = new Notice($message, $line, $file, $backtrace); break; case E_WARNING: case E_USER_WARNING: $exception = new Warning($message, $line, $file, $backtrace); break; case E_ERROR: case E_USER_ERROR: default: $exception = new Error($message, $line, $file, $backtrace); } return $exception; } }
Use field.to_python to do django type conversions on the field before checking if dirty. This solves issues where you might have a decimal field that you write a string to, eg: >>> m = MyModel.objects.get(id=1) >>> m.my_decimal_field Decimal('1.00') >>> m.my_decimal_field = u'1.00' # from a form or something >>> m.is_dirty() # currently evaluates to True, should evaluate to False False This pull request could probably use some unit testing, but it should be safe as the base class for django fields defines to_python as: def to_python(self, value): return value So, any field type that does not have an explicit to_python method will behave as before this change.
# Adapted from http://stackoverflow.com/questions/110803/dirty-fields-in-django from django.db.models.signals import post_save class DirtyFieldsMixin(object): def __init__(self, *args, **kwargs): super(DirtyFieldsMixin, self).__init__(*args, **kwargs) post_save.connect(reset_state, sender=self.__class__, dispatch_uid='%s-DirtyFieldsMixin-sweeper' % self.__class__.__name__) reset_state(sender=self.__class__, instance=self) def _as_dict(self): return dict([(f.name, f.to_python(getattr(self, f.name))) for f in self._meta.local_fields if not f.rel]) def get_dirty_fields(self): new_state = self._as_dict() return dict([(key, value) for key, value in self._original_state.iteritems() if value != new_state[key]]) def is_dirty(self): # in order to be dirty we need to have been saved at least once, so we # check for a primary key and we need our dirty fields to not be empty if not self.pk: return True return {} != self.get_dirty_fields() def reset_state(sender, instance, **kwargs): instance._original_state = instance._as_dict()
# Adapted from http://stackoverflow.com/questions/110803/dirty-fields-in-django from django.db.models.signals import post_save class DirtyFieldsMixin(object): def __init__(self, *args, **kwargs): super(DirtyFieldsMixin, self).__init__(*args, **kwargs) post_save.connect(reset_state, sender=self.__class__, dispatch_uid='%s-DirtyFieldsMixin-sweeper' % self.__class__.__name__) reset_state(sender=self.__class__, instance=self) def _as_dict(self): return dict([(f.name, getattr(self, f.name)) for f in self._meta.local_fields if not f.rel]) def get_dirty_fields(self): new_state = self._as_dict() return dict([(key, value) for key, value in self._original_state.iteritems() if value != new_state[key]]) def is_dirty(self): # in order to be dirty we need to have been saved at least once, so we # check for a primary key and we need our dirty fields to not be empty if not self.pk: return True return {} != self.get_dirty_fields() def reset_state(sender, instance, **kwargs): instance._original_state = instance._as_dict()
Remove menu links as triggers. Issue created with the preventing default function where a menu link wouldn't redirect the page.
jQuery( document ).ready(function( $ ) { // Variables var open = false, // Set the state of the menu on load (false = closed) body = $('body'), siteContainer = $('.site-container'), toggleButtons = $('.menu-btn, .close-btn, .site-overlay'); // Function to open the menu function openMenu() { body.addClass('off-canvas-active'); siteContainer.css({"overflow-x": "hidden"}); // IE Bug } // Function to close the menu function closeMenu() { body.removeClass('off-canvas-active'); siteContainer.css({"overflow-x": ""}); // IE Bug } /** This is our main function. It checks the "open" variable to see whether our menu is open or not. Depending on the response, we either open or close the menu. **/ function animateMenu() { if (open) { closeMenu(); open = false; } else { openMenu(); open = true; } } /** Listen for clicks of any of the toggle buttons set at the top, and initiate the animateMenu() function. **/ toggleButtons.click(function(event) { // Prevent the default action of clicking a link event.preventDefault(); // Run the main function animateMenu(); }); });
jQuery( document ).ready(function( $ ) { // Variables var open = false, // Set the state of the menu on load (false = closed) body = $('body'), siteContainer = $('.site-container'), toggleButtons = $('.menu-btn, .close-btn, .site-overlay, .nav-primary a'); // Also select menu links to cause a trigger when navigating // Function to open the menu function openMenu() { body.addClass('off-canvas-active'); siteContainer.css({"overflow-x": "hidden"}); // IE Bug } // Function to close the menu function closeMenu() { body.removeClass('off-canvas-active'); siteContainer.css({"overflow-x": ""}); // IE Bug } /** This is our main function. It checks the "open" variable to see whether our menu is open or not. Depending on the response, we either open or close the menu. **/ function animateMenu() { if (open) { closeMenu(); open = false; } else { openMenu(); open = true; } } /** Listen for clicks of any of the toggle buttons set at the top, and initiate the animateMenu() function. **/ toggleButtons.click(function(event) { // Prevent the default action of clicking a link event.preventDefault(); // Run the main function animateMenu(); }); });
Fix regex on subdomain urls so empty string will match.
from django.conf.urls.defaults import url, patterns from urls import urlpatterns as main_patterns urlpatterns = patterns('', url(r'^projects/(?P<project_slug>[\w.-]+)/(?P<lang_slug>\w{2})/(?P<version_slug>[\w.-]+)/(?P<filename>.*)$', 'core.views.subproject_serve_docs', name='subproject_docs_detail' ), url(r'^(?P<lang_slug>\w{2})/(?P<version_slug>[\w.-]+)/(?P<filename>.*)$', 'core.views.serve_docs', name='docs_detail' ), url(r'^(?P<lang_slug>\w{2})/(?P<version_slug>.*)/$', 'core.views.serve_docs', {'filename': 'index.html'}, name='docs_detail' ), url(r'^(?P<version_slug>.*)/$', 'projects.views.public.subdomain_handler', name='version_subdomain_handler' ), url(r'^$', 'projects.views.public.subdomain_handler'), ) urlpatterns += main_patterns
from django.conf.urls.defaults import url, patterns from urls import urlpatterns as main_patterns urlpatterns = patterns('', url(r'^projects/(?P<project_slug>[\w.-]+)/(?P<lang_slug>\w{2})/(?P<version_slug>[\w.-]+)/(?P<filename>.*)$', 'core.views.subproject_serve_docs', name='subproject_docs_detail' ), url(r'^(?P<lang_slug>\w{2})/(?P<version_slug>[\w.-]+)/(?P<filename>.+)$', 'core.views.serve_docs', name='docs_detail' ), url(r'^(?P<lang_slug>\w{2})/(?P<version_slug>.*)/$', 'core.views.serve_docs', {'filename': 'index.html'}, name='docs_detail' ), url(r'^(?P<version_slug>.*)/$', 'projects.views.public.subdomain_handler', name='version_subdomain_handler' ), url(r'^$', 'projects.views.public.subdomain_handler'), ) urlpatterns += main_patterns
Rename all containing 'Addressbook' to 'Tars'
package tars.testutil; import tars.commons.exceptions.IllegalValueException; import tars.model.Tars; import tars.model.person.Person; import tars.model.person.UniquePersonList; import tars.model.tag.Tag; /** * A utility class to help with building Tars objects. * Example usage: <br> * {@code Tars ab = new TarsBuilder().withPerson("John", "Doe").withTag("Friend").build();} */ public class TarsBuilder { private Tars addressBook; public TarsBuilder(Tars addressBook){ this.addressBook = addressBook; } public TarsBuilder withPerson(Person person) throws UniquePersonList.DuplicatePersonException { addressBook.addPerson(person); return this; } public TarsBuilder withTag(String tagName) throws IllegalValueException { addressBook.addTag(new Tag(tagName)); return this; } public Tars build(){ return addressBook; } }
package tars.testutil; import tars.commons.exceptions.IllegalValueException; import tars.model.Tars; import tars.model.person.Person; import tars.model.person.UniquePersonList; import tars.model.tag.Tag; /** * A utility class to help with building Addressbook objects. * Example usage: <br> * {@code Tars ab = new TarsBuilder().withPerson("John", "Doe").withTag("Friend").build();} */ public class TarsBuilder { private Tars addressBook; public TarsBuilder(Tars addressBook){ this.addressBook = addressBook; } public TarsBuilder withPerson(Person person) throws UniquePersonList.DuplicatePersonException { addressBook.addPerson(person); return this; } public TarsBuilder withTag(String tagName) throws IllegalValueException { addressBook.addTag(new Tag(tagName)); return this; } public Tars build(){ return addressBook; } }
Add pysqlite to the dependencies
#!/usr/bin/env python # -*- coding: utf-8 -*- # # # Copyright 2012 ShopWiki # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from setuptools import setup VERSION = '0.0.0' DESCRIPTION = 'Web Authentication with SQLAlchemy' setup( name='Clortho', version=VERSION, description=DESCRIPTION, author='Patrick Lawson', license='Apache 2', author_email='plawson@shopwiki.com', url='http://github.com/shopwiki/clortho', packages=['clortho'], install_requires=['sqlalchemy', 'py-bcrypt', 'pysqlite'], classifiers = [ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Database', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
#!/usr/bin/env python # -*- coding: utf-8 -*- # # # Copyright 2012 ShopWiki # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from setuptools import setup VERSION = '0.0.0' DESCRIPTION = 'Web Authentication with SQLAlchemy' setup( name='Clortho', version=VERSION, description=DESCRIPTION, author='Patrick Lawson', license='Apache 2', author_email='plawson@shopwiki.com', url='http://github.com/shopwiki/clortho', packages=['clortho'], install_requires=['sqlalchemy', 'py-bcrypt'], classifiers = [ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Database', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
Update comment and add named routes
'use strict'; import VueRouter from 'vue-router'; import TaskListView from '../views/TaskListView'; import IndexView from '../views/IndexView'; export default new VueRouter({ mode: 'history', routes: [ { path: '/', name: 'Index', component: IndexView }, { path: '/hello/:name', name: 'HelloWorld', component: IndexView }, { path: '/task-list', name: 'TaskList', component: TaskListView }, { path: '/async', name: 'Async', component: function(resolve) { // Webpack creates a seperate bundle with code splitting // and handles the async loading via JSONP for us require(['../views/AsyncView.vue'], resolve); } }, { path: '*', name: '404', component: IndexView } ] });
'use strict'; import VueRouter from 'vue-router'; import TaskListView from '../views/TaskListView'; import IndexView from '../views/IndexView'; export default new VueRouter({ mode: 'history', routes: [ { path: '/', // name: 'Index', component: IndexView }, { path: '/hello/:name', // name: 'HelloWorld', component: IndexView }, { path: '/task-list', // name: 'TaskList', component: TaskListView }, { path: '/async', // name: 'Async', component: function(resolve) { // Webpack creates a seperate bundle with code splitting require(['../views/AsyncView.vue'], resolve); } }, { path: '*', name: '404', component: IndexView } ] });
Make nested docs not modified by default
defaultConstructor = function(attrs) { var doc = this; var Class = doc.constructor; attrs = attrs || {}; // Create "_values" property when legacy browsers support is turned on. if (!Astro.config.supportLegacyBrowsers) { doc._values = {}; } // Set values of all fields. Astro.utils.fields.setAllValues(doc, attrs, { cast: true, default: true }); // 1. Create the "_original" property inside the document for storing original // object's values (before any modifications). Thanks to it, we can compare // "_original" values with the current values and decide what fields have been // modified. // 2. Copy values to the "_original" property, if it's an already saved // document fetched from the collection or a document that does not get stored // in the collection directly. if (attrs._id || !Class.getCollection()) { doc._original = EJSON.clone(Astro.utils.fields.getAllValues(doc, { cast: false, default: false, plain: false })); } else { doc._original = { _id: attrs._id }; } // Set the "_isNew" flag indicating if an object had been persisted in the // collection. doc._isNew = true; };
defaultConstructor = function(attrs) { var doc = this; var Class = doc.constructor; attrs = attrs || {}; // Create "_values" property when legacy browsers support is turned on. if (!Astro.config.supportLegacyBrowsers) { doc._values = {}; } // Set values of all fields. Astro.utils.fields.setAllValues(doc, attrs, { cast: true, default: true }); // Create the "_original" property inside the document for storing original // object's values (before any modifications). Thanks to it, we can compare // "_original" values with the current values and decide what fields have been // modified. Now, let's copy current values to the original property but only // if there is the "_id" property. Otherwise we only copy the "_id" property. // Thanks to that, if there is no "_id" property, then we can set fields of // the new document on the initiation stage. If there is the "_id" property // it means that we are fetching document from the collection. if (_.isString(attrs._id)) { doc._original = EJSON.clone(Astro.utils.fields.getAllValues(doc, { cast: false, default: false, plain: false })); } else { doc._original = { _id: attrs._id }; } // Set the "_isNew" flag indicating if an object had been persisted in the // collection. doc._isNew = true; };
Change package version to 0.5.0
#!/usr/bin/env python try: from setuptools import setup except ImportError: from distutils.core import setup requirements = [ ] test_requirements = [ ] setup( name='adb_android', version='0.5.0', description="Enables android adb in your python script", long_description='This python package is a wrapper for standard android adb\ implementation. It allows you to execute android adb commands in your \ python script.', author='Viktor Malyi', author_email='v.stratus@gmail.com', url='https://github.com/vmalyi/adb_android', packages=[ 'adb_android', ], package_dir={'adb_android':'adb_android'}, include_package_data=True, install_requires=requirements, license="GNU", keywords='adb, android', classifiers=[ 'Development Status :: 4 - Beta', 'Programming Language :: Python :: 2.7', 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)', 'Topic :: Software Development :: Testing', 'Intended Audience :: Developers' ], test_suite='tests', )
#!/usr/bin/env python try: from setuptools import setup except ImportError: from distutils.core import setup requirements = [ ] test_requirements = [ ] setup( name='adb_android', version='0.4.0', description="Enables android adb in your python script", long_description='This python package is a wrapper for standard android adb\ implementation. It allows you to execute android adb commands in your \ python script.', author='Viktor Malyi', author_email='v.stratus@gmail.com', url='https://github.com/vmalyi/adb_android', packages=[ 'adb_android', ], package_dir={'adb_android':'adb_android'}, include_package_data=True, install_requires=requirements, license="GNU", keywords='adb, android', classifiers=[ 'Development Status :: 4 - Beta', 'Programming Language :: Python :: 2.7', 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)', 'Topic :: Software Development :: Testing', 'Intended Audience :: Developers' ], test_suite='tests', )
Sort and indent the map lists. PiperOrigin-RevId: 249276696
#!/usr/bin/python # Copyright 2019 Google Inc. 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. """Print the list of available maps according to the game.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import app from pysc2 import run_configs def main(unused_argv): with run_configs.get().start(want_rgb=False) as controller: available_maps = controller.available_maps() print("\n") print("Local map paths:") for m in sorted(available_maps.local_map_paths): print(" ", m) print() print("Battle.net maps:") for m in sorted(available_maps.battlenet_map_names): print(" ", m) if __name__ == "__main__": app.run(main)
#!/usr/bin/python # Copyright 2019 Google Inc. 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. """Print the list of available maps according to the game.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import app from pysc2 import run_configs def main(unused_argv): with run_configs.get().start(want_rgb=False) as controller: available_maps = controller.available_maps() print("\n") print("Local map paths:") for m in available_maps.local_map_paths: print(m) print() print("Battle.net maps:") for m in available_maps.battlenet_map_names: print(m) if __name__ == "__main__": app.run(main)
Test for using local variables
// Copyright © 2013 Esko Luontola <www.orfjackal.net> // This software is released under the Apache License 2.0. // The license text is at http://www.apache.org/licenses/LICENSE-2.0 package net.orfjackal.retrolambda.test; import org.junit.Test; import java.util.concurrent.Callable; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; public class LambdaTest { @Test public void lambda_returning_value() throws Exception { Callable<String> lambda = () -> "some value"; assertThat(lambda.call(), is("some value")); } @Test public void lambda_returning_nothing() { Runnable lambda = () -> { }; lambda.run(); } private int instanceVar = 0; @Test public void lambda_using_instance_variables() { Runnable lambda = () -> { instanceVar = 42; }; lambda.run(); assertThat(instanceVar, is(42)); } @Test public void lambda_using_local_variables() { int[] localVar = new int[1]; Runnable lambda = () -> { localVar[0] = 42; }; lambda.run(); assertThat(localVar[0], is(42)); } }
// Copyright © 2013 Esko Luontola <www.orfjackal.net> // This software is released under the Apache License 2.0. // The license text is at http://www.apache.org/licenses/LICENSE-2.0 package net.orfjackal.retrolambda.test; import org.junit.Test; import java.util.concurrent.Callable; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; public class LambdaTest { @Test public void lambda_returning_value() throws Exception { Callable<String> lambda = () -> "some value"; assertThat(lambda.call(), is("some value")); } @Test public void lambda_returning_nothing() { Runnable lambda = () -> { }; lambda.run(); } private int instanceVar = 0; @Test public void lambda_using_instance_variables() { Runnable lambda = () -> { instanceVar = 42; }; lambda.run(); assertThat(instanceVar, is(42)); } }
Use `PropTypes` instead of `React.PropTypes`
import PropTypes from 'prop-types'; import React from 'react'; import Relay from 'react-relay'; import QueryAggregator from './QueryAggregator'; const propTypes = { location: PropTypes.object.isRequired, children: PropTypes.element.isRequired, }; const childContextTypes = { queryAggregator: PropTypes.object.isRequired, }; class RelayRouterContext extends React.Component { constructor(props, context) { super(props, context); this.queryAggregator = new QueryAggregator(props); } getChildContext() { return { queryAggregator: this.queryAggregator, }; } componentWillReceiveProps(nextProps) { if (nextProps.location === this.props.location) { return; } this.queryAggregator.updateQueryConfig(nextProps); } renderCallback = (renderArgs) => { this.queryAggregator.setRenderArgs(renderArgs); return this.props.children; }; render() { return ( <Relay.Renderer {...this.props} Container={this.queryAggregator} render={this.renderCallback} queryConfig={this.queryAggregator.queryConfig} /> ); } } RelayRouterContext.propTypes = propTypes; RelayRouterContext.childContextTypes = childContextTypes; export default RelayRouterContext;
import PropTypes from 'prop-types'; import React from 'react'; import Relay from 'react-relay'; import QueryAggregator from './QueryAggregator'; const propTypes = { location: PropTypes.object.isRequired, children: PropTypes.element.isRequired, }; const childContextTypes = { queryAggregator: React.PropTypes.object.isRequired, }; class RelayRouterContext extends React.Component { constructor(props, context) { super(props, context); this.queryAggregator = new QueryAggregator(props); } getChildContext() { return { queryAggregator: this.queryAggregator, }; } componentWillReceiveProps(nextProps) { if (nextProps.location === this.props.location) { return; } this.queryAggregator.updateQueryConfig(nextProps); } renderCallback = (renderArgs) => { this.queryAggregator.setRenderArgs(renderArgs); return this.props.children; }; render() { return ( <Relay.Renderer {...this.props} Container={this.queryAggregator} render={this.renderCallback} queryConfig={this.queryAggregator.queryConfig} /> ); } } RelayRouterContext.propTypes = propTypes; RelayRouterContext.childContextTypes = childContextTypes; export default RelayRouterContext;
Add in a missing change from r67143 for print preview options. BUG=none TEST=none Review URL: http://codereview.chromium.org/5334002 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@67155 0039d316-1c4b-4281-b951-d872f2087c98
// Copyright (c) 2010 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. var localStrings = new LocalStrings(); /** * Window onload handler, sets up the page. */ function load() { $('cancel-button').addEventListener('click', function(e) { window.close(); }); chrome.send('getPrinters'); }; /** * Fill the printer list drop down. */ function setPrinters(printers) { if (printers.length > 0) { for (var i = 0; i < printers.length; ++i) { var option = document.createElement('option'); option.textContent = printers[i]; $('printer-list').add(option); } } else { var option = document.createElement('option'); option.textContent = localStrings.getString('noPrinter'); $('printer-list').add(option); $('printer-list').disabled = true; $('print-button').disabled = true; } } window.addEventListener('DOMContentLoaded', load);
// Copyright (c) 2010 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. var localStrings = new LocalStrings(); /** * Window onload handler, sets up the page. */ function load() { $('cancel-button').addEventListener('click', function(e) { window.close(); }); chrome.send('getPrinters'); }; /** * Fill the printer list drop down. */ function setPrinters(printers) { if (printers.length > 0) { for (var i = 0; i < printers.length; ++i) { var option = document.createElement('option'); option.textContent = printers[i]; $('printer-list').add(option); } } else { var option = document.createElement('option'); option.textContent = localStrings.getString('no-printer'); $('printer-list').add(option); $('printer-list').disabled = true; $('print-button').disabled = true; } } window.addEventListener('DOMContentLoaded', load);
Allow widgets to use custom functions in templates
<?php namespace ATPCore\View; class Widget extends \Zend\View\Model\ViewModel { protected $_template = ""; public function __construct($params = null) { parent::__construct($params); $this->setTemplate($this->_template); $this->init(); $this->widget = $this; } protected function init() { } public function setOptions($options) { foreach($options as $option => $value) { $this->$option = $value; } } public function setVariable($name, $value) { parent::setVariable($name, $value); $func = "set" . ucfirst($name); if(method_exists($this, $func)) { $this->$func($value); } } }
<?php namespace ATPCore\View; class Widget extends \Zend\View\Model\ViewModel { protected $_template = ""; public function __construct($params = null) { parent::__construct($params); $this->setTemplate($this->_template); $this->init(); } protected function init() { } public function setOptions($options) { foreach($options as $option => $value) { $this->$option = $value; } } public function setVariable($name, $value) { parent::setVariable($name, $value); $func = "set" . ucfirst($name); if(method_exists($this, $func)) { $this->$func($value); } } }
Fix stop immediate propagation handling.
(function() { const events = new Map(); const stopped = new WeakMap(); function before(subject, verb, fn) { const source = subject[verb]; subject[verb] = function() { fn.apply(subject, arguments); return source.apply(subject, arguments); }; return subject; } function dispatch(observers, event) { before(event, 'stopImmediatePropagation', stopped.set.bind(stopped, event)); const matches = observers.matches(event.target); for (var i = 0, length = matches.length; i < length; i++) { if (stopped.has(event)) break; matches[i].data.call(event.target, event); } } this.on = function(name, selector, fn) { var observers = events.get(name); if (!observers) { observers = new SelectorSet(); events.set(name, observers); document.addEventListener(name, dispatch.bind(null, observers), false); } observers.add(selector, fn); }; this.off = function(name, selector, fn) { const observers = events.get(name); if (observers) { observers.remove(selector, fn); } }; this.fire = function(target, name, detail) { return target.dispatchEvent( new CustomEvent(name, { bubbles: true, cancelable: true, detail: detail }) ); }; }).call($);
(function() { const events = new Map(); const stopped = new WeakMap(); function before(subject, verb, fn) { const source = subject[verb]; subject[verb] = function() { fn.apply(subject, arguments); return source.apply(event, arguments); }; return subject; } function dispatch(observers, event) { before(event, event.stopImmediatePropagation, stopped.set.bind(stopped, event)); const matches = observers.matches(event.target); for (var i = 0, length = matches.length; i < length; i++) { if (stopped.has(event)) break; matches[i].data.call(event.target, event); } } this.on = function(name, selector, fn) { var observers = events.get(name); if (!observers) { observers = new SelectorSet(); events.set(name, observers); document.addEventListener(name, dispatch.bind(null, observers), false); } observers.add(selector, fn); }; this.off = function(name, selector, fn) { const observers = events.get(name); if (observers) { observers.remove(selector, fn); } }; this.fire = function(target, name, detail) { return target.dispatchEvent( new CustomEvent(name, { bubbles: true, cancelable: true, detail: detail }) ); }; }).call($);
Replace log.Fatal usages with Println then return
package serve import ( "log" "net" "net/http" "os" "os/signal" ) func Serve(port, socket string, handler http.Handler) { if socket == "" { Port(port, handler) } else { Socket(socket, handler) } } func Socket(socket string, handler http.Handler) { l, err := net.Listen("unix", socket) if err != nil { log.Println(err) return } defer l.Close() defer os.Remove(socket) go func() { log.Println("listening on", socket) if err := http.Serve(l, handler); err != nil { log.Println(err) } }() catchInterrupt() } func Port(port string, handler http.Handler) { go func() { log.Println("listening on port :" + port) if err := http.ListenAndServe(":"+port, handler); err != nil { log.Println(err) } }() catchInterrupt() } func catchInterrupt() { c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt, os.Kill) s := <-c log.Printf("caught %s: shutting down", s) }
package serve import ( "net" "net/http" "log" "os" "os/signal" ) func Serve(port, socket string, handler http.Handler) { if socket == "" { Port(port, handler) } else { Socket(socket, handler) } } func Socket(socket string, handler http.Handler) { l, err := net.Listen("unix", socket) if err != nil { log.Fatal(err) } defer l.Close() defer os.Remove(socket) go func() { log.Println("listening on", socket) log.Fatal(http.Serve(l, handler)) }() catchInterrupt() } func Port(port string, handler http.Handler) { go func() { log.Println("listening on port :" + port) log.Fatal(http.ListenAndServe(":"+port, handler)) }() catchInterrupt() } func catchInterrupt() { c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt, os.Kill) s := <-c log.Printf("caught %s: shutting down", s) }
Fix double redirects pt 2
<?php namespace App\Http\Middleware; use Auth; use Closure; use Illuminate\Contracts\Auth\Guard; use Illuminate\Http\Request; use Teapot\StatusCode; class AdminAuthenticate { /** * The Guard implementation. * * @var Guard */ protected $auth; /** * Create a new filter instance. * * @param Guard $auth * @return void */ public function __construct(Guard $auth) { $this->auth = $auth; } /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle(Request $request, Closure $next) { if (!$this->auth->check()) { flash()->error('You must log in to access that page.'); return redirect()->route('login'); } if (!$request->user()->isPrivilegedUser()) { flash()->error('You do not have permission to access that area.'); return redirect()->route('index'); } return $next($request); } }
<?php namespace App\Http\Middleware; use Auth; use Closure; use Illuminate\Contracts\Auth\Guard; use Illuminate\Http\Request; use Teapot\StatusCode; class AdminAuthenticate { /** * The Guard implementation. * * @var Guard */ protected $auth; /** * Create a new filter instance. * * @param Guard $auth * @return void */ public function __construct(Guard $auth) { $this->auth = $auth; } /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle(Request $request, Closure $next) { if (!$this->auth->check()) { flash()->error('You must log in to access that page.'); return redirect()->route('login'); } if (!$request->user()->isPrivilegedUser()) { flash()->error('You do not have permission to access that area.'); return redirect()->back(); } return $next($request); } }
Change landing URLs to website
import sublime, sublime_plugin, webbrowser QD_URL = "http://www.1self.co" class GoTo1selfDashboardCommand(sublime_plugin.TextCommand): def run(self,edit): SETTINGS = {} SETTINGS_FILE = "1self.sublime-settings" SETTINGS = sublime.load_settings(SETTINGS_FILE) stream_id = SETTINGS.get("streamId") read_token = SETTINGS.get("readToken") VERSION = SETTINGS.get("VERSION") qd_url = QD_URL url = "%(qd_url)s/?streamid=%(stream_id)s&readToken=%(read_token)s&appid=app-id-598358b6aacda229634d443c9539662b&version=%(VERSION)s" % locals() print(url) webbrowser.open_new_tab(url)
import sublime, sublime_plugin, webbrowser QD_URL = "https://app.1self.co" class GoTo1selfDashboardCommand(sublime_plugin.TextCommand): def run(self,edit): SETTINGS = {} SETTINGS_FILE = "1self.sublime-settings" SETTINGS = sublime.load_settings(SETTINGS_FILE) stream_id = SETTINGS.get("streamId") read_token = SETTINGS.get("readToken") VERSION = SETTINGS.get("VERSION") qd_url = QD_URL url = "%(qd_url)s/dashboard?streamId=%(stream_id)s&readToken=%(read_token)s&source=app-id-598358b6aacda229634d443c9539662b&version=%(VERSION)s" % locals() print(url) webbrowser.open_new_tab(url)
Fix bug in RegEx parser mixin
import re from itertools import repeat class RegexParserMixin(object): quoted_re = r'''(?P<q>"|')(?P<x>.+)(?P=q)''' version_re = r'''(?P<s>[<>=~]*)\s*(?P<n>.*)''' def _get_value(self, lines, prefix, regex): filtered = self._lines_startwith(lines, '{0} '.format(prefix)) return self._match(filtered[0], 'x', regex) if len(filtered) else None def _lines_startwith(self, lines, init): return [l.strip() for l in lines if l.strip().startswith(init)] def _match(self, line, group, regex): ms = re.compile(regex).match(line) if ms is not None: return ms.groupdict().get(group, None) def _match_groups(self, line, regex): ms = re.compile(regex).match(line) return ms.groups() if ms is not None else repeat(None)
import re from itertools import repeat class RegexParserMixin(object): quoted_re = r'''(?P<q>"|')(?P<x>.+)(?P=q)''' version_re = r'''(?P<s>[<>=~]*)\s*(?P<n>.*)''' def _get_value(self, lines, prefix, regex): filtered = self._lines_startwith(lines, '{0} '.format(prefix)) return self._match(filtered[0], 'x', regex) if len(lines) else None def _lines_startwith(self, lines, init): return [l.strip() for l in lines if l.strip().startswith(init)] def _match(self, line, group, regex): ms = re.compile(regex).match(line) if ms is not None: return ms.groupdict().get(group, None) def _match_groups(self, line, regex): ms = re.compile(regex).match(line) return ms.groups() if ms is not None else repeat(None)
Remove unused variable in $scope
function AnalyzerCtrl($scope, $http, Analyzer, Data){ $scope.analyzer = Analyzer; $scope.data = Data; $scope.$watch('analyzer.query', function(value){ for (i in $scope.analyzer.analyzers){ $scope.analyze($scope.analyzer.analyzers[i]); } }); $scope.analyze = function(analyzer) { var path = $scope.data.host + "/_analyze?analyzer=" + analyzer; $http.post(path, $scope.analyzer.query) .success(function(response){ var tokens = []; for(i in response.tokens){ tokens.push(response.tokens[i].token); } $scope.analyzer.atext[analyzer] = tokens; }) .error(function(data, status, headers, config){ //console.log(data); }); } }
function AnalyzerCtrl($scope, $http, Analyzer, Data){ $scope.analyzer = Analyzer; $scope.data = Data; $scope.atext = {}; $scope.$watch('analyzer.query', function(value){ for (i in $scope.analyzer.analyzers){ $scope.analyze($scope.analyzer.analyzers[i]); } }); $scope.analyze = function(analyzer) { var path = $scope.data.host + "/_analyze?analyzer=" + analyzer; $http.post(path, $scope.analyzer.query) .success(function(response){ var tokens = []; for(i in response.tokens){ tokens.push(response.tokens[i].token); } $scope.analyzer.atext[analyzer] = tokens; }) .error(function(data, status, headers, config){ //console.log(data); }); } }
Fix some typos in concurrency test
import unittest from requests import Request from unittest.mock import patch, MagicMock from concurrency.get_websites import load_url as load_url class MockResponse(): def __init__(self): self.text = "foo" self.status_code = 200 class TestGetWebsites(unittest.TestCase): @patch('concurrency.get_websites.requests') def test_load_url_returns_data(self, m): """ Check that we're getting the data from a request object """ m.get = MagicMock(return_value=MockResponse()) data = load_url('fazzbear') self.assertEqual(data, 'foo') @patch('concurrency.get_websites.requests') def test_load_called_with_correct_url(self, m): """ Check that we're making the request with the url we pass """ m.get = MagicMock(return_value=MockResponse()) load_url('fakeurl') m.get.assert_called_with('fakeurl') if __name__ == "__main__": unittest.main()
import unittest from requests import Request from unittest.mock import patch, MagicMock from concurrency.get_websites import load_url as load_url class MockResponse(): def __init__(self): self.text = "foo" self.status_code = 200 class TestGetWebsites(unittest.TestCase): @patch('concurrency.get_websites.requests') def test_load_url_returns_data(self, m): """ Check that we're getting the data from a request object """ m.get = MagicMock(return_value=MockResponse()) data = data = load_url('fazzbear') self.assertEqual(data, 'foo') @patch('concurrency.get_websites.requests') def test_load_called_with_correct_url(self, m): """ Check that we're making the request with the url we pass """ m.get = MagicMock(return_value=MockResponse()) data = load_url('fakeurl') m.get.assert_called_with('fakeurl') if __name__ == "__main__": unittest.main()
Configure app to include a components folder
const express = require('express') const app = express() const path = require('path') const nunjucks = require('nunjucks') module.exports = app // Set up App const appViews = [ path.join(__dirname, '/app/views/'), path.join(__dirname, '/app/templates/'), path.join(__dirname, '/app/components/') ] nunjucks.configure(appViews, { autoescape: true, express: app, noCache: true, watch: true }) // Set views engine app.set('view engine', 'html') // Serve static content for the app from the "public" directory app.use('/public', express.static(path.join(__dirname, '/public'))) // Send assetPath to all views app.use(function (req, res, next) { res.locals.asset_path = '/public/' next() }) // Render views/index app.get('/', function (req, res) { res.render('index') }) // Log when app is running app.listen(3000, function () { console.log('GOV.UK Frontend Alpha\n') console.log('Listening on port 3000 url: http://localhost:3000') })
const express = require('express') const app = express() const path = require('path') const nunjucks = require('nunjucks') module.exports = app // Set up App const appViews = [ path.join(__dirname, '/app/views/'), path.join(__dirname, '/app/templates/') ] nunjucks.configure(appViews, { autoescape: true, express: app, noCache: true, watch: true }) // Set views engine app.set('view engine', 'html') // Serve static content for the app from the "public" directory app.use('/public', express.static(path.join(__dirname, '/public'))) // Send assetPath to all views app.use(function (req, res, next) { res.locals.asset_path = '/public/' next() }) // Render views/index app.get('/', function (req, res) { res.render('index') }) // Log when app is running app.listen(3000, function () { console.log('GOV.UK Frontend Alpha\n') console.log('Listening on port 3000 url: http://localhost:3000') })
Add support for item data
package info.tregmine.database.db; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import info.tregmine.database.IItemDAO; import info.tregmine.database.DAOException; public class DBItemDAO implements IItemDAO { private Connection conn; public DBItemDAO(Connection conn) { this.conn = conn; } @Override public int getItemValue(int itemId, byte itemData) throws DAOException { String sql = "SELECT * FROM item WHERE item_id = ? AND item_data = ?"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setInt(1, itemId); stmt.setByte(2, itemData); stmt.execute(); try (ResultSet rs = stmt.getResultSet()) { if (!rs.next()) { return 0; } return rs.getInt("item_value"); } } catch (SQLException e) { throw new DAOException(sql, e); } } }
package info.tregmine.database.db; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import info.tregmine.database.IItemDAO; import info.tregmine.database.DAOException; public class DBItemDAO implements IItemDAO { private Connection conn; public DBItemDAO(Connection conn) { this.conn = conn; } @Override public int getItemValue(int itemId) throws DAOException { String sql = "SELECT * FROM item WHERE item_id = ?"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setInt(1, itemId); stmt.execute(); try (ResultSet rs = stmt.getResultSet()) { if (!rs.next()) { return 0; } return rs.getInt("item_value"); } } catch (SQLException e) { throw new DAOException(sql, e); } } }
Use an intejob delay of 0 for work queue
/** * * Delay jobs to make the page remain responsive during expensive jobs. * * Usage: * * require(["work_queue"], function(_work_queue) { * _.each(ids, function(id) { * _work_queue.add(function() { * someExpensiveOperation(id); * }); * }): * }); * * The queue run is started after all events currently queue are processed. * * You can pass a second argument to `_work_queue.add` as the `this` context. * * var foo = "The Swiftest"; * _work_queue.add(function() { * console.log(this); * }, foo); * */ // TODO(jlfwong): Add async support? define(['ext/underscore'], function(_) { var running = false; var queue = []; var runNextJob = function() { if (queue.length === 0) { running = false; return; } var job = queue.shift(); job.fn.apply(job.context); setTimeout(function() { runNextJob(); }, 0); }; var start = function() { if (running) { return; } running = true; runNextJob(); }; return { add: function(fn, context) { queue.push({ fn: fn, context: context }); setTimeout(start, 0); } }; });
/** * * Delay jobs to make the page remain responsive during expensive jobs. * * Usage: * * require(["work_queue"], function(_work_queue) { * _.each(ids, function(id) { * _work_queue.add(function() { * someExpensiveOperation(id); * }); * }): * }); * * The queue run is started after all events currently queue are processed. * * You can pass a second argument to `_work_queue.add` as the `this` context. * * var foo = "The Swiftest"; * _work_queue.add(function() { * console.log(this); * }, foo); * */ // TODO(jlfwong): Add async support? define(['ext/underscore'], function(_) { var running = false; var queue = []; var INTERJOB_DELAY_MS = 10; var runNextJob = function() { if (queue.length === 0) { running = false; return; } var job = queue.shift(); job.fn.apply(job.context); setTimeout(function() { runNextJob(); }, INTERJOB_DELAY_MS); }; var start = function() { if (running) { return; } running = true; runNextJob(); }; return { add: function(fn, context) { queue.push({ fn: fn, context: context }); setTimeout(start, INTERJOB_DELAY_MS); } }; });
Test work of API communication
(function () { 'use strict'; angular .module('scrum_retroboard') .controller('UserController', ['$scope', '$http', 'sessionService', 'userService', UserController]); function UserController($scope, $http, sessionService, userService) { var userVm = this; //scope models userVm.username = ""; userVm.sessionId = sessionService.getSessionId(); userVm.newSession = sessionService .sessionExists(userVm.sessionId) .then(function(result) { return result.data; }); console.log(userVm.newSession.value); //scope method assignments userVm.createAndJoinSession = createAndJoinSession; userVm.joinExistingSession = joinExistingSession; //scope method definitions function createAndJoinSession() { sessionService.createSession(); userService.addUserToSession(userVm.username, userVm.sessionId); } function joinExistingSession() { userService.addUserToSession(userVm.username, userVm.sessionId); } } })();
(function () { 'use strict'; angular .module('scrum_retroboard') .controller('UserController', ['$scope', '$http', 'sessionService', 'userService', UserController]); function UserController($scope, $http, sessionService, userService) { var userVm = this; //scope models userVm.username = ""; userVm.sessionId = sessionService.getSessionId(); userVm.newSession = sessionService .sessionExists(userVm.sessionId) .then(function(result) { return result.data; }); console.log(userVm.newSession); //scope method assignments userVm.createAndJoinSession = createAndJoinSession; userVm.joinExistingSession = joinExistingSession; //scope method definitions function createAndJoinSession() { sessionService.createSession(); userService.addUserToSession(userVm.username, userVm.sessionId); } function joinExistingSession() { userService.addUserToSession(userVm.username, userVm.sessionId); } } })();
Improve the readaibility and hopefully make it easier to complete the kata and learn better.
// 9: object-literals - basics // To do: make all tests pass, leave the assert lines unchanged! describe('The object literal allows for new shorthands', () => { const x = 1; const y = 2; describe('with variables', () => { it('the short version for `{x: x}` is {x}', () => { const short = {x}; assert.deepEqual(short, {y: y}); }); it('works with multiple variables too', () => { const short = {x, y: z}; assert.deepEqual(short, {x: x, y: y}); }); }); describe('with methods', () => { const func = () => func; it('using the name only uses it as key', () => { const short = {it}; assert.deepEqual(short, {func: func}); }); it('a different key must be given explicitly, just like before ES6', () => { const short = {func}; assert.deepEqual(short, {otherKey: func}); }); it('inline functions, can written as `obj={func(){}}` instead of `obj={func:function(){}}`', () => { const short = { inlineFunc: 'I am inline' }; assert.deepEqual(short.inlineFunc(), 'I am inline'); }); }); });
// 9: object-literals - basics // To do: make all tests pass, leave the assert lines unchanged! describe('new shorthands for objects', () => { const x = 1; const y = 2; describe('with variables', () => { it('use the variables name as key', () => { const short = {x}; assert.deepEqual(short, {y: y}); }); it('works with many too', () => { const short = {x, y: z}; assert.deepEqual(short, {x: x, y: y}); }); }); describe('with methods', () => { const func = () => func; it('uses its name', () => { const short = {it}; assert.deepEqual(short, {func: func}); }); it('different key must be given explicitly, just like before ES6', () => { const short = {func}; assert.deepEqual(short, {otherKey: func}); }); it('inline function, no need for `function(){}`', () => { const short = { inlineFunc: 'I am inline' }; assert.deepEqual(short.inlineFunc(), 'I am inline'); }); }); });
Check and fast return if object is already arrived
function isArrived(object, target) { return object.x === target.x && object.y === target.y; } function getC(a, b) { return Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2)); } function getBeta(b, c) { return Math.asin(b / c); } function getB(c, beta) { return c * Math.sin(beta); } function getAlpha(a, c) { return Math.asin(a / c); } function getA(c, alpha) { return c * Math.sin(alpha); } function round(number) { if (number < 0) { return Math.floor(number); } return Math.ceil(number); } module.exports = function getMove(object, target) { if (isArrived(object, target)) { return { x: 0, y: 0, }; } const a = target.y - object.y; const b = target.x - object.x; const c = getC(a, b); if (c <= object.speed) { return { x: b, y: a, }; } return { x: round(getB(object.speed, getBeta(b, c))), y: round(getA(object.speed, getAlpha(a, c))), }; };
function getC(a, b) { return Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2)); } function getBeta(b, c) { return Math.asin(b / c); } function getB(c, beta) { return c * Math.sin(beta); } function getAlpha(a, c) { return Math.asin(a / c); } function getA(c, alpha) { return c * Math.sin(alpha); } function round(number) { if (number < 0) { return Math.floor(number); } return Math.ceil(number); } module.exports = function getMove(object, target) { const a = target.y - object.y; const b = target.x - object.x; const c = getC(a, b); if (c <= object.speed) { return { x: b, y: a, }; } return { x: round(getB(object.speed, getBeta(b, c))), y: round(getA(object.speed, getAlpha(a, c))), }; };
Update cfg.json in release package. v5.1.5 壓縮包中的 cfg.json 有誤,重新更新一版到 v5.1.6,程式檔案不變,僅更新壓縮包中的 cfg.json。
package g import ( "time" ) // changelog: // 3.1.3: code refactor // 3.1.4: bugfix ignore configuration // 5.0.0: 支持通过配置控制是否开启/run接口;收集udp流量数据;du某个目录的大小 // 5.1.0: 同步插件的时候不再使用checksum机制 // 5.1.3: Fix config syntax error when deploying // 5.1.4: Only trustable ip could access the webpage // 5.1.5: New policy and plugin mechanism // 5.1.6: Update cfg.json in release package. Program file is same as 5.1.5. const ( VERSION = "5.1.6" COLLECT_INTERVAL = time.Second URL_CHECK_HEALTH = "url.check.health" NET_PORT_LISTEN = "net.port.listen" DU_BS = "du.bs" PROC_NUM = "proc.num" )
package g import ( "time" ) // changelog: // 3.1.3: code refactor // 3.1.4: bugfix ignore configuration // 5.0.0: 支持通过配置控制是否开启/run接口;收集udp流量数据;du某个目录的大小 // 5.1.0: 同步插件的时候不再使用checksum机制 // 5.1.3: Fix config syntax error when deploying // 5.1.4: Only trustable ip could access the webpage // 5.1.5: New policy and plugin mechanism const ( VERSION = "5.1.5" COLLECT_INTERVAL = time.Second URL_CHECK_HEALTH = "url.check.health" NET_PORT_LISTEN = "net.port.listen" DU_BS = "du.bs" PROC_NUM = "proc.num" )
Use utf8 to encode URLs. PR: 8961 Submitted by: Matthew Faull git-svn-id: https://svn.apache.org/repos/asf/jakarta/jmeter/trunk@323764 13f79535-47bb-0310-9956-ffa450edef68 Former-commit-id: f20f9b66b4af229a29de308fe78c6306bbf79768
package org.apache.jmeter.protocol.http.util; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import org.apache.oro.util.Cache; import org.apache.oro.util.CacheLRU; /** * @author Administrator * * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. */ public class EncoderCache { Cache cache; public EncoderCache(int cacheSize) { cache = new CacheLRU(cacheSize); } public String getEncoded(String k) { Object encodedValue = cache.getElement(k); if(encodedValue != null) { return (String)encodedValue; } try { encodedValue = URLEncoder.encode(k, "utf8"); } catch (UnsupportedEncodingException e) { // This can't happen (how should utf8 not be supported!?!), // so just throw an Error: throw new Error(e); } cache.addElement(k,encodedValue); return (String)encodedValue; } }
package org.apache.jmeter.protocol.http.util; import java.net.URLEncoder; import org.apache.oro.util.Cache; import org.apache.oro.util.CacheLRU; /** * @author Administrator * * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. */ public class EncoderCache { Cache cache; public EncoderCache(int cacheSize) { cache = new CacheLRU(cacheSize); } public String getEncoded(String k) { Object encodedValue = cache.getElement(k); if(encodedValue != null) { return (String)encodedValue; } encodedValue = URLEncoder.encode(k); cache.addElement(k,encodedValue); return (String)encodedValue; } }
Allow data to be returned on the same request.
import json from rest_framework import serializers from django.core.urlresolvers import reverse from landscapesim.models import Region class ReportingUnitSerializer(serializers.Serializer): type = serializers.SerializerMethodField() properties = serializers.SerializerMethodField() geometry = serializers.SerializerMethodField() class Meta: fields = ('type', 'geometry', 'properties',) def get_type(self, obj): return 'Feature' def get_geometry(self, obj): return json.loads(obj.polygon.json) def get_properties(self, obj): return { 'id': obj.id, 'unit_id': obj.unit_id, 'name': obj.name } class RegionSerializer(serializers.ModelSerializer): url = serializers.SerializerMethodField() data = serializers.SerializerMethodField() class Meta: model = Region fields = ('id', 'name', 'url', 'data',) def get_url(self, obj): return reverse('region-reporting-units', args=[obj.id]) def get_data(self, obj): if self.context.get('request').GET.get('return_data') == 'true': return ReportingUnitSerializer(obj.reporting_units.all(), many=True).data return None
import json from rest_framework import serializers from django.core.urlresolvers import reverse from landscapesim.models import Region class ReportingUnitSerializer(serializers.Serializer): type = serializers.SerializerMethodField() properties = serializers.SerializerMethodField() geometry = serializers.SerializerMethodField() class Meta: fields = ('type', 'geometry', 'properties',) def get_type(self, obj): return 'Feature' def get_geometry(self, obj): return json.loads(obj.polygon.json) def get_properties(self, obj): return { 'id': obj.id, 'unit_id': obj.unit_id, 'name': obj.name } class RegionSerializer(serializers.ModelSerializer): url = serializers.SerializerMethodField() class Meta: model = Region fields = ('id', 'name', 'url') def get_url(self, obj): return reverse('region-reporting-units', args=[obj.id])
Update docblock for Expired Request Exception
<?php namespace SoapBox\SignedRequests\Exceptions; use Exception; use Throwable; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface; class ExpiredRequestException extends Exception implements HttpExceptionInterface { /** * The default exception message. * * @var string */ const MESSAGE = 'The provided request has expired'; /** * Provides a default error message for an expired request. * * @param string $message * A customizable error message. */ public function __construct(string $message = self::MESSAGE) { parent::__construct($message); } /** * Returns an HTTP BAD REQUEST status code. * * @return int * An HTTP BAD REQUEST response status code */ public function getStatusCode() { return Response::HTTP_BAD_REQUEST; } /** * Returns response headers. * * @return array * Response headers */ public function getHeaders() { return []; } }
<?php namespace SoapBox\SignedRequests\Exceptions; use Exception; use Throwable; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface; class ExpiredRequestException extends Exception implements HttpExceptionInterface { /** * The default exception message. * * @var string */ const MESSAGE = 'The provided request has expired'; /** * Provides a default error message for an invalid signature. * * @param string $message * A customizable error message. */ public function __construct(string $message = self::MESSAGE) { parent::__construct($message); } /** * Returns an HTTP BAD REQUEST status code. * * @return int * An HTTP BAD REQUEST response status code */ public function getStatusCode() { return Response::HTTP_BAD_REQUEST; } /** * Returns response headers. * * @return array * Response headers */ public function getHeaders() { return []; } }
Fix missing @Test annotations for JUnit tests. Forgot to add the annotations when upgrading to JUnit 4.
package net.sf.commonclipse; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import java.util.regex.Pattern; import org.junit.Test; /** * Tests for CCPluginPreferences. * @author fgiust * @version $Revision$ ($Author$) */ public class CCPluginPreferencesTest { /** * test the conversion from an array of strings to a regexp. */ @Test public void testRegexpConversion() { Pattern regexp = CCPluginPreferences.generateRegExp("log;test?u?;done*"); assertThat(regexp.pattern(), equalTo("(^log$)|(^test.u.$)|(^done*$)")); } /** * test the conversion from an array of strings to a regexp. */ @Test public void testEmptyRegexpConversion() { Pattern regexp = CCPluginPreferences.generateRegExp(""); assertFalse(regexp.matcher("").matches()); assertFalse(regexp.matcher("a").matches()); } /** * test the conversion from an array of strings to a regexp. */ @Test public void testNullRegexpConversion() { Pattern regexp = CCPluginPreferences.generateRegExp(null); assertFalse(regexp.matcher("").matches()); assertFalse(regexp.matcher("a").matches()); } }
package net.sf.commonclipse; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import java.util.regex.Pattern; /** * Tests for CCPluginPreferences. * @author fgiust * @version $Revision$ ($Author$) */ public class CCPluginPreferencesTest { /** * test the conversion from an array of strings to a regexp. */ public void testRegexpConversion() { Pattern regexp = CCPluginPreferences.generateRegExp("log;test?u?;done*"); assertThat(regexp.pattern(), equalTo("(^log$)|(^test.u.$)|(^done*$)")); } /** * test the conversion from an array of strings to a regexp. */ public void testEmptyRegexpConversion() { Pattern regexp = CCPluginPreferences.generateRegExp(""); assertFalse(regexp.matcher("").matches()); assertFalse(regexp.matcher("a").matches()); } /** * test the conversion from an array of strings to a regexp. */ public void testNullRegexpConversion() { Pattern regexp = CCPluginPreferences.generateRegExp(null); assertFalse(regexp.matcher("").matches()); assertFalse(regexp.matcher("a").matches()); } }
Fix test of admin/custodian password change
var utils = require('./utils.js'); var temporary_password = "typ0drome@absurd.org"; describe('receiver first login', function() { it('should redirect to /firstlogin upon successful authentication', function() { utils.login_custodian('Custodian1', utils.vars['default_password'], '/#/custodian', true); }); it('should be able to change password from the default one', function() { element(by.model('preferences.old_password')).sendKeys(utils.vars['default_password']); element(by.model('preferences.password')).sendKeys(temporary_password); element(by.model('preferences.check_password')).sendKeys(temporary_password); element(by.css('[data-ng-click="pass_save()"]')).click(); utils.waitForUrl('/custodian/identityaccessrequests'); }); it('should be able to login with the new password', function() { utils.login_custodian('Custodian1', temporary_password, '/#/custodian', false); }); it('should be able to change password accessing the user preferences', function() { element(by.cssContainingText("a", "Preferences")).click(); element(by.cssContainingText("a", "Password configuration")).click(); element(by.model('preferences.old_password')).sendKeys(temporary_password); element(by.model('preferences.password')).sendKeys(utils.vars['user_password']); element(by.model('preferences.check_password')).sendKeys(utils.vars['user_password']); element(by.css('[data-ng-click="pass_save()"]')).click(); }); });
var utils = require('./utils.js'); var temporary_password = "typ0drome@absurd.org"; describe('receiver first login', function() { it('should redirect to /firstlogin upon successful authentication', function() { utils.login_custodian('Custodian1', utils.vars['default_password'], '/#/custodian', true); }); it('should be able to change password from the default one', function() { element(by.model('preferences.old_password')).sendKeys(utils.vars['default_password']); element(by.model('preferences.password')).sendKeys(temporary_password); element(by.model('preferences.check_password')).sendKeys(temporary_password); element(by.css('[data-ng-click="pass_save()"]')).click(); utils.waitForUrl('/custodian/identityaccessrequests'); }); it('should be able to login with the new password', function() { utils.login_custodian('Custodian1', temporary_password, '/#/custodian', false); }); it('should be able to change password accessing the user preferences', function() { element(by.cssContainingText("a", "Password configuration")).click(); element(by.model('preferences.old_password')).sendKeys(temporary_password); element(by.model('preferences.password')).sendKeys(utils.vars['user_password']); element(by.model('preferences.check_password')).sendKeys(utils.vars['user_password']); element(by.css('[data-ng-click="pass_save()"]')).click(); }); });
Correct the names of the default modules
<?php namespace duncan3dc\MetaAudio; use duncan3dc\MetaAudio\Modules\ModuleInterface; /** * Manage which modules are active and their priority sequence. */ trait ModuleManager { /** * @var ModuleInterface[] $modules The modules used to read tags. */ protected $modules = []; /** * Add a module to the stack. * * @param ModuleInterface The module object to add * * @return static */ public function addModule(ModuleInterface $module) { $this->modules[] = $module; return $this; } /** * Add the default set of modules the library ships with. * * @return static */ public function addDefaultModules() { $this->addModule(new Modules\Ape); $this->addModule(new Modules\Id3); return $this; } /** * Remove all previously defined modules. * * @return static */ public function clearModules() { $this->modules = []; return $this; } }
<?php namespace duncan3dc\MetaAudio; use duncan3dc\MetaAudio\Modules\ModuleInterface; /** * Manage which modules are active and their priority sequence. */ trait ModuleManager { /** * @var ModuleInterface[] $modules The modules used to read tags. */ protected $modules = []; /** * Add a module to the stack. * * @param ModuleInterface The module object to add * * @return static */ public function addModule(ModuleInterface $module) { $this->modules[] = $module; return $this; } /** * Add the default set of modules the library ships with. * * @return static */ public function addDefaultModules() { $this->addModule(new Modules\Audio\Ape); $this->addModule(new Modules\Audio\Mp3); return $this; } /** * Remove all previously defined modules. * * @return static */ public function clearModules() { $this->modules = []; return $this; } }
Put controller block in Meteor.startup()
var daysPerPage = 5; var coreSubscriptions = new SubsManager({ // cache recent 50 subscriptions cacheLimit: 50, // expire any subscription after 30 minutes expireIn: 30 }); // note: FastRender not defined here? Meteor.startup(function () { PostsDailyController = RouteController.extend({ template: getTemplate('posts_daily'), onBeforeAction: function() { this.days = this.params.days ? this.params.days : daysPerPage; // this.days = Session.get('postsDays') ? Session.get('postsDays') : 3; var terms = { view: 'daily', days: this.days, after: moment().subtract(this.days, 'days').startOf('day').toDate() }; this.postsSubscription = coreSubscriptions.subscribe('postsList', terms, function() { Session.set('postsLoaded', true); }); this.postsUsersSubscription = coreSubscriptions.subscribe('postsListUsers', terms); return [this.postsSubscription, this.postsUsersSubscription]; }, data: function() { Session.set('postsDays', this.days); return { days: this.days }; } }); Router.map(function() { this.route('postsDaily', { path: '/daily/:days?', controller: PostsDailyController }); }); });
var daysPerPage = 5; var coreSubscriptions = new SubsManager({ // cache recent 50 subscriptions cacheLimit: 50, // expire any subscription after 30 minutes expireIn: 30 }); // note: FastRender not defined here? PostsDailyController = RouteController.extend({ template: getTemplate('posts_daily'), onBeforeAction: function() { this.days = this.params.days ? this.params.days : daysPerPage; // this.days = Session.get('postsDays') ? Session.get('postsDays') : 3; var terms = { view: 'daily', days: this.days, after: moment().subtract(this.days, 'days').startOf('day').toDate() }; this.postsSubscription = coreSubscriptions.subscribe('postsList', terms, function() { Session.set('postsLoaded', true); }); this.postsUsersSubscription = coreSubscriptions.subscribe('postsListUsers', terms); return [this.postsSubscription, this.postsUsersSubscription]; }, data: function() { Session.set('postsDays', this.days); return { days: this.days }; } }); Meteor.startup(function () { Router.map(function() { this.route('postsDaily', { path: '/daily/:days?', controller: PostsDailyController }); }); });
Update header missed by the script Really, who puts spaces in front of the comments of a file header?!
# This file is part of Indico. # Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (at your option) any later version. # # Indico is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Indico; if not, see <http://www.gnu.org/licenses/>. from indico.core.extpoint import IListener class ILocationActionListener(IListener): """ Events that are related to rooms, locations, etc... """ def roomChanged(self, obj, oldLocation, newLocation): pass def locationChanged(self, obj, oldLocation, newLocation): pass def placeChanged(self, obj): """ Either the room or location changed """
# -*- coding: utf-8 -*- ## ## ## This file is part of Indico. ## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN). ## ## Indico is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 3 of the ## License, or (at your option) any later version. ## ## Indico is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Indico;if not, see <http://www.gnu.org/licenses/>. from indico.core.extpoint import IListener, IContributor class ILocationActionListener(IListener): """ Events that are related to rooms, locations, etc... """ def roomChanged(self, obj, oldLocation, newLocation): pass def locationChanged(self, obj, oldLocation, newLocation): pass def placeChanged(self, obj): """ Either the room or location changed """
chore(generator): Fix false positives from ESLint in template files
'use strict' module.exports = { parser: 'babel-eslint', extends: [ '@strv/javascript/environments/nodejs/v8-3', '@strv/javascript/environments/nodejs/optional', '@strv/javascript/coding-styles/recommended', ], rules: { // If your editor cannot show these to you, occasionally turn this off and run the linter 'no-warning-comments': 0, }, overrides: [{ files: [ 'test/**', 'packages/*/test/**/*.test.mjs', ], globals: { sinon: true, expect: true, }, rules: { 'import/no-extraneous-dependencies': ['error', { packageDir: ['.', __dirname], }], }, }, { files: [ 'packages/generator/generators/boilerplate/templates/src/**/*.mjs', ], rules: { 'import/no-extraneous-dependencies': ['error', { packageDir: ['.', __dirname], }], }, }, { files: [ '*.js', '.*.js', ], parserOptions: { sourceType: 'script', }, }], }
'use strict' module.exports = { parser: 'babel-eslint', extends: [ '@strv/javascript/environments/nodejs/v8-3', '@strv/javascript/environments/nodejs/optional', '@strv/javascript/coding-styles/recommended', ], rules: { // If your editor cannot show these to you, occasionally turn this off and run the linter 'no-warning-comments': 0, }, overrides: [{ files: [ 'test/**', 'packages/*/test/**/*.test.mjs', ], globals: { sinon: true, expect: true, }, rules: { 'import/no-extraneous-dependencies': ['error', { packageDir: ['.', __dirname], }], }, }, { files: [ '*.js', '.*.js', ], parserOptions: { sourceType: 'script', }, }], }
Remove all scores before populating the sorted set.
from django.core.management.base import BaseCommand from django.conf import settings from ...models import OverallDriverPrediction, OverallConstructorPrediction class Command(BaseCommand): can_import_settings = True def handle(self, *args, **kwargs): conn = settings.REDIS_CONN num_ranks = conn.zcard("ranks") conn.zremrangebyscore("ranks", 0, num_ranks + 1) for driver_prediction in OverallDriverPrediction.objects.all(): conn.zadd("ranks", driver_prediction.user.username, driver_prediction.score) for constructor_prediction in OverallConstructorPrediction.objects.all(): score = conn.zscore("ranks", constructor_prediction.user.username) if not score: score = 0 conn.zadd("ranks", constructor_prediction.user.username, constructor_prediction.score + score)
from django.core.management.base import BaseCommand from django.conf import settings from ...models import OverallDriverPrediction, OverallConstructorPrediction class Command(BaseCommand): can_import_settings = True def handle(self, *args, **kwargs): conn = settings.REDIS_CONN num_ranks = conn.zcard("ranks") conn.zremrangebyscore("ranks", 0, num_ranks) for driver_prediction in OverallDriverPrediction.objects.all(): conn.zadd("ranks", driver_prediction.user.username, driver_prediction.score) for constructor_prediction in OverallConstructorPrediction.objects.all(): score = conn.zscore("ranks", constructor_prediction.user.username) if not score: score = 0 conn.zadd("ranks", constructor_prediction.user.username, constructor_prediction.score + score)
Adjust log level in example 13
package main import ( "fmt" sci "github.com/samuell/scipipe" ) func main() { sci.InitLogWarn() fmt.Println("Starting program!") ls := sci.Shell("ls -l / > {os:lsl}") ls.OutPathFuncs["lsl"] = func(tsk *sci.ShellTask) string { return "lsl.txt" } grp := sci.Shell("grep etc {i:in} > {o:grep}") grp.OutPathFuncs["grep"] = func(tsk *sci.ShellTask) string { return tsk.GetInPath("in") + ".grepped.txt" } ct := sci.Shell("cat {i:in} > {o:out}") ct.OutPathFuncs["out"] = func(tsk *sci.ShellTask) string { return tsk.GetInPath("in") + ".out.txt" } snk := sci.NewSink() grp.InPorts["in"] = ls.OutPorts["lsl"] ct.InPorts["in"] = grp.OutPorts["grep"] snk.In = ct.OutPorts["out"] pl := sci.NewPipeline() pl.AddProcs(ls, grp, ct, snk) pl.Run() fmt.Println("Finished program!") }
package main import ( "fmt" sci "github.com/samuell/scipipe" ) func main() { sci.InitLogDebug() fmt.Println("Starting program!") ls := sci.Shell("ls -l / > {os:lsl}") ls.OutPathFuncs["lsl"] = func(tsk *sci.ShellTask) string { return "lsl.txt" } grp := sci.Shell("grep etc {i:in} > {o:grep}") grp.OutPathFuncs["grep"] = func(tsk *sci.ShellTask) string { return tsk.GetInPath("in") + ".grepped.txt" } ct := sci.Shell("cat {i:in} > {o:out}") ct.OutPathFuncs["out"] = func(tsk *sci.ShellTask) string { return tsk.GetInPath("in") + ".out.txt" } snk := sci.NewSink() grp.InPorts["in"] = ls.OutPorts["lsl"] ct.InPorts["in"] = grp.OutPorts["grep"] snk.In = ct.OutPorts["out"] pl := sci.NewPipeline() pl.AddProcs(ls, grp, ct, snk) pl.Run() fmt.Println("Finished program!") }
Fix Eclipse resolution of plugins; this may be different in other IDEs
package uk.co.uwcs.choob.modules; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; class ChoobURLStreamHandler extends URLStreamHandler { @Override protected URLConnection openConnection(URL u) throws IOException { final String path = u.getPath(); { final URL resource = ChoobURLStreamHandler.class.getResource(path); if (null != resource) return resource.openConnection(); } for (File sourcePath : new File[] { new File("main/plugins-alpha"), new File("main/plugins"), }) { final File f = new File(sourcePath, u.getPath()); if (f.isFile()) return new URL("file:///" + f.getAbsolutePath()).openConnection(); } throw new FileNotFoundException("Couldn't resolve '" + path + "' from the classpath or source directories"); } }
package uk.co.uwcs.choob.modules; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; class ChoobURLStreamHandler extends URLStreamHandler { @Override protected URLConnection openConnection(URL u) throws IOException { final String path = u.getPath(); { final URL resource = ChoobURLStreamHandler.class.getResource(path); if (null != resource) return resource.openConnection(); } for (File sourcePath : new File[] { new File("src/main/plugins-alpha"), new File("src/main/plugins"), }) { final File f = new File(sourcePath, u.getPath()); if (f.isFile()) return new URL("file:///" + f.getAbsolutePath()).openConnection(); } throw new FileNotFoundException("Couldn't resolve '" + path + "' from the classpath or source directories"); } }
Fix triangle wave for the modulo of a negative number issue
/** * @depends TableLookupOscillator.js */ var Triangle = new Class({ Extends: TableLookupOscillator, initialize: function(audiolet, frequency) { TableLookupOscillator.prototype.initialize.apply(this, [audiolet, Triangle.TABLE, frequency]); } }); Triangle.TABLE = []; for (var i = 0; i < 8192; i++) { // Smelly, but looks right... Triangle.TABLE.push(Math.abs(((((i - 2048) / 8192) % 1) + 1) % 1* 2 - 1) * 2 - 1); }
/** * @depends TableLookupOscillator.js */ var Triangle = new Class({ Extends: TableLookupOscillator, initialize: function(audiolet, frequency) { TableLookupOscillator.prototype.initialize.apply(this, [audiolet, Triangle.TABLE, frequency]); } }); Triangle.TABLE = []; for (var i = 0; i < 8192; i++) { // Smelly, but looks right... Triangle.TABLE.push(Math.abs(((i - 2048) / 8192) % 1 * 2 - 1) * 2 - 1); }
Fix Typo bug. TRUST -> TRUSTEE
/* * Copyright 2006-2014 innopost.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * or in the "license" file accompanying this file. This file 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.popbill.api.taxinvoice; /** * Enum for MgtKeyType. * * @author KimSeonjun * @version 1.0.0 */ public enum MgtKeyType { /** * 매출 */ SELL, /** * 매입 */ BUY, /** * 수탁 */ TRUSTEE }
/* * Copyright 2006-2014 innopost.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * or in the "license" file accompanying this file. This file 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.popbill.api.taxinvoice; /** * Enum for MgtKeyType. * * @author KimSeonjun * @version 1.0.0 */ public enum MgtKeyType { /** * 매출 */ SELL, /** * 매입 */ BUY, /** * 수탁 */ TRUST }
Add support for tern complete_strings plugin
# -*- coding: utf-8 -*- import json import os.path import re from completor import Completor from completor.compat import to_unicode dirname = os.path.dirname(__file__) class Tern(Completor): filetype = 'javascript' daemon = True ident = re.compile(r"""(\w+)|(('|").+)""", re.U) trigger = r"""\w+$|[\w\)\]\}\'\"]+\.\w*$|('|").*$""" def format_cmd(self): binary = self.get_option('node_binary') or 'node' tern_config = self.find_config_file('.tern-project') cmd = [binary, os.path.join(dirname, 'tern_wrapper.js')] if tern_config: cmd.append(os.path.dirname(tern_config)) return cmd def parse(self, data): try: data = to_unicode(data[0], 'utf-8') return [i for i in json.loads(data) if not self.input_data.endswith(i['word'])] except Exception: return []
# -*- coding: utf-8 -*- import json import os.path from completor import Completor from completor.compat import to_unicode dirname = os.path.dirname(__file__) class Tern(Completor): filetype = 'javascript' daemon = True trigger = r'\w+$|[\w\)\]\}\'\"]+\.\w*$' def format_cmd(self): binary = self.get_option('node_binary') or 'node' tern_config = self.find_config_file('.tern-project') cmd = [binary, os.path.join(dirname, 'tern_wrapper.js')] if tern_config: cmd.append(os.path.dirname(tern_config)) return cmd def parse(self, data): try: data = to_unicode(data[0], 'utf-8') return [i for i in json.loads(data) if not self.input_data.endswith(i['word'])] except Exception: return []
Fix reorder call in controller
<?php namespace Code16\Sharp\Http\Api; class EntityListController extends ApiController { /** * @param string $entityKey * @return \Illuminate\Http\JsonResponse */ public function show($entityKey) { sharp_check_ability("entity", $entityKey); $list = $this->getListInstance($entityKey); $list->buildListConfig(); return response()->json([ "containers" => $list->dataContainers(), "layout" => $list->listLayout(), "data" => $list->data(), "config" => $list->listConfig() ]); } /** * Call for reorder instances. * * @param string $entityKey * @return \Illuminate\Http\JsonResponse */ public function update($entityKey) { sharp_check_ability("update", $entityKey); $list = $this->getListInstance($entityKey); $list->buildListConfig(); $list->reorderHandler()->reorder( request("instances") ); return response()->json([ "ok" => true ]); } }
<?php namespace Code16\Sharp\Http\Api; class EntityListController extends ApiController { /** * @param string $entityKey * @return \Illuminate\Http\JsonResponse */ public function show($entityKey) { sharp_check_ability("entity", $entityKey); $list = $this->getListInstance($entityKey); $list->buildListConfig(); return response()->json([ "containers" => $list->dataContainers(), "layout" => $list->listLayout(), "data" => $list->data(), "config" => $list->listConfig() ]); } /** * Call for reorder instances. * * @param string $entityKey * @return \Illuminate\Http\JsonResponse */ public function update($entityKey) { sharp_check_ability("update", $entityKey); $list = $this->getListInstance($entityKey); $list->reorderHandler()->reorder( request("instances") ); return response()->json([ "ok" => true ]); } }
Allow having unique integer columns in the database
package sword.langbook3.android.sqlite; import sword.database.DbColumn; import sword.database.DbValue; public final class SqliteUtils { private SqliteUtils() { } public static String sqlType(DbColumn column) { if (column.isPrimaryKey()) { return "INTEGER PRIMARY KEY AUTOINCREMENT"; } else { final String typeName = column.isText()? "TEXT" : "INTEGER"; return column.isUnique()? typeName + " UNIQUE ON CONFLICT IGNORE" : typeName; } } public static String sqlValue(DbValue value) { return value.isText()? "'" + value.toText() + '\'' : Integer.toString(value.toInt()); } }
package sword.langbook3.android.sqlite; import sword.database.DbColumn; import sword.database.DbValue; public final class SqliteUtils { private SqliteUtils() { } public static String sqlType(DbColumn column) { if (column.isPrimaryKey()) { return "INTEGER PRIMARY KEY AUTOINCREMENT"; } else if (column.isUnique()) { return "TEXT UNIQUE ON CONFLICT IGNORE"; } else if (column.isText()) { return "TEXT"; } else { return "INTEGER"; } } public static String sqlValue(DbValue value) { return value.isText()? "'" + value.toText() + '\'' : Integer.toString(value.toInt()); } }
Define scripts in a array instead of inline
angular .module('ngSharepoint', []) .run(function($sp, $spLoader) { if ($sp.getAutoload()) { if ($sp.getConnectionMode() === 'JSOM') { var scripts = [ '//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js', 'SP.Runtime.js', 'SP.js' ]; $spLoader.loadScripts('SP.Core', scripts); }else if ($sp.getConnectionMode() === 'REST' && !$sp.getAccessToken()) { $spLoader.loadScript('SP.RequestExecutor.js'); } } });
angular .module('ngSharepoint', []) .run(function($sp, $spLoader) { if ($sp.getAutoload()) { if ($sp.getConnectionMode() === 'JSOM') { $spLoader.loadScripts('SP.Core', ['//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js', 'SP.Runtime.js', 'SP.js']); }else if ($sp.getConnectionMode() === 'REST' && !$sp.getAccessToken()) { $spLoader.loadScript('SP.RequestExecutor.js'); } } });
Exit with code 1 if no connection to the DB
var orm = require('orm'); var connectionString; if (process.env.SQLITE == 'true') connectionString = 'sqlite://' + __dirname + '/db.sqlite'; else connectionString = 'postgres://cote:ohgath2ig8eoP8@pg/cote'; var db = orm.connect(connectionString, function onConnect(err) { if (err) { console.log('Error', err); process.exit(1); } }); db.settings.set('instance.cache', false); var Product = db.define('product', { name: String, price: Number, stock: Number }); var Purchase = db.define('purchase', {}); var User = db.define('user', { balance: { type: 'number', defaultValue: 30 } }); Purchase.hasOne('product', Product, { autoFetch: true }); Purchase.hasOne('owner', User, { autoFetch: true, reverse: 'purchases' }); function init(callback) { console.log('Dropping db.'); db.drop(function() { console.log('Initializing db.'); db.sync(callback); }); } module.exports = { Product: Product, Purchase: Purchase, User: User, init: init };
var orm = require('orm'); var connectionString; if (process.env.SQLITE == 'true') connectionString = 'sqlite://' + __dirname + '/db.sqlite'; else connectionString = 'postgres://cote:ohgath2ig8eoP8@pg/cote'; var db = orm.connect(connectionString, function onConnect(err) { if (err) { console.log('Error', err); process.exit(); } }); db.settings.set('instance.cache', false); var Product = db.define('product', { name: String, price: Number, stock: Number }); var Purchase = db.define('purchase', {}); var User = db.define('user', { balance: { type: 'number', defaultValue: 30 } }); Purchase.hasOne('product', Product, { autoFetch: true }); Purchase.hasOne('owner', User, { autoFetch: true, reverse: 'purchases' }); function init(callback) { console.log('Dropping db.'); db.drop(function() { console.log('Initializing db.'); db.sync(callback); }); } module.exports = { Product: Product, Purchase: Purchase, User: User, init: init };
Use t.Error if formatting is not needed
package crane import "testing" func TestDependencies(t *testing.T) { container := &Container{Run: RunParameters{RawLink: []string{"a:b", "b:d"}}} if deps := container.Dependencies(); deps[0] != "a" || deps[1] != "b" { t.Error("Dependencies should have been a and b") } container = &Container{Run: RunParameters{RawLink: []string{}}} if deps := container.Dependencies(); len(deps) != 0 { t.Error("Dependencies should have been empty") } } func TestIsTargeted(t *testing.T) { container := &Container{RawName: "a"} if container.IsTargeted([]string{"b"}) { t.Error("Container name was a, got targeted with b") } if !container.IsTargeted([]string{"x", "a"}) { t.Error("Container name was a, should have been targeted with a") } }
package crane import "testing" func TestDependencies(t *testing.T) { container := &Container{Run: RunParameters{RawLink: []string{"a:b", "b:d"}}} if deps := container.Dependencies(); deps[0] != "a" || deps[1] != "b" { t.Errorf("Dependencies should have been a and b") } container = &Container{Run: RunParameters{RawLink: []string{}}} if deps := container.Dependencies(); len(deps) != 0 { t.Errorf("Dependencies should have been empty") } } func TestIsTargeted(t *testing.T) { container := &Container{RawName: "a"} if container.IsTargeted([]string{"b"}) { t.Errorf("Container name was a, got targeted with b") } if !container.IsTargeted([]string{"x", "a"}) { t.Errorf("Container name was a, should have been targeted with a") } }
Add a little bit more documentation for round2submission script
#!/usr/bin/env python import opensim as osim from osim.redis.client import Client from osim.env import * import numpy as np import argparse import os """ NOTE: For testing your submission scripts, you first need to ensure that redis-server is running in the background and you can locally run the grading service by running this script : https://github.com/crowdAI/osim-rl/blob/master/osim/redis/service.py The client and the grading service communicate with each other by pointing to the same redis server. """ """ Please ensure that `visualize=False`, else there might be unexpected errors in your submission """ env = RunEnv(visualize=False) client = Client() # Create environment observation = client.env_create() """ The grader runs N simulations of at most 1000 steps each. We stop after the last one A new simulation start when `clinet.env_step` returns `done==True` and all the simulatiosn end when the subsequent `client.env_reset()` returns a False """ while True: _action = env.action_space.sample().tolist() [observation, reward, done, info] = client.env_step(_action) print(observation) if done: observation = client.env_reset() if not observation: break client.submit()
#!/usr/bin/env python import opensim as osim from osim.redis.client import Client from osim.env import * import numpy as np import argparse import os """ Please ensure that `visualize=False`, else there might be unexpected errors in your submission """ env = RunEnv(visualize=False) client = Client() # Create environment observation = client.env_create() """ The grader runs N simulations of at most 1000 steps each. We stop after the last one A new simulation start when `clinet.env_step` returns `done==True` and all the simulatiosn end when the subsequent `client.env_reset()` returns a False """ while True: _action = env.action_space.sample().tolist() [observation, reward, done, info] = client.env_step(_action) print(observation) if done: observation = client.env_reset() if not observation: break client.submit()
Add a zone port range.
# ##### BEGIN AGPL LICENSE BLOCK ##### # This file is part of SimpleMMO. # # Copyright (C) 2011, 2012 Charles Nelson # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # ##### END AGPL LICENSE BLOCK ##### PROTOCOL = "http" HOSTNAME = "localhost" AUTHSERVERPORT = 1234 CHARSERVERPORT = 1235 MASTERZONESERVERPORT = 1236 ZONESTARTPORT = 1300 ZONEENDPORT = 1400 ZONESTARTUPTIME = 10 DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S:%f' ADMINISTRATORS = ['admin'] CLIENT_TIMEOUT = 10 # Client gives up connecting after 10 seconds. MSPERSEC = 1000 CLIENT_NETWORK_FPS = 10 CLIENT_UPDATE_FREQ = MSPERSEC/CLIENT_NETWORK_FPS
# ##### BEGIN AGPL LICENSE BLOCK ##### # This file is part of SimpleMMO. # # Copyright (C) 2011, 2012 Charles Nelson # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # ##### END AGPL LICENSE BLOCK ##### PROTOCOL = "http" HOSTNAME = "localhost" AUTHSERVERPORT = 1234 CHARSERVERPORT = 1235 MASTERZONESERVERPORT = 1236 ZONESTARTUPTIME = 10 DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S:%f' ADMINISTRATORS = ['admin'] CLIENT_TIMEOUT = 10 # Client gives up connecting after 10 seconds. MSPERSEC = 1000 CLIENT_NETWORK_FPS = 10 CLIENT_UPDATE_FREQ = MSPERSEC/CLIENT_NETWORK_FPS
OLMIS-1128: Add redirecting when requisition id is not found
(function() { 'use strict'; angular.module('openlmis.requisitions').config(config); config.$inject = ['$stateProvider']; function config($stateProvider) { $stateProvider.state('requisitions', { abstract: true, url: '/requisitions', template: '<div ui-view></div>' }); $stateProvider.state('requisitions.requisition', { url: '^/requisition/:rnr', controller: 'RequisitionCtrl', templateUrl: 'requisitions/requisition.html', resolve: { requisition: function ($location, $q, $stateParams, RequisitionFactory) { var deferred = $q.defer(); RequisitionFactory.get($stateParams.rnr).$promise.then(function(response) { deferred.resolve(response); }, function(response) { deferred.reject(); return $location.url('/404'); }); return deferred.promise; } } }); } })();
(function() { 'use strict'; angular.module('openlmis.requisitions').config(config); config.$inject = ['$stateProvider']; function config($stateProvider) { $stateProvider.state('requisitions', { abstract: true, url: '/requisitions', template: '<div ui-view></div>' }); $stateProvider.state('requisitions.requisition', { url: '^/requisition/:rnr', controller: 'RequisitionCtrl', templateUrl: 'requisitions/requisition.html', resolve: { requisition: function ($q, $stateParams, RequisitionFactory) { var deferred = $q.defer(); RequisitionFactory.get($stateParams.rnr).$promise.then(function(response) { deferred.resolve(response); }, function(response) { alert('Cannot find requisition with UUID: ' + $stateParams.rnr); deferred.reject(); }); return deferred.promise; } } }); } })();