text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Use list for Models collector + sort
<?php namespace Barryvdh\Debugbar\DataCollector; use DebugBar\DataCollector\DataCollector; use DebugBar\DataCollector\DataCollectorInterface; use DebugBar\DataCollector\Renderable; use Illuminate\Contracts\Events\Dispatcher; use Illuminate\Support\Str; /** * Collector for Models. */ class ModelsCollector extends DataCollector implements DataCollectorInterface, Renderable { public $models = []; /** * @param Dispatcher $events */ public function __construct(Dispatcher $events) { $events->listen('eloquent.*', function ($event, $models) { if (Str::contains($event, 'eloquent.retrieved')) { foreach (array_filter($models) as $model) { $class = get_class($model); $this->models[$class] = ($this->models[$class] ?? 0) + 1; } } }); } public function collect() { ksort($this->models, SORT_NUMERIC); return array_reverse($this->models); } /** * {@inheritDoc} */ public function getName() { return 'models'; } /** * {@inheritDoc} */ public function getWidgets() { return [ "models" => [ "icon" => "cubes", "widget" => "PhpDebugBar.Widgets.HtmlVariableListWidget", "map" => "models", "default" => "{}" ] ]; } }
<?php namespace Barryvdh\Debugbar\DataCollector; use Barryvdh\Debugbar\DataFormatter\SimpleFormatter; use DebugBar\DataCollector\MessagesCollector; use Illuminate\Contracts\Events\Dispatcher; use Illuminate\Support\Str; /** * Collector for Models. */ class ModelsCollector extends MessagesCollector { public $models = []; /** * @param Dispatcher $events */ public function __construct(Dispatcher $events) { parent::__construct('models'); $this->setDataFormatter(new SimpleFormatter()); $events->listen('eloquent.*', function ($event, $models) { if (Str::contains($event, 'eloquent.retrieved')) { foreach (array_filter($models) as $model) { $class = get_class($model); $this->models[$class] = ($this->models[$class] ?? 0) + 1; } } }); } public function collect() { foreach ($this->models as $type => $count) { $this->addMessage($count, $type); } return [ 'count' => array_sum($this->models), 'messages' => $this->getMessages(), ]; } public function getWidgets() { $widgets = parent::getWidgets(); $widgets['models']['icon'] = 'cubes'; return $widgets; } }
Put in $F function to grab values instead of $('id').value
var FormHelper = { // TODO: Make this more generic, because it // will be reused. hideShowConfigurationTitle: function() { if ($('configuration_title').visible()) { $('configuration_title').hide(); $('configuration_title_container').show(); } else { $('configuration_title').show(); $('configuration_title_container').hide(); $('configuration_title').focus(); } }, configurationTitleKeyPress: function(e) { // Escape key press. There are probably constants for this! if (e.keyCode == 27) { this.hideShowConfigurationTitle(); } // Enter key pressed. else if (e.keyCode == 13) { var url = "/admin/configurations?title=" + $F('configuration_title'); new Ajax.Request(url, { asynchronous:'true', evalScripts:'true', method:'put', onLoading: function() { FormHelper.hideShowConfigurationTitle(); $('configuration_title_container').innerText = "Saving..." }, // onSuccess: function(transport) { // var response = transport.responseText; // $('configuration_title_container').innerText = response; // }, onFailure: function() { alert('Something went wrong...') }, }); } } } Event.observe(window, 'load', function() { Event.observe('configuration_title_container', 'click', FormHelper.hideShowConfigurationTitle); Event.observe('configuration_title', 'blur', FormHelper.hideShowConfigurationTitle); Event.observe('configuration_title', 'keypress', FormHelper.configurationTitleKeyPress.bindAsEventListener(FormHelper)); });
var FormHelper = { // TODO: Make this more generic, because it // will be reused. hideShowConfigurationTitle: function() { if ($('configuration_title').visible()) { $('configuration_title').hide(); $('configuration_title_container').show(); } else { $('configuration_title').show(); $('configuration_title_container').hide(); $('configuration_title').focus(); } }, configurationTitleKeyPress: function(e) { // Escape key press. There are probably constants for this! if (e.keyCode == 27) { this.hideShowConfigurationTitle(); } // Enter key pressed. else if (e.keyCode == 13) { var url = "/admin/configurations?title=" + $('configuration_title').value; new Ajax.Request(url, { asynchronous:'true', evalScripts:'true', method:'put', onLoading: function() { FormHelper.hideShowConfigurationTitle(); $('configuration_title_container').innerText = "Saving..." }, // onSuccess: function(transport) { // var response = transport.responseText; // $('configuration_title_container').innerText = response; // }, onFailure: function() { alert('Something went wrong...') }, }); } } } Event.observe(window, 'load', function() { Event.observe('configuration_title_container', 'click', FormHelper.hideShowConfigurationTitle); Event.observe('configuration_title', 'blur', FormHelper.hideShowConfigurationTitle); Event.observe('configuration_title', 'keypress', FormHelper.configurationTitleKeyPress.bindAsEventListener(FormHelper)); });
Fix a bug when a command like "/list-players" is miss-spelled and "/leave" is executed cause of its alias "/l".
package client.command; public enum Commands { Username(new String[]{"/username", "/name", "/u"}, Username.class), Team(new String[]{"/team", "/t"}, Team.class), Contract(new String[]{"/contract"}, Contract.class), Create(new String[]{"/create", "/c"}, Create.class), Join(new String[]{"/join", "/j"}, Join.class), ListPlayers(new String[]{"/list-players"}, ListPlayers.class), ListChannel(new String[]{"/list-channel"}, ListChannel.class), Leave(new String[]{"/leave", "/l"}, Leave.class), ShowCards(new String[]{"/show-cards"}, ShowCards.class), ShowTable(new String[]{"/show-table"}, ShowTable.class), PlayCard(new String[]{"/play"}, PlayCard.class), ShowContract(new String[]{"/show-contract"}, ShowContract.class); private String[] aliases; private Class command; Commands(String[] aliases, Class command) { this.aliases = aliases; this.command = command; } public static Class from(String text) throws Exception { for (Commands command : Commands.values()) { for (String alias : command.getAliases()) { if (text.startsWith(alias + ' ')) { return command.getCommand(); } } } throw new Exception(); } public String[] getAliases() { return this.aliases; } public Class getCommand() { return this.command; } }
package client.command; public enum Commands { Username(new String[]{"/username", "/name", "/u"}, Username.class), Team(new String[]{"/team", "/t"}, Team.class), Contract(new String[]{"/contract"}, Contract.class), Create(new String[]{"/create", "/c"}, Create.class), Join(new String[]{"/join", "/j"}, Join.class), ListPlayers(new String[]{"/list-players"}, ListPlayers.class), ListChannel(new String[]{"/list-channel"}, ListChannel.class), Leave(new String[]{"/leave", "/l"}, Leave.class), ShowCards(new String[]{"/show-cards"}, ShowCards.class), ShowTable(new String[]{"/show-table"}, ShowTable.class), PlayCard(new String[]{"/play"}, PlayCard.class), ShowContract(new String[]{"/show-contract"}, ShowContract.class); private String[] aliases; private Class command; Commands(String[] aliases, Class command) { this.aliases = aliases; this.command = command; } public static Class from(String text) throws Exception { for (Commands command : Commands.values()) { for (String alias : command.getAliases()) { if (text.startsWith(alias)) { return command.getCommand(); } } } throw new Exception(); } public String[] getAliases() { return this.aliases; } public Class getCommand() { return this.command; } }
Fix syntax error and refer correct method
package org.edx.mobile.module.analytics; import android.content.Context; import org.edx.mobile.util.Config; public class SegmentFactory { private static ISegment sInstance; /** * Returns a singleton instance of {@link org.edx.mobile.module.analytics.ISegment}. * Use {@link #makeInstance(android.content.Context)} to create an instance. * Returns an instance of {@link org.edx.mobile.module.analytics.ISegmentEmptyImpl} if * {@link #makeInstance(android.content.Context)} was never called before. * @return */ public static ISegment getInstance() { if (sInstance == null) { sInstance = new ISegmentEmptyImpl(); } return sInstance; } /** * Creates a singleton instance of {@link org.edx.mobile.module.analytics.ISegment} * if not already created. * If configuration does not allow third party traffic, then this method makes * an instance of {@link org.edx.mobile.module.analytics.ISegmentEmptyImpl} class * which does not capture any data. * @param context */ public static void makeInstance(Context context) { if (sInstance == null) { if (Config.getInstance().getThirdPartyTraffic().isSegmentEnabled()) { sInstance = new ISegmentImpl(context); } else { sInstance = new ISegmentEmptyImpl(); } } } }
package org.edx.mobile.module.analytics; import android.content.Context; import org.edx.mobile.util.Config; public class SegmentFactory { private static ISegment sInstance; /** * Returns a singleton instance of {@link org.edx.mobile.module.analytics.ISegment}. * Use {@link #makeInstance(android.content.Context)} to create an instance. * Returns an instance of {@link org.edx.mobile.module.analytics.ISegmentEmptyImpl} if * {@link #makeInstance(android.content.Context)} was never called before. * @return */ public static ISegment getInstance() { if (sInstance == null) { sInstance = new ISegmentEmptyImpl(); } return sInstance; } /** * Creates a singleton instance of {@link org.edx.mobile.module.analytics.ISegment} * if not already created. * If configuration does not allow third party traffic, then this method makes * an instance of {@link org.edx.mobile.module.analytics.ISegmentEmptyImpl} class * which does not capture any data. * @param context */ public static void makeInstance(Context context) { if (sInstance == null) { if (Config.getInstance().getThirdPartyTrafficEnabled()) { sInstance = new ISegmentImpl(context); } else { sInstance = new ISegmentEmptyImpl(); } } } }
Update test case create is not available because of field edit permission.
<?php namespace ProcessWire\GraphQL\Test\Permissions; use ProcessWire\GraphQL\Test\GraphqlTestCase; use function ProcessWire\GraphQL\Test\Assert\assertTypePathNotExists; class EditorCreateNotAvailableFieldEditPermissionTest extends GraphqlTestCase { /** * + For editor. * + The template is legal. * + The configured parent template is legal. * + All required fields are legal. * + Editor has all required permissions for templates. * - Editor does not have edit permission on required field. (title) */ public static function getSettings() { return [ 'login' => 'editor', 'legalTemplates' => ['skyscraper', 'city'], 'legalFields' => ['title', 'images'], 'access' => [ 'templates' => [ [ 'name' => 'skyscraper', 'roles' => ['editor'], 'editRoles' => ['editor'], 'createRoles' => ['editor'], ], [ 'name' => 'city', 'roles' => ['editor'], 'addRoles' => ['editor'], ] ], 'fields' => [ [ 'name' => 'images', 'editRoles' => ['editor'], ], [ 'name' => 'title', // 'editRoles' => ['editor'], // <-- has no edit permission to the required "title" field. ], ] ] ]; } public function testPermission() { assertTypePathNotExists( ['Mutation', 'createSkyscraper'], 'createSkyscraper mutation field should not be available if user has no edit permission on the required field.' ); } }
<?php namespace ProcessWire\GraphQL\Test\Permissions; use ProcessWire\GraphQL\Test\GraphqlTestCase; use ProcessWire\GraphQL\Utils; use function ProcessWire\GraphQL\Test\Assert\assertTypePathNotExists; class EditorCreateNotAvailableFieldEditPermissionTest extends GraphqlTestCase { /** * + For editor. * + The template is legal. * + The configured parent template is legal. * + All required fields are legal. * + Editor has all required permissions for templates. * - Editor does not have edit permission on required field. (title) */ public static function getSettings() { $editorRole = Utils::roles()->get("editor"); return [ 'login' => 'editor', 'legalTemplates' => ['skyscraper', 'city'], 'legalFields' => ['title', 'images'], 'access' => [ 'templates' => [ [ 'name' => 'skyscraper', 'roles' => [$editorRole->id], 'editRoles' => [$editorRole->id], 'createRoles' => [$editorRole->id], ], [ 'name' => 'city', 'roles' => [$editorRole->id], 'addRoles' => [$editorRole->id], ] ], 'fields' => [ [ 'name' => 'images', 'editRoles' => [$editorRole->id], ] ] ] ]; } public function testPermission() { assertTypePathNotExists( ['Mutation', 'createSkyscraper'], 'createSkyscraper mutation field should not be available if one of the required fields is not legal.' ); } }
Hide video facility contents from non-financial clients
const BinaryPjax = require('../base/binary_pjax'); const Client = require('../base/client'); const localize = require('../base/localize').localize; const defaultRedirectUrl = require('../base/url').defaultRedirectUrl; const getLoginToken = require('../common_functions/common_functions').getLoginToken; const DeskWidget = require('../common_functions/attach_dom/desk_widget'); const BinarySocket = require('../websocket_pages/socket'); const VideoFacility = (() => { const onLoad = () => { if (Client.get('loginid_array').find(obj => obj.id === Client.get('loginid')).non_financial) { $('#loading').replaceWith($('<p/>', { class: 'notice-msg center-text', text: localize('Sorry, this feature is not available in your jurisdiction.') })); return; } BinarySocket.send({ get_account_status: 1 }).then((response) => { if (response.error) { $('#error_message').setVisibility(1).text(response.error.message); } else { const status = response.get_account_status.status; if (/authenticated/.test(status)) { BinaryPjax.load(defaultRedirectUrl()); } else { DeskWidget.showDeskLink('', '#facility_content'); if (!Client.isFinancial()) { $('#not_authenticated').setVisibility(1); } $('.msg_authenticate').setVisibility(1); $('#generated_token').text(getLoginToken().slice(-4)); } } }); }; return { onLoad: onLoad, }; })(); module.exports = VideoFacility;
const BinaryPjax = require('../base/binary_pjax'); const Client = require('../base/client'); const defaultRedirectUrl = require('../base/url').defaultRedirectUrl; const getLoginToken = require('../common_functions/common_functions').getLoginToken; const DeskWidget = require('../common_functions/attach_dom/desk_widget'); const BinarySocket = require('../websocket_pages/socket'); const VideoFacility = (() => { const onLoad = () => { BinarySocket.send({ get_account_status: 1 }).then((response) => { if (response.error) { $('#error_message').setVisibility(1).text(response.error.message); } else { const status = response.get_account_status.status; if (/authenticated/.test(status)) { BinaryPjax.load(defaultRedirectUrl()); } else { DeskWidget.showDeskLink('', '#facility_content'); if (!Client.isFinancial()) { $('#not_authenticated').setVisibility(1); } $('.msg_authenticate').setVisibility(1); $('#generated_token').text(getLoginToken().slice(-4)); } } }); }; return { onLoad: onLoad, }; })(); module.exports = VideoFacility;
Destroy session redis way too.
var CONTEXT_URI = process.env.CONTEXT_URI; exports.requiresSession = function (req, res, next) { if (req.session.encodedUsername) { res.cookie('_eun', req.session.encodedUsername); next(); } else { req.session.redirectUrl = CONTEXT_URI + req.originalUrl; if (req.url.split('?')[1] !== undefined) { var intent = "session.redirect"; var redirectUrl = CONTEXT_URI + req.url; res.redirect(CONTEXT_URI + "/signup" + "?intent=" + intent + "&redirectUrl=" + encodeURIComponent(redirectUrl)); } else { res.redirect(CONTEXT_URI + "/signup"); } } }; exports.setSession = function (req, res, user) { req.session.username = user.username; req.session.encodedUsername = user.encodedUsername; req.session.githubUsername = user.githubUser.username; req.session.avatarUrl = user.githubUser._json.avatar_url; res.cookie('_eun', req.session.encodedUsername); }; exports.resetSession = function (req) { req.session.destory; req.session.encodedUsername = null; req.session.auth = null; req.session.intent = null; req.session.oneselfUsername = null; req.session.username = null; req.session.githubUsername = null; req.session.avatarUrl = null; };
var CONTEXT_URI = process.env.CONTEXT_URI; exports.requiresSession = function (req, res, next) { if (req.session.encodedUsername) { res.cookie('_eun', req.session.encodedUsername); next(); } else { req.session.redirectUrl = CONTEXT_URI + req.originalUrl; if (req.url.split('?')[1] !== undefined) { var intent = "session.redirect"; var redirectUrl = CONTEXT_URI + req.url; res.redirect(CONTEXT_URI + "/signup" + "?intent=" + intent + "&redirectUrl=" + encodeURIComponent(redirectUrl)); } else { res.redirect(CONTEXT_URI + "/signup"); } } }; exports.setSession = function (req, res, user) { req.session.username = user.username; req.session.encodedUsername = user.encodedUsername; req.session.githubUsername = user.githubUser.username; req.session.avatarUrl = user.githubUser._json.avatar_url; res.cookie('_eun', req.session.encodedUsername); }; exports.resetSession = function (req) { req.session.encodedUsername = null; req.session.auth = null; req.session.intent = null; req.session.oneselfUsername = null; req.session.username = null; req.session.githubUsername = null; req.session.avatarUrl = null; };
Decrease limit for faster testing
var should = require('should'); var Client = require('../../../client/v1'); var Promise = require('bluebird'); var path = require('path'); var mkdirp = require('mkdirp'); var inquirer = require('inquirer'); var _ = require('underscore'); var fs = require('fs'); describe("`AccountFollowers` class", function() { var feed, session; before(function() { session = require('../../run').session; feed = new Client.Feed.AccountFollowers(session, '25025320', 400); }) it("should not be problem to get followers", function(done) { var originalCursor = feed.getCursor(); feed.get().then(function(data) { _.each(data, function(account) { account.should.be.instanceOf(Client.Account) }) should(originalCursor).not.equal(feed.getCursor()) feed.moreAvailable.should.be.Boolean(); feed.moreAvailable.should.equal(true); done() }) }) it("should not be problem to get all followers with limit 400", function(done) { feed.all().then(function(data) { _.each(data, function(account) { account.should.be.instanceOf(Client.Account) }) feed.moreAvailable.should.be.Boolean(); done() }) }) })
var should = require('should'); var Client = require('../../../client/v1'); var Promise = require('bluebird'); var path = require('path'); var mkdirp = require('mkdirp'); var inquirer = require('inquirer'); var _ = require('underscore'); var fs = require('fs'); describe("`AccountFollowers` class", function() { var feed, session; before(function() { session = require('../../run').session; feed = new Client.Feed.AccountFollowers(session, '25025320', 1000); }) it("should not be problem to get followers", function(done) { var originalCursor = feed.getCursor(); feed.get().then(function(data) { _.each(data, function(account) { account.should.be.instanceOf(Client.Account) }) should(originalCursor).not.equal(feed.getCursor()) feed.moreAvailable.should.be.Boolean(); feed.moreAvailable.should.equal(true); done() }) }) it("should not be problem to get all followers", function(done) { feed.all().then(function(data) { _.each(data, function(account) { account.should.be.instanceOf(Client.Account) }) feed.moreAvailable.should.be.Boolean(); done() }) }) })
Make session cookies have secure and httponly flags by default.
# Copyright 2016 David Tomaschik <[email protected]> # # 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. import os class Defaults(object): ATTACHMENT_BACKEND = 'file://attachments' COUNT_QUERIES = False CSP_POLICY = None CWD = os.path.dirname(os.path.realpath(__file__)) DEBUG = False EXTEND_CSP_POLICY = None ERROR_404_HELP = False FIRST_BLOOD = 0 GAME_TIME = (None, None) LOGIN_METHOD = 'local' MAIL_FROM = 'ctf@scoreboard' MAIL_FROM_NAME = None MAIL_HOST = 'localhost' NEWS_POLL_INTERVAL = 60000 RULES = '/rules' SCOREBOARD_ZEROS = True SCORING = 'plain' SECRET_KEY = None SESSION_COOKIE_HTTPONLY = True SESSION_COOKIE_SECURE = True SYSTEM_NAME = 'root' TEAMS = True TEASE_HIDDEN = True TITLE = 'Scoreboard'
# Copyright 2016 David Tomaschik <[email protected]> # # 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. import os class Defaults(object): ATTACHMENT_BACKEND = 'file://attachments' COUNT_QUERIES = False CSP_POLICY = None CWD = os.path.dirname(os.path.realpath(__file__)) DEBUG = False EXTEND_CSP_POLICY = None ERROR_404_HELP = False FIRST_BLOOD = 0 GAME_TIME = (None, None) LOGIN_METHOD = 'local' MAIL_FROM = 'ctf@scoreboard' MAIL_FROM_NAME = None MAIL_HOST = 'localhost' NEWS_POLL_INTERVAL = 60000 RULES = '/rules' SCOREBOARD_ZEROS = True SCORING = 'plain' SECRET_KEY = None SYSTEM_NAME = 'root' TEAMS = True TEASE_HIDDEN = True TITLE = 'Scoreboard'
Update dm.xmlsec.binding dependency to 1.3.7
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2010-2018 OneLogin, Inc. # MIT License from setuptools import setup setup( name='python-saml', version='2.4.1', description='Onelogin Python Toolkit. Add SAML support to your Python software using this library', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', ], author='OneLogin', author_email='[email protected]', license='MIT', url='https://github.com/onelogin/python-saml', packages=['onelogin', 'onelogin/saml2'], include_package_data=True, package_data={ 'onelogin/saml2/schemas': ['*.xsd'], }, package_dir={ '': 'src', }, test_suite='tests', install_requires=[ 'dm.xmlsec.binding==1.3.7', 'isodate>=0.5.0', 'defusedxml>=0.4.1', ], extras_require={ 'test': ( 'coverage>=3.6', 'freezegun==0.3.5', 'pylint==1.9.1', 'pep8==1.5.7', 'pyflakes==0.8.1', 'coveralls==1.1', ), }, keywords='saml saml2 xmlsec django flask', )
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2010-2018 OneLogin, Inc. # MIT License from setuptools import setup setup( name='python-saml', version='2.4.1', description='Onelogin Python Toolkit. Add SAML support to your Python software using this library', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', ], author='OneLogin', author_email='[email protected]', license='MIT', url='https://github.com/onelogin/python-saml', packages=['onelogin', 'onelogin/saml2'], include_package_data=True, package_data={ 'onelogin/saml2/schemas': ['*.xsd'], }, package_dir={ '': 'src', }, test_suite='tests', install_requires=[ 'dm.xmlsec.binding==1.3.3', 'isodate>=0.5.0', 'defusedxml>=0.4.1', ], extras_require={ 'test': ( 'coverage>=3.6', 'freezegun==0.3.5', 'pylint==1.9.1', 'pep8==1.5.7', 'pyflakes==0.8.1', 'coveralls==1.1', ), }, keywords='saml saml2 xmlsec django flask', )
Disable sleep function when stopping
import threading import queue class Routine(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.queue = queue.Queue() self.manager = None self.no_wait = False self.is_stopping = False self.sleeper = threading.Event() def run(self): while True: got_task = False data = None if self.no_wait: try: data = self.queue.get_nowait() got_task = True except queue.Empty: data = None got_task = False else: data = self.queue.get() got_task = True if data: index = 'routine_command' routine_command = data[index] if index in data else None if routine_command == 'stop': self.is_stopping = True self.process(data) if got_task: self.queue.task_done() if self.is_stopping: break def process(self, data): pass def sleep(self, seconds): if self.is_stopping: return while not self.sleeper.is_set(): self.sleeper.wait(timeout=seconds) self.sleeper.clear() def stop_signal(self): while not self.queue.empty(): try: self.queue.get_nowait() except queue.Empty: continue self.queue.task_done() self.queue.put({'routine_command': 'stop'}) self.sleeper.set()
import threading import queue class Routine(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.queue = queue.Queue() self.manager = None self.no_wait = False self.is_stopping = False self.sleeper = threading.Event() def run(self): while True: got_task = False data = None if self.no_wait: try: data = self.queue.get_nowait() got_task = True except queue.Empty: data = None got_task = False else: data = self.queue.get() got_task = True if data: index = 'routine_command' routine_command = data[index] if index in data else None if routine_command == 'stop': self.is_stopping = True self.process(data) if got_task: self.queue.task_done() if self.is_stopping: break def process(self, data): pass def sleep(self, seconds): while not self.sleeper.is_set(): self.sleeper.wait(timeout=seconds) self.sleeper.clear() def stop_signal(self): while not self.queue.empty(): try: self.queue.get_nowait() except queue.Empty: continue self.queue.task_done() self.queue.put({'routine_command': 'stop'}) self.sleeper.set()
Change URL to our online apidocs server
"use strict"; angular.module("angular-mobile-docs") .factory("MockFetchService", function ($http, $q) { var config = { url: "http://apidocs.angularjs.de/code.angularjs.org/" }; var getVersionList = function (version) { return $http.get(config.url+"versions.json"); } var getFileList = function (version) { return $http.get( config.url + version + "/docs/partials/api/filelist.json"); } var getPartial = function (version, name) { return $http.get( config.url + version + "/docs/partials/api/" + name); } var getAllPartials = function (version) { var promises = []; var fileNameList = getFileList(version); angular.forEach(fileNameList, function (fileName) { promises.push(getPartial(fileName, version)); }) return $q.all(promises); } return { getVersionList: function () { return getVersionList(); }, getFileList : function (version) { return getFileList(version); }, getPartial : function (version, name) { return getPartial(version, name); }, getAllPartials: function (version) { return getAllPartials(version); } }; });
"use strict"; angular.module("angular-mobile-docs") .factory("MockFetchService", function ($http, $q) { var config = { url: "http://localhost:8080/assets/code.angularjs.org/" }; var getVersionList = function (version) { return $http.get(config.url+"versions.json"); } var getFileList = function (version) { return $http.get( config.url + version + "/docs/partials/api/filelist.json"); } var getPartial = function (version, name) { return $http.get( config.url + version + "/docs/partials/api/" + name); } var getAllPartials = function (version) { var promises = []; var fileNameList = getFileList(version); angular.forEach(fileNameList, function (fileName) { promises.push(getPartial(fileName, version)); }) return $q.all(promises); } return { getVersionList: function () { return getVersionList(); }, getFileList : function (version) { return getFileList(version); }, getPartial : function (version, name) { return getPartial(version, name); }, getAllPartials: function (version) { return getAllPartials(version); } }; });
Make the extra 'tiff' to be less confusing It matches the new version of the documentation, and is how it is normally spelled. Signed-off-by: Marcus D. Hanwell <[email protected]>
from setuptools import setup, find_packages dm3_url = 'git+https://[email protected]/cjh1/pydm3reader.git' \ '@filelike#egg=dm3_lib-1.2' bottle_url = 'https://github.com/bottlepy/bottle/archive/41ed6965.zip' \ '#egg=bottle-0.13-dev' setup( name='tomviz-acquisition', version='0.0.1', description='Tomviz acquisition server.', author='Kitware, Inc.', author_email='[email protected]', url='https://www.tomviz.org/', license='BSD 3-Clause', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: BSD 3-Clause', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5' ], packages=find_packages(), extras_require={ 'tiff': ['Pillow'], 'test': ['requests', 'Pillow', 'mock', 'diskcache'] }, entry_points={ 'console_scripts': [ 'tomviz-acquisition = tomviz.acquisition.cli:main', 'tomviz-tiltseries-writer = tests.mock.tiltseries.writer:main' ] } )
from setuptools import setup, find_packages dm3_url = 'git+https://[email protected]/cjh1/pydm3reader.git' \ '@filelike#egg=dm3_lib-1.2' bottle_url = 'https://github.com/bottlepy/bottle/archive/41ed6965.zip' \ '#egg=bottle-0.13-dev' setup( name='tomviz-acquisition', version='0.0.1', description='Tomviz acquisition server.', author='Kitware, Inc.', author_email='[email protected]', url='https://www.tomviz.org/', license='BSD 3-Clause', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: BSD 3-Clause', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5' ], packages=find_packages(), extras_require={ 'tif': ['Pillow'], 'test': ['requests', 'Pillow', 'mock', 'diskcache'] }, entry_points={ 'console_scripts': [ 'tomviz-acquisition = tomviz.acquisition.cli:main', 'tomviz-tiltseries-writer = tests.mock.tiltseries.writer:main' ] } )
Use persistent test DB (--keepdb can skip migrations) By default test database is in-memory (':memory:'), i.e. not saved on disk, making it impossible to skip migrations to quickly re-run tests with '--keepdb' argument.
# # Copyright (c) 2015 Red Hat # Licensed under The MIT License (MIT) # http://opensource.org/licenses/MIT # """ Extra Django settings for test environment of pdc project. """ from settings import * # Database settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'test.sqlite3', 'TEST': {'NAME': 'test.sqlite3'}, } } # disable PERMISSION while testing REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'pdc.apps.auth.authentication.TokenAuthenticationWithChangeSet', 'rest_framework.authentication.SessionAuthentication', ), # 'DEFAULT_PERMISSION_CLASSES': [ # 'rest_framework.permissions.DjangoModelPermissions' # ], 'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend', 'pdc.apps.utils.utils.RelatedNestedOrderingFilter'), 'DEFAULT_METADATA_CLASS': 'contrib.bulk_operations.metadata.BulkMetadata', 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', 'pdc.apps.common.renderers.ReadOnlyBrowsableAPIRenderer', ), 'EXCEPTION_HANDLER': 'pdc.apps.common.handlers.exception_handler', 'DEFAULT_PAGINATION_CLASS': 'pdc.apps.common.pagination.AutoDetectedPageNumberPagination', 'NON_FIELD_ERRORS_KEY': 'detail', } COMPONENT_BRANCH_NAME_BLACKLIST_REGEX = r'^epel\d+$'
# # Copyright (c) 2015 Red Hat # Licensed under The MIT License (MIT) # http://opensource.org/licenses/MIT # """ Extra Django settings for test environment of pdc project. """ from settings import * # Database settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'test.sqlite3', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } # disable PERMISSION while testing REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'pdc.apps.auth.authentication.TokenAuthenticationWithChangeSet', 'rest_framework.authentication.SessionAuthentication', ), # 'DEFAULT_PERMISSION_CLASSES': [ # 'rest_framework.permissions.DjangoModelPermissions' # ], 'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend', 'pdc.apps.utils.utils.RelatedNestedOrderingFilter'), 'DEFAULT_METADATA_CLASS': 'contrib.bulk_operations.metadata.BulkMetadata', 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', 'pdc.apps.common.renderers.ReadOnlyBrowsableAPIRenderer', ), 'EXCEPTION_HANDLER': 'pdc.apps.common.handlers.exception_handler', 'DEFAULT_PAGINATION_CLASS': 'pdc.apps.common.pagination.AutoDetectedPageNumberPagination', 'NON_FIELD_ERRORS_KEY': 'detail', } COMPONENT_BRANCH_NAME_BLACKLIST_REGEX = r'^epel\d+$'
Fix challengeTypes object incorrect key names
window.common = (function({ common = { init: [] } }) { common.init.push(function($) { $('#report-issue').on('click', function() { var textMessage = [ 'Challenge [', (common.challengeName || window.location.pathname), '](', window.location.href, ') has an issue.\n', 'User Agent is: <code>', navigator.userAgent, '</code>.\n', 'Please describe how to reproduce this issue, and include ', 'links to screenshots if possible.\n\n' ].join(''); if ( common.editor && typeof common.editor.getValue === 'function' && common.editor.getValue().trim() ) { var type; switch (common.challengeType) { case common.challengeTypes.HTML: type = 'html'; break; case common.challengeTypes.JS: case common.challengeTypes.BONFIRE: type = 'javascript'; break; default: type = ''; } textMessage += [ 'My code:\n```', type, '\n', common.editor.getValue(), '\n```\n\n' ].join(''); } textMessage = encodeURIComponent(textMessage); $('#issue-modal').modal('hide'); window.open( 'https://github.com/freecodecamp/freecodecamp/issues/new?&body=' + textMessage, '_blank' ); }); }); return common; }(window));
window.common = (function({ common = { init: [] } }) { common.init.push(function($) { $('#report-issue').on('click', function() { var textMessage = [ 'Challenge [', (common.challengeName || window.location.pathname), '](', window.location.href, ') has an issue.\n', 'User Agent is: <code>', navigator.userAgent, '</code>.\n', 'Please describe how to reproduce this issue, and include ', 'links to screenshots if possible.\n\n' ].join(''); if ( common.editor && typeof common.editor.getValue === 'function' && common.editor.getValue().trim() ) { var type; switch (common.challengeType) { case common.challengeTypes.html: type = 'html'; break; case common.challengeTypes.js: case common.challengeTypes.bonfire: type = 'javascript'; break; default: type = ''; } textMessage += [ 'My code:\n```', type, '\n', common.editor.getValue(), '\n```\n\n' ].join(''); } textMessage = encodeURIComponent(textMessage); $('#issue-modal').modal('hide'); window.open( 'https://github.com/freecodecamp/freecodecamp/issues/new?&body=' + textMessage, '_blank' ); }); }); return common; }(window));
Fix passing the search_term parameter to Searcher
""" grep_redone, version 0.9 Search files for a pattern or string, optionally do this recursively. usage: grep_redone [-rnfe] [SEARCH_TERM] Arguments: SEARCH_TERM The string to search for. Options: -h --help Display this page. -r Do a recursive search. -f Display full/absolute paths. -e Use the search term as a regex pattern. -n Display line numbers for matches. """ import os from docopt import docopt import grep as grep_ def main(): """Entry point for grep_redone.""" try: args = docopt(__doc__) search_term = args['SEARCH_TERM'] if args['SEARCH_TERM'] else [""] searcher = grep_.Searcher( caller_dir=os.path.abspath(os.path.curdir), search_term=search_term, is_recursive=args['-r'], is_abs_path=args['-f'], is_regex_pattern=args['-e'], is_search_line_by_line=args['-n'] ) searcher.run() except KeyboardInterrupt: pass if __name__ == "__main__": main()
""" grep_redone, version 0.9 Search files for a pattern or string, optionally do this recursively. usage: grep_redone [-rnfe] [SEARCH_TERM] Arguments: SEARCH_TERM The string to search for. Options: -h --help Display this page. -r Do a recursive search. -f Display full/absolute paths. -e Use the search term as a regex pattern. -n Display line numbers for matches. """ import os from docopt import docopt import grep as grep_ def main(): """Entry point for grep_redone.""" try: args = docopt(__doc__) search_term = args['SEARCH_TERM'] if args['SEARCH_TERM'] else [""] searcher = grep_.Searcher( caller_dir=os.path.abspath(os.path.curdir), search_term=search_term[0], is_recursive=args['-r'], is_abs_path=args['-f'], is_regex_pattern=args['-e'], is_search_line_by_line=args['-n'] ) searcher.run() except KeyboardInterrupt: pass if __name__ == "__main__": main()
Revert "Remove Sf4.2 deprecation on TreeBuilder constructor" This reverts commit 803a5a2bcfa827db60f2bd0b55f144aa896adfb5.
<?php namespace AlterPHP\EasyAdminExtensionBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files. * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/configuration.html} */ class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('easy_admin_extension'); $rootNode ->children() ->arrayNode('custom_form_types') ->useAttributeAsKey('short_name') ->prototype('scalar') ->validate() ->ifTrue(function ($v) { return !\class_exists($v); }) ->thenInvalid('Class %s for custom type does not exist !') ->end() ->end() ->end() ->scalarNode('minimum_role') ->defaultNull() ->end() ->arrayNode('embedded_list') ->addDefaultsIfNotSet() ->children() ->booleanNode('open_new_tab') ->defaultTrue() ->end() ->end() ->end() ->end() ; return $treeBuilder; } }
<?php namespace AlterPHP\EasyAdminExtensionBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files. * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/configuration.html} */ class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder('easy_admin_extension'); $treeBuilder ->getRootNode() ->children() ->arrayNode('custom_form_types') ->useAttributeAsKey('short_name') ->prototype('scalar') ->validate() ->ifTrue(function ($v) { return !\class_exists($v); }) ->thenInvalid('Class %s for custom type does not exist !') ->end() ->end() ->end() ->scalarNode('minimum_role') ->defaultNull() ->end() ->arrayNode('embedded_list') ->addDefaultsIfNotSet() ->children() ->booleanNode('open_new_tab') ->defaultTrue() ->end() ->end() ->end() ->end() ; return $treeBuilder; } }
Change libraryTarget to UMD, remove add-module-export plugin
var path = require('path'); var webpack = require('webpack'); module.exports = { regular: { devtool: 'source-map', output: { filename: 'meyda.js', library: 'Meyda', libraryTarget: 'umd' }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', options: { presets: [['es2015', {modules: false}]] } } ] } }, minified: { devtool: 'source-map', output: { filename: 'meyda.min.js', sourceMapFilename: 'meyda.min.map', library: 'Meyda', libraryTarget: 'umd' }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', options: { presets: [['es2015', {modules: false}]] } } ] }, plugins: [ new webpack.optimize.UglifyJsPlugin({ compress: { warnings: true, drop_console: false }, sourceMap: true }) ] } };
var path = require('path'); var webpack = require('webpack'); module.exports = { regular: { devtool: 'source-map', output: { filename: 'meyda.js', library: 'Meyda', libraryTarget: 'var' }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', options: { presets: ['es2015'], plugins: [ 'add-module-exports' ] } } ] } }, minified: { devtool: 'source-map', output: { filename: 'meyda.min.js', sourceMapFilename: 'meyda.min.map', library: 'Meyda', libraryTarget: 'var' }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', options: { presets: ['es2015'], plugins: [ 'add-module-exports' ] } } ] }, plugins: [ new webpack.optimize.UglifyJsPlugin({ compress: { warnings: true, drop_console: false }, sourceMap: true }) ] } };
Fix tab-complete when having many arenas
package xyz.upperlevel.uppercore.arena.command; import xyz.upperlevel.uppercore.arena.Arena; import xyz.upperlevel.uppercore.arena.ArenaManager; import xyz.upperlevel.uppercore.command.functional.parameter.ParameterHandler; import java.util.Collections; import java.util.stream.Collectors; public final class ArenaParameterHandler { private ArenaParameterHandler() { } public static void register() { ParameterHandler.register( Collections.singletonList(Arena.class), args -> { Arena arena = ArenaManager.get().get(args.take()); if (arena == null) { throw args.areWrong(); } return arena; }, args -> { if (args.remaining() > 1) return Collections.emptyList(); String arenaName = args.take(); return ArenaManager.get().getArenas() .stream() .filter(arena -> arena.getId().startsWith(arenaName)) .map(Arena::getId) .collect(Collectors.toList()); }); } }
package xyz.upperlevel.uppercore.arena.command; import xyz.upperlevel.uppercore.arena.Arena; import xyz.upperlevel.uppercore.arena.ArenaManager; import xyz.upperlevel.uppercore.command.functional.parameter.ParameterHandler; import xyz.upperlevel.uppercore.command.functional.parameter.ParameterParseException; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Queue; import java.util.stream.Collectors; public final class ArenaParameterHandler { private ArenaParameterHandler() { } public static void register() { ParameterHandler.register( Collections.singletonList(Arena.class), args -> { Arena arena = ArenaManager.get().get(args.take()); if (arena == null) { throw args.areWrong(); } return arena; }, args -> { if (args.remaining() > 1) return Collections.emptyList(); return ArenaManager.get().getArenas() .stream() .filter(arena -> arena.getId().startsWith(args.take())) .map(Arena::getId) .collect(Collectors.toList()); }); } }
Use the "ELLIPSIS"-Character instead of dots
angular.module('truncate', []) .filter('characters', function () { return function (input, chars, breakOnWord) { if (isNaN(chars)) return input; if (chars <= 0) return ''; if (input && input.length >= chars) { input = input.substring(0, chars); if (!breakOnWord) { var lastspace = input.lastIndexOf(' '); //get last space if (lastspace !== -1) { input = input.substr(0, lastspace); } }else{ while(input.charAt(input.length-1) == ' '){ input = input.substr(0, input.length -1); } } return input + '…'; } return input; }; }) .filter('words', function () { return function (input, words) { if (isNaN(words)) return input; if (words <= 0) return ''; if (input) { var inputWords = input.split(/\s+/); if (inputWords.length > words) { input = inputWords.slice(0, words).join(' ') + '…'; } } return input; }; });
angular.module('truncate', []) .filter('characters', function () { return function (input, chars, breakOnWord) { if (isNaN(chars)) return input; if (chars <= 0) return ''; if (input && input.length >= chars) { input = input.substring(0, chars); if (!breakOnWord) { var lastspace = input.lastIndexOf(' '); //get last space if (lastspace !== -1) { input = input.substr(0, lastspace); } }else{ while(input.charAt(input.length-1) == ' '){ input = input.substr(0, input.length -1); } } return input + '...'; } return input; }; }) .filter('words', function () { return function (input, words) { if (isNaN(words)) return input; if (words <= 0) return ''; if (input) { var inputWords = input.split(/\s+/); if (inputWords.length > words) { input = inputWords.slice(0, words).join(' ') + '...'; } } return input; }; });
Fix for /whoami with a user who doesn't have a profile picture && should be ||
<?php /* * This file is part of the TelegramBot package. * * (c) Avtandil Kikabidze aka LONGMAN <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Longman\TelegramBot\Entities; use Longman\TelegramBot\Exception\TelegramException; class UserProfilePhotos extends Entity { protected $total_count; protected $photos; public function __construct(array $data) { $this->total_count = isset($data['total_count']) ? $data['total_count'] : null; if ($this->total_count === null || !is_numeric($this->total_count)) { throw new TelegramException('total_count is empty!'); } $this->photos = isset($data['photos']) ? $data['photos'] : null; if ($this->photos === null || !is_array($data['photos'])) { throw new TelegramException('photos is empty!'); } $photos = []; foreach ($this->photos as $key => $photo) { if (is_array($photo)) { foreach ($photo as $photo_size) { $photos[$key][] = new PhotoSize($photo_size); } } else { throw new TelegramException('photo is not an array!'); } } $this->photos = $photos; } public function getTotalCount() { return $this->total_count; } public function getPhotos() { return $this->photos; } }
<?php /* * This file is part of the TelegramBot package. * * (c) Avtandil Kikabidze aka LONGMAN <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Longman\TelegramBot\Entities; use Longman\TelegramBot\Exception\TelegramException; class UserProfilePhotos extends Entity { protected $total_count; protected $photos; public function __construct(array $data) { $this->total_count = isset($data['total_count']) ? $data['total_count'] : null; if ($this->total_count === null && !is_numeric($this->total_count)) { throw new TelegramException('total_count is empty!'); } $this->photos = isset($data['photos']) ? $data['photos'] : null; if ($this->photos === null || !is_array($data['photos'])) { throw new TelegramException('photos is empty!'); } $photos = []; foreach ($this->photos as $key => $photo) { if (is_array($photo)) { foreach ($photo as $photo_size) { $photos[$key][] = new PhotoSize($photo_size); } } else { throw new TelegramException('photo is not an array!'); } } $this->photos = $photos; } public function getTotalCount() { return $this->total_count; } public function getPhotos() { return $this->photos; } }
Add support for arbitrary user actions on marking
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals from __future__ import division from functools import wraps from django.db import transaction from django.http import Http404 from django.contrib.flatpages.views import flatpage def render_flatpage(url): def fn(request, *args, **kwargs): return flatpage(request, url) return fn def mark_user(attr, extra_block=None): def outer_decorator(view_fn): @wraps(view_fn) @transaction.atomic def wrapper(request, *args, **kwargs): user = request.user if user.is_authenticated() and not getattr(user, attr): setattr(user, attr, True) user.save() should_trigger_extra_block = True else: should_trigger_extra_block = False ctx = view_fn(request, *args, **kwargs) # in case the extra block does things that don't # work well with database transactions (like email) # postpone it to the end of the transaction block # to avoid cases in which an email is sent but the # transaction is rolled back due to a later exception if extra_block and should_trigger_extra_block: extra_block(user) return ctx return wrapper return outer_decorator def require_visitability(step): def outer_decorator(view_fn): @wraps(view_fn) @transaction.atomic def wrapper(request, *args, **kwargs): if not step.is_visitable(request.user): raise Http404() else: return view_fn(request, *args, **kwargs) return wrapper return outer_decorator
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals from __future__ import division from functools import wraps from django.db import transaction from django.http import Http404 from django.contrib.flatpages.views import flatpage def render_flatpage(url): def fn(request, *args, **kwargs): return flatpage(request, url) return fn def mark_user(attr): def outer_decorator(view_fn): @wraps(view_fn) @transaction.atomic def wrapper(request, *args, **kwargs): user = request.user if user.is_authenticated() and not getattr(user, attr): setattr(user, attr, True) user.save() ctx = view_fn(request, *args, **kwargs) return ctx return wrapper return outer_decorator def require_visitability(step): def outer_decorator(view_fn): @wraps(view_fn) @transaction.atomic def wrapper(request, *args, **kwargs): if not step.is_visitable(request.user): raise Http404() else: return view_fn(request, *args, **kwargs) return wrapper return outer_decorator
Add question desciption for valid parentheses
""" Source : https://oj.leetcode.com/problems/valid-parentheses/ Author : Changxi Wu Date : 2015-01-20 Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. """ def isValid( s): if not s: return False stack = [] map = {'(':')', '[':']', '{':'}'} for c in s: if c in map.keys(): stack.append(c) else: if len(stack) > 0: top = stack.pop() if map[top] != c: return False else: return False if len(stack) == 0: return True else: return False if __name__ == '__main__': test_list = ['','(){}[]','({})','(',')',')(','()','([)]','([{])}'] result_list = [0, 1, 1, 0, 0, 0, 1, 0, 0] success = True for i, s in enumerate(test_list): result = isValid(s) if result != result_list[i]: success = False print s print 'Expected value %d' % result_list[i] print 'Actual value %d' % result if success: print 'All the tests passed' else: print 'Please fix the failed test'
def isValid( s): if not s: return False stack = [] map = {'(':')', '[':']', '{':'}'} for c in s: if c in map.keys(): stack.append(c) else: if len(stack) > 0: top = stack.pop() if map[top] != c: return False else: return False if len(stack) == 0: return True else: return False if __name__ == '__main__': test_list = ['','(){}[]','({})','(',')',')(','()','([)]','([{])}'] result_list = [0, 1, 1, 0, 0, 0, 1, 0, 0] success = True for i, s in enumerate(test_list): result = isValid(s) if result != result_list[i]: success = False print s print 'Expected value %d' % result_list[i] print 'Actual value %d' % result if success: print 'All the tests passed' else: print 'Please fix the failed test'
Fix an bug into the id generation for a score record.
(function(){ angular .module("movieMash") .factory("scoreService",scoreService); scoreService.$inject=['localStorageService','$firebaseArray','firebaseDataService']; function scoreService(localStorageService,$firebaseArray,firebaseDataService){ var scoresSyncArray = $firebaseArray(firebaseDataService.scores); var service={ getAllScores:getAllScores, addPointToMovie:addPointToMovie, removePointToMovie:removePointToMovie }; return service; function getAllScores(){ return scoresSyncArray; } function addPointToMovie(movie){ var movieObj = scoresSyncArray.$getRecord(movie.id); if(movieObj){ movieObj.points ++; scoresSyncArray.$save({movieObj}); }else{ scoresSyncArray.$ref().child(movie.id).set({ movie:movie, points:1 }); } } function removePointToMovie(movie){ var points = localStorageService.get(movie.id) ? localStorageService.get(movie.id).points : 0; points --; localStorageService.set(movie.id,{movie:movie,points:points}); } } })();
(function(){ angular .module("movieMash") .factory("scoreService",scoreService); scoreService.$inject=['localStorageService','$firebaseArray','firebaseDataService']; function scoreService(localStorageService,$firebaseArray,firebaseDataService){ var scoresSyncArray = $firebaseArray(firebaseDataService.scores); var service={ getAllScores:getAllScores, addPointToMovie:addPointToMovie, removePointToMovie:removePointToMovie }; return service; function getAllScores(){ return scoresSyncArray; } function addPointToMovie(movie){ var movieObj = scoresSyncArray.$getRecord(movie.id); if(movieObj){ movieObj.points ++; scoresSyncArray.$save({movieObj}); }else{ scoresSyncArray.$add({ $id:movie.id, movie:movie, points:1 }); } } function removePointToMovie(movie){ var points = localStorageService.get(movie.id) ? localStorageService.get(movie.id).points : 0; points --; localStorageService.set(movie.id,{movie:movie,points:points}); } } })();
Update docblocks in Service Provider
<?php /** * @author Ben Rowe <[email protected]> * @license http://www.opensource.org/licenses/mit-license.html MIT License */ namespace Benrowe\Laravel\Config; use Illuminate\Support\ServiceProvider; /** * Service Provider for Config * * @package Benrowe\Laravel\Config; */ class ServiceProvider extends ServiceProvider { protected $defer = false; /** * Boot the configuration component * * @return nil */ public function boot() { $configPath = __DIR__ . '/../config/config.php'; $this->publishes([ $configPath => $this->getConfigPath(), ], 'config'); } /** * Register an instance of the component * * @return void */ public function register() { $this->app->singleton('config', function () { return new Config(); }); } /** * Define the services this provider will build & provide * * @return array */ public function provides() { return [ 'Benrowe\Laravel\Config\Config', 'config' ]; } /** * Get the configuration destination path * * @return string */ protected function getConfigPath() { return config_path('config.php'); } }
<?php /** * @author Ben Rowe <[email protected]> * @license http://www.opensource.org/licenses/mit-license.html MIT License */ namespace Benrowe\Laravel\Config; use Illuminate\Support\ServiceProvider; /** * Service Provider for Config * * @package Benrowe\Laravel\Config; */ class ServiceProvider extends ServiceProvider { protected $defer = false; /** * Boot the configuration component * * @return nil */ public function boot() { $configPath = __DIR__ . '/../config/config.php'; $this->publishes([ $configPath => $this->getConfigPath(), ], 'config'); } /** * Register an instance of the component * * @return [type] [description] */ public function register() { $this->app->singleton('config', function () { return new Config(); }); } /** * * * @return */ public function provides() { return [ 'Benrowe\Laravel\Config\Config', 'config' ]; } /** * Get the configuration destination path * * @return string */ protected function getConfigPath() { return config_path('config.php'); } }
Test db instead of memory db
from setuptools import setup from distutils.core import Command class TestCommand(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): from django.conf import settings settings.configure( DATABASES={ 'default': { 'NAME': 'test.db', 'ENGINE': 'django.db.backends.sqlite3' } }, INSTALLED_APPS=('bakery',) ) from django.core.management import call_command import django if django.VERSION[:2] >= (1, 7): django.setup() call_command('test', 'bakery') setup( name='django-bakery', version='0.7.1', description='A set of helpers for baking your Django site out as flat files', author='The Los Angeles Times Data Desk', author_email='[email protected]', url='http://www.github.com/datadesk/django-bakery/', classifiers=[ 'Programming Language :: Python', 'Programming Language :: Python :: 3' ], install_requires=[ 'six==1.5.2', 'boto==2.28', ], cmdclass={'test': TestCommand} )
from setuptools import setup from distutils.core import Command class TestCommand(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): from django.conf import settings settings.configure( DATABASES={ 'default': { 'NAME': ':memory:', 'ENGINE': 'django.db.backends.sqlite3' } }, INSTALLED_APPS=('bakery',) ) from django.core.management import call_command import django if django.VERSION[:2] >= (1, 7): django.setup() call_command('test', 'bakery') setup( name='django-bakery', version='0.7.1', description='A set of helpers for baking your Django site out as flat files', author='The Los Angeles Times Data Desk', author_email='[email protected]', url='http://www.github.com/datadesk/django-bakery/', classifiers=[ 'Programming Language :: Python', 'Programming Language :: Python :: 3' ], install_requires=[ 'six==1.5.2', 'boto==2.28', ], cmdclass={'test': TestCommand} )
Store references to albums, add new methods.
from BaseIndexEntry import BaseIndexEntry class PerformerIndexEntry(BaseIndexEntry): '''A class to hold index data for performers. Performers have titles and albums. ''' def __init__(self, name, titles, number): super(PerformerIndexEntry, self).__init__(name, titles, number) # Set the performer number on each of the titles for title in self._titles: title.performer_number = self._number # To be set later self._albums = [] self._album_numbers = [] self._albums_initialised = False self._freeze() def __str__(self): return '{}: {} {}, albums: {} {}, titles: {}'.format( self.__class__.__name__, self._number, self._name, self.number_of_albums, self._album_numbers, self.number_of_titles) def init_albums(self, albums): for title in self._titles: if title.album_number not in self._album_numbers: self._album_numbers.append(title.album_number) self._albums.append(albums[title.album_number]) self._albums_initialised = True @property def album_numbers(self): if self._albums_initialised: return self._album_numbers else: raise Exception("Albums not initialised.") @property def number_of_albums(self): if self._albums_initialised: return len(self._album_numbers) else: raise Exception("Albums not initialised.") def album(self, album_number): for a in self._albums: if a.number == album_number: return a return None def number_of_titles_for_album(self, album_number): count = set() for title in self._titles: if title.album_number == album_number: count.add(title.index) return len(count)
from BaseIndexEntry import BaseIndexEntry class PerformerIndexEntry(BaseIndexEntry): def __init__(self, name, titles, number): super(PerformerIndexEntry, self).__init__(name, titles, number) # Set the performer number on each of the titles for title in self._titles: title.performer_number = self._number # To be set later self._albums = [] self._albums_initialised = False self._freeze() def __str__(self): return '{}: {} {}, albums: {} {}, titles: {}'.format( self.__class__.__name__, self._number, self._name, self.number_of_albums, self._albums, self.number_of_titles) def init_albums(self): for title in self._titles: if title.album_number not in self._albums: self._albums.append(title.album_number) self._albums_initialised = True @property def albums(self): if self._albums_initialised: return self._albums else: raise Exception("Albums not initialised.") @property def number_of_albums(self): return len(self._albums)
Switch unit test stubs to sinon-chrome-webextensions.min.js
const reporters = ['mocha', 'coverage'] if (process.env.COVERALLS_REPO_TOKEN) { reporters.push('coveralls') } module.exports = function (config) { config.set({ singleRun: true, browsers: ['Firefox'], frameworks: ['mocha'], reporters, coverageReporter: { dir: 'build/coverage', reporters: [ { type: 'lcov', subdir: 'lcov' }, { type: 'html', subdir (browser) { // normalization process to keep a consistent browser name // across different OS return browser.toLowerCase().split(/[ /-]/)[0] } }, {type: 'text-summary'} ] }, files: [ 'node_modules/sinon/pkg/sinon.js', 'node_modules/sinon-chrome/bundle/sinon-chrome-webextensions.min.js', 'ext/src/background/*.js', 'test/unit/*.test.js' ], preprocessors: {'ext/**/*.js': ['coverage']}, plugins: [ 'karma-coveralls', 'karma-coverage', 'karma-firefox-launcher', 'karma-mocha', 'karma-mocha-reporter' ] }) }
const reporters = ['mocha', 'coverage'] if (process.env.COVERALLS_REPO_TOKEN) { reporters.push('coveralls') } module.exports = function (config) { config.set({ singleRun: true, browsers: ['Firefox'], frameworks: ['mocha'], reporters, coverageReporter: { dir: 'build/coverage', reporters: [ { type: 'lcov', subdir: 'lcov' }, { type: 'html', subdir (browser) { // normalization process to keep a consistent browser name // across different OS return browser.toLowerCase().split(/[ /-]/)[0] } }, {type: 'text-summary'} ] }, files: [ 'node_modules/sinon/pkg/sinon.js', 'node_modules/sinon-chrome/dist/sinon-chrome.latest.js', 'ext/src/background/*.js', 'test/unit/*.test.js' ], preprocessors: {'ext/**/*.js': ['coverage']}, plugins: [ 'karma-coveralls', 'karma-coverage', 'karma-firefox-launcher', 'karma-mocha', 'karma-mocha-reporter' ] }) }
Add 'name' option to Printer object, to specify the 'printer_name' argument sent to the client.
openerp.printer_proxy = function (instance) { instance.printer_proxy = {}; instance.printer_proxy.Printer = instance.web.Class.extend({ init: function(options){ options = options || {}; this.name = options.name || 'zebra_python_unittest'; this.connection = new instance.web.JsonRPC(); this.connection.setup(options.url || 'http://localhost:8069'); this.notifications = {}; }, // Makes a JSON-RPC call to the local OpenERP server. message : function(name,params){ var ret = new $.Deferred(); var callbacks = this.notifications[name] || []; for(var i = 0; i < callbacks.length; i++){ callbacks[i](params); } this.connection.rpc('/printer_proxy/' + name, params || {}).done(function(result) { ret.resolve(result); }).fail(function(error) { ret.reject(error); }); return ret; }, // Allows triggers to be set for when particular JSON-RPC function calls are made via 'message.' add_notification: function(name, callback){ if(!this.notifications[name]){ this.notifications[name] = []; } this.notifications[name].push(callback); }, // Convenience function for sending EPL commands to the local printer. print_epl: function (data) { return this.message("print_epl", {"printer_name": this.name, "data": data}); } }); };
openerp.printer_proxy = function (instance) { instance.printer_proxy = {}; instance.printer_proxy.Printer = instance.web.Class.extend({ init: function(options){ options = options || {}; this.connection = new instance.web.JsonRPC(); this.connection.setup(options.url || 'http://localhost:8069'); this.notifications = {}; }, // Makes a JSON-RPC call to the local OpenERP server. message : function(name,params){ var ret = new $.Deferred(); var callbacks = this.notifications[name] || []; for(var i = 0; i < callbacks.length; i++){ callbacks[i](params); } this.connection.rpc('/printer_proxy/' + name, params || {}).done(function(result) { ret.resolve(result); }).fail(function(error) { ret.reject(error); }); return ret; }, // Allows triggers to be set for when particular JSON-RPC function calls are made via 'message.' add_notification: function(name, callback){ if(!this.notifications[name]){ this.notifications[name] = []; } this.notifications[name].push(callback); }, // Convenience function for sending EPL commands to the local printer. print_epl: function (data) { return this.message("print_epl", {"data": data}); } }); };
Fix for zero depth path
import re import logging logger = logging.getLogger("Parsing") def create_node(data): tag_part = r"(?P<tag>\w+)" attr_part = r"(?P<q>\[(?P<attr>\w+)=(\"|\')(?P<val>.+?)(\"|\')\])?" selector_part = r"(\{(?P<selector>\d+)\})?" p = tag_part + attr_part + selector_part patt = re.compile(p) m = patt.match(data) tag = m.group("tag") if m.group("q"): q = {m.group("attr"): m.group("val")} else: q = None def selector(lst): s = m.group("selector") if s: sel = int(s) return [lst[sel]] if sel < len(lst) else [] else: return lst def node(root): return selector(root.findAll(tag, q)) return node def parse(key, paths, context): path = paths.pop() results = [] for node in context: for out in path(node): results.append(out) if len(paths) == 0: # End of line return [(key, result.text, result.attrs) for result in results] else: return parse(key, paths, results)
import re import logging logger = logging.getLogger("Parsing") def create_node(data): tag_part = r"(?P<tag>\w+)" attr_part = r"(?P<q>\[(?P<attr>\w+)=(\"|\')(?P<val>.+?)(\"|\')\])?" selector_part = r"(\{(?P<selector>\d+)\})?" p = tag_part + attr_part + selector_part patt = re.compile(p) m = patt.match(data) tag = m.group("tag") if m.group("q"): q = {m.group("attr"): m.group("val")} else: q = None def selector(lst): s = m.group("selector") if s: sel = int(s) return [lst[sel]] if sel < len(lst) else [] else: return lst def node(root): return selector(root.findAll(tag, q)) return node def parse(key, paths, context): path = paths.pop() results = [] if len(paths) == 0: # End of line return [(key, result.text, result.attrs) for result in context] else: for node in context: for out in path(node): results.append(out) return parse(key, paths, results)
Check if the model is empty first in collection relationship
<?php namespace EGALL\Transformer\Relationships; use EGALL\Transformer\Relationship; /** * ModelToCollectionRelationship Class * * @package EGALL\Transformer\Relationships * @author Erik Galloway <[email protected]> */ class ModelToCollectionRelationship extends Relationship { /** * Transform a model to collection relationship. * * @return array */ public function transform() { $model = $this->item->{$this->key}; if (!$model->isEmpty() && $this->isTransformable($model->first())) { return $this->transformCollection($model); } return $this->collectionToArray($model); } /** * Map a collection calling toArray() on each item. * * @param $model * @return array */ protected function collectionToArray($model) { return $model->map(function($item) { return $item->toArray(); })->toArray(); } /** * Transform a transformable collection. * * @param $model * @return array */ protected function transformCollection($model) { return $model->map(function($child) { if ($this->child) { return $child->transformer(true)->with($this->child)->transform(); } return $child->transform(); })->toArray(); } }
<?php namespace EGALL\Transformer\Relationships; use EGALL\Transformer\Relationship; /** * ModelToCollectionRelationship Class * * @package EGALL\Transformer\Relationships * @author Erik Galloway <[email protected]> */ class ModelToCollectionRelationship extends Relationship { /** * Transform a model to collection relationship. * * @return array */ public function transform() { $model = $this->item->{$this->key}; if ($this->isTransformable($model->first())) { return $this->transformCollection($model); } return $this->collectionToArray($model); } /** * Map a collection calling toArray() on each item. * * @param $model * @return array */ protected function collectionToArray($model) { return $model->map(function($item) { return $item->toArray(); })->toArray(); } /** * Transform a transformable collection. * * @param $model * @return array */ protected function transformCollection($model) { return $model->map(function($child) { if ($this->child) { return $child->transformer(true)->with($this->child)->transform(); } return $child->transform(); })->toArray(); } }
Fix bug in OboSerializer` causing `Ontology.dump` to crash
import io from typing import BinaryIO, ClassVar from ._fastobo import FastoboSerializer from .base import BaseSerializer class OboSerializer(FastoboSerializer, BaseSerializer): format = "obo" def dump(self, file): writer = io.TextIOWrapper(file) try: # dump the header if self.ont.metadata: header = self._to_header_frame(self.ont.metadata) file.write(str(header).encode("utf-8")) if self.ont._terms or self.ont._relationships: file.write(b"\n") # dump terms if self.ont._terms: for i, (id, data) in enumerate(self.ont._terms.items()): frame = self._to_term_frame(data) file.write(str(frame).encode("utf-8")) if i < len(self.ont._terms) - 1 or self.ont._relationships: file.write(b"\n") # dump typedefs if self.ont._relationships: for i, (id, data) in enumerate(self.ont._relationships.items()): frame = self._to_typedef_frame(data) file.write(str(frame).encode("utf-8")) if i < len(self.ont._relationships) - 1: file.write(b"\n") finally: writer.detach()
import io from typing import BinaryIO, ClassVar from ._fastobo import FastoboSerializer from .base import BaseSerializer class OboSerializer(FastoboSerializer, BaseSerializer): format = "obo" def dump(self, file): writer = io.TextIOWrapper(file) try: # dump the header if self.ont.metadata: header = self._to_header_frame(self.ont.metadata) file.write(str(header).encode("utf-8")) if self.ont._terms or self.ont._typedefs: file.write(b"\n") # dump terms if self.ont._terms: for i, (id, data) in enumerate(self.ont._terms.items()): frame = self._to_term_frame(data) file.write(str(frame).encode("utf-8")) if i < len(self.ont._terms) - 1 or self.ont._relationships: file.write(b"\n") # dump typedefs if self.ont._relationships: for i, (id, data) in enumerate(self.ont._relationships.items()): frame = self._to_typedef_frame(data) file.write(str(frame).encode("utf-8")) if i < len(self.ont._relationships) - 1: file.write(b"\n") finally: writer.detach()
Throw exception right away if it happen to avoid repeatedly throwing exceptions.
package uk.ac.ebi.ddi.extservices.net; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class FtpUtils { private static final Logger LOGGER = LoggerFactory.getLogger(FtpUtils.class); public static List<String> getListFiles(FTPClient client, String path, String... ignoreDir) throws IOException { List<String> result = new ArrayList<>(); for (String dir : ignoreDir) { if (path.equals(dir)) { return result; } } if (!client.changeWorkingDirectory(path)) { return Collections.emptyList(); } FTPFile[] ftpFiles = client.listFiles(); for (FTPFile file : ftpFiles) { if (!file.getName().equals(".") && !file.getName().equals("..")) { if (file.isDirectory()) { result.addAll(getListFiles(client, file.getName(), ignoreDir)); } else { String link = String.format("%s/%s", client.printWorkingDirectory(), file.getName()); result.add(link); } } } client.changeToParentDirectory(); return result; } }
package uk.ac.ebi.ddi.extservices.net; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class FtpUtils { private static final Logger LOGGER = LoggerFactory.getLogger(FtpUtils.class); public static List<String> getListFiles(FTPClient client, String path, String... ignoreDir) { List<String> result = new ArrayList<>(); for (String dir : ignoreDir) { if (path.equals(dir)) { return result; } } try { if (!client.changeWorkingDirectory(path)) { return Collections.emptyList(); } FTPFile[] ftpFiles = client.listFiles(); for (FTPFile file : ftpFiles) { if (!file.getName().equals(".") && !file.getName().equals("..")) { if (file.isDirectory()) { result.addAll(getListFiles(client, file.getName(), ignoreDir)); } else { String link = String.format("%s/%s", client.printWorkingDirectory(), file.getName()); result.add(link); } } } client.changeToParentDirectory(); } catch (Exception e) { LOGGER.error("Exception occurred when listing ftp files of {}, ", path, e); } return result; } }
Fix a premature import when patching SQLite compatibility. We provide a compatibility patch that fixes certain versions of SQLite with Django prior to 2.1.5. This patch made the assumption that it could import the Django SQLite backend at the module level, since SQLite is built into Python. However, on modern versions of Django, this will fail to import if the version of SQLite is too old. We now import this only if we're about to apply the patch, in which case we've already confirmed the compatible version range. Testing Done: Tested on reviews.reviewboard.org, where this problem was first encountered due to an older SQLite. We no longer hit a premature import. Reviewed at https://reviews.reviewboard.org/r/12414/
"""Patch to enable SQLite Legacy Alter Table support.""" from __future__ import unicode_literals import sqlite3 import django def needs_patch(): """Return whether the SQLite backend needs patching. It will need patching if using Django 1.11 through 2.1.4 while using SQLite3 v2.26. Returns: bool: ``True`` if the backend needs to be patched. ``False`` if it does not. """ return (sqlite3.sqlite_version_info > (2, 26, 0) and (1, 11) <= django.VERSION < (2, 1, 5)) def apply_patch(): """Apply a patch to the SQLite database backend. This will turn on SQLite's ``legacy_alter_table`` mode on when modifying the schema, which is needed in order to successfully allow Django to make table modifications. """ from django.db.backends.sqlite3.base import DatabaseWrapper class DatabaseSchemaEditor(DatabaseWrapper.SchemaEditorClass): def __enter__(self): with self.connection.cursor() as c: c.execute('PRAGMA legacy_alter_table = ON') return super(DatabaseSchemaEditor, self).__enter__() def __exit__(self, *args, **kwargs): super(DatabaseSchemaEditor, self).__exit__(*args, **kwargs) with self.connection.cursor() as c: c.execute('PRAGMA legacy_alter_table = OFF') DatabaseWrapper.SchemaEditorClass = DatabaseSchemaEditor
"""Patch to enable SQLite Legacy Alter Table support.""" from __future__ import unicode_literals import sqlite3 import django from django.db.backends.sqlite3.base import DatabaseWrapper def needs_patch(): """Return whether the SQLite backend needs patching. It will need patching if using Django 1.11 through 2.1.4 while using SQLite3 v2.26. Returns: bool: ``True`` if the backend needs to be patched. ``False`` if it does not. """ return (sqlite3.sqlite_version_info > (2, 26, 0) and (1, 11) <= django.VERSION < (2, 1, 5)) def apply_patch(): """Apply a patch to the SQLite database backend. This will turn on SQLite's ``legacy_alter_table`` mode on when modifying the schema, which is needed in order to successfully allow Django to make table modifications. """ class DatabaseSchemaEditor(DatabaseWrapper.SchemaEditorClass): def __enter__(self): with self.connection.cursor() as c: c.execute('PRAGMA legacy_alter_table = ON') return super(DatabaseSchemaEditor, self).__enter__() def __exit__(self, *args, **kwargs): super(DatabaseSchemaEditor, self).__exit__(*args, **kwargs) with self.connection.cursor() as c: c.execute('PRAGMA legacy_alter_table = OFF') DatabaseWrapper.SchemaEditorClass = DatabaseSchemaEditor
Check item.payload.docs is iterable before iterating
'use strict' class DocumentIndex { constructor () { this._index = {} } get (key, fullOp = false) { return fullOp ? this._index[key] : this._index[key] ? this._index[key].payload.value : null } updateIndex (oplog, onProgressCallback) { const reducer = (handled, item, idx) => { if (item.payload.op === 'PUTALL' && item.payload.docs[Symbol.iterator]) { for (const doc of item.payload.docs) { if (handled[doc.key] !== true) { handled[doc.key] = true this._index[doc.key] = { payload: { op: 'PUT', key: doc.key, value: doc.value } } } } } else if (handled[item.payload.key] !== true) { handled[item.payload.key] = true if (item.payload.op === 'PUT') { this._index[item.payload.key] = item } else if (item.payload.op === 'DEL') { delete this._index[item.payload.key] } } if (onProgressCallback) onProgressCallback(item, idx) return handled } oplog.values .slice() .reverse() .reduce(reducer, {}) } } module.exports = DocumentIndex
'use strict' class DocumentIndex { constructor () { this._index = {} } get (key, fullOp = false) { return fullOp ? this._index[key] : this._index[key] ? this._index[key].payload.value : null } updateIndex (oplog, onProgressCallback) { const reducer = (handled, item, idx) => { if (item.payload.op === 'PUTALL') { for (const doc of item.payload.docs) { if (handled[doc.key] !== true) { handled[doc.key] = true this._index[doc.key] = { payload: { op: 'PUT', key: doc.key, value: doc.value } } } } } else if (handled[item.payload.key] !== true) { handled[item.payload.key] = true if (item.payload.op === 'PUT') { this._index[item.payload.key] = item } else if (item.payload.op === 'DEL') { delete this._index[item.payload.key] } } if (onProgressCallback) onProgressCallback(item, idx) return handled } oplog.values .slice() .reverse() .reduce(reducer, {}) } } module.exports = DocumentIndex
Disable pseudo-tty to fix issues with Shipit and Docker
require('dotenv').config(); module.exports = shipit => { shipit.initConfig({ production: { servers: process.env.SHIPIT_PRODUCTION_SERVER, dir: process.env.SHIPIT_PRODUCTION_DIR, }, staging: { servers: process.env.SHIPIT_STAGING_SERVER, dir: process.env.SHIPIT_STAGING_DIR, }, }); const dockerApp = 'sudo docker-compose exec -T app '; function options() { return { cwd: shipit.config.dir }; } // Git shipit.blTask('pull', () => { return shipit.remote('git pull', options()); }); // JS shipit.blTask('install-js-deps', () => { return shipit.remote(dockerApp + 'yarn install', options()); }); shipit.blTask('build-js', ['install-js-deps'], () => { return shipit.remote(dockerApp + 'yarn run build', options()); }); shipit.blTask('deploy-js', [ 'pull', 'build-js', ]); // App shipit.blTask('restart-app', () => { return shipit.remote('sudo docker-compose restart app', options()); }); shipit.blTask('splatnet', () => { return shipit.remote(dockerApp + 'yarn splatnet', options()); }); // Combination Tasks shipit.blTask('deploy', [ 'pull', 'deploy-js', 'restart-app', ]); }
require('dotenv').config(); module.exports = shipit => { shipit.initConfig({ production: { servers: process.env.SHIPIT_PRODUCTION_SERVER, dir: process.env.SHIPIT_PRODUCTION_DIR, }, staging: { servers: process.env.SHIPIT_STAGING_SERVER, dir: process.env.SHIPIT_STAGING_DIR, }, }); const dockerApp = 'sudo docker-compose exec app '; function options() { return { cwd: shipit.config.dir }; } // Git shipit.blTask('pull', () => { return shipit.remote('git pull', options()); }); // JS shipit.blTask('install-js-deps', () => { return shipit.remote(dockerApp + 'yarn install', options()); }); shipit.blTask('build-js', ['install-js-deps'], () => { return shipit.remote(dockerApp + 'yarn run build', options()); }); shipit.blTask('deploy-js', [ 'pull', 'build-js', ]); // App shipit.blTask('restart-app', () => { return shipit.remote('sudo docker-compose restart app', options()); }); shipit.blTask('splatnet', () => { return shipit.remote(dockerApp + 'yarn splatnet', options()); }); // Combination Tasks shipit.blTask('deploy', [ 'pull', 'deploy-js', 'restart-app', ]); }
Fix JS error preventing newly created dictionary items from opening automatically (cherry picked from commit 59f90bd08be677817133584fc877f4a53a349359)
/** * @ngdoc controller * @name Umbraco.Editors.Dictionary.CreateController * @function * * @description * The controller for creating dictionary items */ function DictionaryCreateController($scope, $location, dictionaryResource, navigationService, notificationsService, formHelper, appState) { var vm = this; vm.itemKey = ""; vm.createItem = createItem; function createItem() { if (formHelper.submitForm({ scope: $scope, formCtrl: $scope.createDictionaryForm })) { var node = $scope.currentNode; dictionaryResource.create(node.id, vm.itemKey).then(function (data) { navigationService.hideMenu(); // set new item as active in tree var currPath = node.path ? node.path : "-1"; navigationService.syncTree({ tree: "dictionary", path: currPath + "," + data, forceReload: true, activate: true }); // reset form state formHelper.resetForm({ scope: $scope, formCtrl: $scope.createDictionaryForm }); // navigate to edit view var currentSection = appState.getSectionState("currentSection"); $location.path("/" + currentSection + "/dictionary/edit/" + data); }, function (err) { formHelper.resetForm({ scope: $scope, formCtrl: $scope.createDictionaryForm, hasErrors: true }); if (err.data && err.data.message) { notificationsService.error(err.data.message); navigationService.hideMenu(); } }); } } } angular.module("umbraco").controller("Umbraco.Editors.Dictionary.CreateController", DictionaryCreateController);
/** * @ngdoc controller * @name Umbraco.Editors.Dictionary.CreateController * @function * * @description * The controller for creating dictionary items */ function DictionaryCreateController($scope, $location, dictionaryResource, navigationService, notificationsService, formHelper, appState) { var vm = this; vm.itemKey = ""; vm.createItem = createItem; function createItem() { if (formHelper.submitForm({ scope: $scope, formCtrl: this.createDictionaryForm })) { var node = $scope.currentNode; dictionaryResource.create(node.id, vm.itemKey).then(function (data) { navigationService.hideMenu(); // set new item as active in tree var currPath = node.path ? node.path : "-1"; navigationService.syncTree({ tree: "dictionary", path: currPath + "," + data, forceReload: true, activate: true }); // reset form state formHelper.resetForm({ scope: $scope, formCtrl: this.createDictionaryForm }); // navigate to edit view var currentSection = appState.getSectionState("currentSection"); $location.path("/" + currentSection + "/dictionary/edit/" + data); }, function (err) { formHelper.resetForm({ scope: $scope, formCtrl: this.createDictionaryForm, hasErrors: true }); if (err.data && err.data.message) { notificationsService.error(err.data.message); navigationService.hideMenu(); } }); } } } angular.module("umbraco").controller("Umbraco.Editors.Dictionary.CreateController", DictionaryCreateController);
Add comment regarding Google account security
package org.linuxguy.MarketBot; import org.linuxguy.MarketBot.FlowdockNotifier.FlowdockNotificationType; public class MarketBot { public static void main(String[] args) throws InterruptedException { // This can be any valid Google account. For security reasons, I do NOT recommend using the same account // that you use to manage your app. String googlePlayUsername = "[email protected]"; String googlePlayPassword = "foo"; String groupMeBotId = "XYZPDQ"; String flowdockInboxId = "123456789"; String botName = "MarketBot"; final String androidPackage = "com.mycompany.MyApp"; GooglePlayWatcher playWatcher = new GooglePlayWatcher(googlePlayUsername, googlePlayPassword, androidPackage, "My Android App"); FlowdockNotifier flowdockNotifier = new FlowdockNotifier(botName, flowdockInboxId, FlowdockNotificationType.INBOX); playWatcher.addListener(flowdockNotifier); playWatcher.start(); // You can find this app ID in iTunes Connect String iOSAppId = "123456789"; AppStoreRSSWatcher appStoreWatcherUS = new AppStoreRSSWatcher("us", iOSAppId, "My iOS App"); appStoreWatcherUS.addListener(new GroupMeNotifier(groupMeBotId)); appStoreWatcherUS.start(); System.out.println("All pollers started"); // Keep running until the watchers get tired. (Never!) playWatcher.join(); appStoreWatcherUS.join(); } }
package org.linuxguy.MarketBot; import org.linuxguy.MarketBot.FlowdockNotifier.FlowdockNotificationType; public class MarketBot { public static void main(String[] args) throws InterruptedException { String googlePlayUsername = "[email protected]"; String googlePlayPassword = "foo"; String groupMeBotId = "XYZPDQ"; String flowdockInboxId = "123456789"; String botName = "MarketBot"; final String androidPackage = "com.mycompany.MyApp"; GooglePlayWatcher playWatcher = new GooglePlayWatcher(googlePlayUsername, googlePlayPassword, androidPackage, "My Android App"); FlowdockNotifier flowdockNotifier = new FlowdockNotifier(botName, flowdockInboxId, FlowdockNotificationType.INBOX); playWatcher.addListener(flowdockNotifier); playWatcher.start(); // You can find this app ID in iTunes Connect String iOSAppId = "123456789"; AppStoreRSSWatcher appStoreWatcherUS = new AppStoreRSSWatcher("us", iOSAppId, "My iOS App"); appStoreWatcherUS.addListener(new GroupMeNotifier(groupMeBotId)); appStoreWatcherUS.start(); System.out.println("All pollers started"); // Keep running until the watchers get tired. (Never!) playWatcher.join(); appStoreWatcherUS.join(); } }
[examples] Add link to jetty ssl example
package javalin.examples; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.util.ssl.SslContextFactory; import javalin.Javalin; import javalin.embeddedserver.EmbeddedServer; import javalin.embeddedserver.jetty.EmbeddedJettyFactory; public class HelloWorldSecure { // This is a very basic example, a better one can be found at: // https://github.com/eclipse/jetty.project/blob/jetty-9.4.x/examples/embedded/src/main/java/org/eclipse/jetty/embedded/LikeJettyXml.java#L139-L163 public static void main(String[] args) { Javalin.create() .embeddedServer(new EmbeddedJettyFactory(() -> { Server server = new Server(); ServerConnector sslConnector = new ServerConnector(server, getSslContextFactory()); sslConnector.setPort(443); ServerConnector connector = new ServerConnector(server); connector.setPort(80); server.setConnectors(new Connector[] {sslConnector, connector}); return server; })) .get("/", (req, res) -> res.body("Hello World")); // valid endpoint for both connectors } private static SslContextFactory getSslContextFactory() { SslContextFactory sslContextFactory = new SslContextFactory(); sslContextFactory.setKeyStorePath(EmbeddedServer.class.getResource("/keystore.jks").toExternalForm()); sslContextFactory.setKeyStorePassword("password"); return sslContextFactory; } }
package javalin.examples; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.util.ssl.SslContextFactory; import javalin.Javalin; import javalin.embeddedserver.EmbeddedServer; import javalin.embeddedserver.jetty.EmbeddedJettyFactory; public class HelloWorldSecure { public static void main(String[] args) { Javalin.create() .embeddedServer(new EmbeddedJettyFactory(() -> { Server server = new Server(); ServerConnector sslConnector = new ServerConnector(server, getSslContextFactory()); sslConnector.setPort(443); ServerConnector connector = new ServerConnector(server); connector.setPort(80); server.setConnectors(new Connector[] {sslConnector, connector}); return server; })) .get("/", (req, res) -> res.body("Hello World")); // valid endpoint for both connectors } private static SslContextFactory getSslContextFactory() { SslContextFactory sslContextFactory = new SslContextFactory(); sslContextFactory.setKeyStorePath(EmbeddedServer.class.getResource("/keystore.jks").toExternalForm()); sslContextFactory.setKeyStorePassword("password"); return sslContextFactory; } }
Fix future query problems (current users not affected either way) [skip ci]
<?php /** * 2016_06_16_000001_create_users_table.php * Copyright (C) 2016 [email protected] * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ declare(strict_types = 1); use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; /** * Class CreateUsersTable */ class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { if (!Schema::hasTable('users')) { Schema::create( 'users', function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->string('email', 255); $table->string('password', 60); $table->string('remember_token', 100)->nullable(); $table->string('reset', 32)->nullable(); $table->tinyInteger('blocked', false, true)->default('0'); $table->string('blocked_code', 25)->nullable(); } ); } } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('users'); } }
<?php /** * 2016_06_16_000001_create_users_table.php * Copyright (C) 2016 [email protected] * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ declare(strict_types = 1); use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; /** * Class CreateUsersTable */ class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { if (!Schema::hasTable('users')) { Schema::create( 'users', function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->string('email', 255); $table->string('password', 60); $table->string('remember_token', 100); $table->string('reset', 32)->nullable(); $table->tinyInteger('blocked', false, true)->default('0'); $table->string('blocked_code', 25)->nullable(); } ); } } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('users'); } }
Disable Good cause pm2 pukes
var hapi = require('hapi'); var moonboots = require('moonboots_hapi'); var config = require('getconfig'); var templatizer = require('templatizer'); //var Good = require('good'); var ElectricFence = require('electricfence'); var server = hapi.createServer(8080, 'localhost'); server.pack.register([ { plugin: moonboots, options: { appPath: '/{p*}', moonboots: { main: __dirname + '/client/app.js', developmentMode: config.isDev, stylesheets: [ __dirname + '/public/css/local.css', __dirname + '/public/css/bootstrap.css' ], beforeBuildJS: function () { templatizer(__dirname + '/templates', __dirname + '/client/templates.js'); } } } //}, { //plugin: Good, //options: { //reporters: [{ ////reporter: Good.GoodConsole //}] //} }, { plugin: ElectricFence, options: config.electricfence } ], function () { server.start(function () { server.log(['info'], 'lift.zone running on the year ' + server.info.port); }); });
var hapi = require('hapi'); var moonboots = require('moonboots_hapi'); var config = require('getconfig'); var templatizer = require('templatizer'); var Good = require('good'); var ElectricFence = require('electricfence'); var server = hapi.createServer(8080, 'localhost'); server.pack.register([ { plugin: moonboots, options: { appPath: '/{p*}', moonboots: { main: __dirname + '/client/app.js', developmentMode: config.isDev, stylesheets: [ __dirname + '/public/css/local.css', __dirname + '/public/css/bootstrap.css' ], beforeBuildJS: function () { templatizer(__dirname + '/templates', __dirname + '/client/templates.js'); } } } }, { plugin: Good, options: { reporters: [{ reporter: Good.GoodConsole }] } }, { plugin: ElectricFence, options: config.electricfence } ], function () { server.start(function () { server.log(['info'], 'lift.zone running on the year ' + server.info.port); }); });
Replace % with f-string :)
"""Module containing helper functions for using pygame.""" def load_class_assets(calling_object, assets_dict): """Load class assets. Only call if class_assets_loaded is False.""" calling_class = type(calling_object) for attribute_name in assets_dict: setattr(calling_class, attribute_name, assets_dict[attribute_name]) setattr(calling_class, "class_assets_loaded", True) def wrap_text(text, font, max_width): """ Returns an array of lines which can be blitted beneath each other in the given font in a box of the given maximum width. """ def wrap_paragraph(paragraph): """Wraps text that doesn't contain newlines.""" def too_long(string): return font.size(string)[0] > max_width def raise_word_too_long_error(word): raise ValueError(f"'{word}' is too long to be wrapped.") lines = [] words = paragraph.split() line = words.pop(0) if too_long(line): raise_word_too_long_error(line) for word in words: if too_long(word): raise_word_too_long_error(word) if too_long(" ".join((line, word))): lines.append(line) line = word else: line = " ".join((line, word)) lines.append(line) return lines paragraphs = text.split("\n") return sum(map(wrap_paragraph, paragraphs), [])
"""Module containing helper functions for using pygame.""" def load_class_assets(calling_object, assets_dict): """Load class assets. Only call if class_assets_loaded is False.""" calling_class = type(calling_object) for attribute_name in assets_dict: setattr(calling_class, attribute_name, assets_dict[attribute_name]) setattr(calling_class, "class_assets_loaded", True) def wrap_text(text, font, max_width): """ Returns an array of lines which can be blitted beneath each other in the given font in a box of the given maximum width. """ def wrap_paragraph(paragraph): """Wraps text that doesn't contain newlines.""" def too_long(string): return font.size(string)[0] > max_width def raise_word_too_long_error(word): raise ValueError("\"%s\" is too long to be wrapped." % word) lines = [] words = paragraph.split() line = words.pop(0) if too_long(line): raise_word_too_long_error(line) for word in words: if too_long(word): raise_word_too_long_error(word) if too_long(" ".join((line, word))): lines.append(line) line = word else: line = " ".join((line, word)) lines.append(line) return lines paragraphs = text.split("\n") return sum(map(wrap_paragraph, paragraphs), [])
Update form with values altered on the server side.
(function() { angular.module('notely.notes', [ 'ui.router' ]) .config(notesConfig); notesConfig['$inject'] = ['$stateProvider']; function notesConfig($stateProvider) { $stateProvider .state('notes', { url: '/notes', resolve: { notesLoaded: ['NotesService', function(NotesService) { return NotesService.fetch(); }] }, templateUrl: '/notes/notes.html', controller: NotesController }) .state('notes.form', { url: '/:noteId', templateUrl: '/notes/notes-form.html', controller: NotesFormController }); } NotesController.$inject = ['$state', '$scope', 'NotesService']; function NotesController($state, $scope, NotesService) { $scope.note = {}; $scope.notes = NotesService.get(); } NotesFormController.$inject = ['$scope', '$state', 'NotesService']; function NotesFormController($scope, $state, NotesService) { $scope.note = NotesService.findById($state.params.noteId); $scope.save = function() { // Decide whether to call create or update... if ($scope.note._id) { NotesService.update($scope.note).then(function(response) { $scope.note = angular.copy(response.data.note); }); } else { NotesService.create($scope.note).then(function(response) { $state.go('notes.form', { noteId: response.data.note._id }); }); } }; } })(); //
(function() { angular.module('notely.notes', [ 'ui.router' ]) .config(notesConfig); notesConfig['$inject'] = ['$stateProvider']; function notesConfig($stateProvider) { $stateProvider .state('notes', { url: '/notes', resolve: { notesLoaded: ['NotesService', function(NotesService) { return NotesService.fetch(); }] }, templateUrl: '/notes/notes.html', controller: NotesController }) .state('notes.form', { url: '/:noteId', templateUrl: '/notes/notes-form.html', controller: NotesFormController }); } NotesController.$inject = ['$state', '$scope', 'NotesService']; function NotesController($state, $scope, NotesService) { $scope.note = {}; $scope.notes = NotesService.get(); } NotesFormController.$inject = ['$scope', '$state', 'NotesService']; function NotesFormController($scope, $state, NotesService) { $scope.note = NotesService.findById($state.params.noteId); $scope.save = function() { // Decide whether to call create or update... if ($scope.note._id) { NotesService.update($scope.note); } else { NotesService.create($scope.note).then(function(response) { $state.go('notes.form', { noteId: response.data.note._id }); }); } }; } })(); //
Simplify initialiazing a datagram by use source port 0 and letting OS find an available port
package org.graylog2; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.util.List; public class GelfSender { private static final int DEFAULT_PORT = 12201; private InetAddress host; private int port; private DatagramSocket socket; public GelfSender(String host) throws UnknownHostException, SocketException { this(host, DEFAULT_PORT); } public GelfSender(String host, int port) throws UnknownHostException, SocketException { this.host = InetAddress.getByName(host); this.port = port; this.socket = initiateSocket(); } private DatagramSocket initiateSocket() throws SocketException { return new DatagramSocket(0); } public boolean sendMessage(GelfMessage message) { return message.isValid() && sendDatagrams(message.toDatagrams()); } public boolean sendDatagrams(List<byte[]> bytesList) { for (byte[] bytes : bytesList) { DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length, host, port); try { socket.send(datagramPacket); } catch (IOException e) { return false; } } return true; } public void close() { socket.close(); } }
package org.graylog2; import java.io.IOException; import java.net.*; import java.util.List; public class GelfSender { private static final int DEFAULT_PORT = 12201; private static final int PORT_MIN = 8000; private static final int PORT_MAX = 8888; private InetAddress host; private int port; private DatagramSocket socket; public GelfSender(String host) throws UnknownHostException, SocketException { this(host, DEFAULT_PORT); } public GelfSender(String host, int port) throws UnknownHostException, SocketException { this.host = InetAddress.getByName(host); this.port = port; this.socket = initiateSocket(); } private DatagramSocket initiateSocket() throws SocketException { int port = PORT_MIN; DatagramSocket resultingSocket = null; boolean binded = false; while (!binded) { try { resultingSocket = new DatagramSocket(port); binded = true; } catch (SocketException e) { port++; if (port > PORT_MAX) throw e; } } return resultingSocket; } public boolean sendMessage(GelfMessage message) { return message.isValid() && sendDatagrams(message.toDatagrams()); } public boolean sendDatagrams(List<byte[]> bytesList) { for (byte[] bytes : bytesList) { DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length, host, port); try { socket.send(datagramPacket); } catch (IOException e) { return false; } } return true; } public void close() { socket.close(); } }
Update service provider for 5.3.
<?php namespace LaravelColors; use Illuminate\Contracts\Events\Dispatcher as DispatcherContract; use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider; class LaravelColorsServiceProvider extends ServiceProvider { /** * Register any other events for your application. */ public function boot() { if (!$this->app->routesAreCached()) { require __DIR__.'/Http/routes.php'; } $this->app->router->group(['namespace' => 'LaravelColors\Http\Controllers'], function () { require __DIR__.'/Http/routes.php'; }); $this->loadViewsFrom(__DIR__.'/resources/views', 'laravel-colors'); $this->publishes([ __DIR__.'/config.php' => config_path('laravel-colors.php'), ]); $this->publishes([ __DIR__.'/resources/assets/public' => public_path('vendor/laravel-colors'), ], 'public'); $this->publishes([ __DIR__.'/2016_03_15_220300_create_color_schemes_table.php' => database_path('migrations/2016_03_15_220300_create_color_schemes_table.php'), ], 'migrations'); } /** * Register bindings in the container. */ public function register() { } }
<?php namespace LaravelColors; use Illuminate\Contracts\Events\Dispatcher as DispatcherContract; use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider; class LaravelColorsServiceProvider extends ServiceProvider { /** * Register any other events for your application. * * @param \Illuminate\Contracts\Events\Dispatcher $events */ public function boot(DispatcherContract $events) { if (!$this->app->routesAreCached()) { require __DIR__.'/Http/routes.php'; } $this->app->router->group(['namespace' => 'LaravelColors\Http\Controllers'], function () { require __DIR__.'/Http/routes.php'; }); $this->loadViewsFrom(__DIR__.'/resources/views', 'laravel-colors'); $this->publishes([ __DIR__.'/config.php' => config_path('laravel-colors.php'), ]); $this->publishes([ __DIR__.'/resources/assets/public' => public_path('vendor/laravel-colors'), ], 'public'); $this->publishes([ __DIR__.'/2016_03_15_220300_create_color_schemes_table.php' => database_path('migrations/2016_03_15_220300_create_color_schemes_table.php'), ], 'migrations'); } /** * Register bindings in the container. */ public function register() { } }
Remove imgur api and path
//Import modules var AWS = require('aws-sdk'); var util = require('util'); var fs = require('fs'); //Create S3 client var s3 = new AWS.S3(); //Create event handler for S3 exports.handler = function(event, context) { console.log("Reading options from event:\n", util.inspect(event, {depth: 5})); for (i = 0; i < event.Records.length; i++){ var srcBucket = event.Records[i].s3.bucket.name; var srcKey = event.Records[i].s3.object.key; console.log("The file which you updated is " + srcKey); //Check the image type. var typeMatch = srcKey.match(/\.([^.]*)$/); if (!typeMatch) { console.error('unable to infer image type for key ' + srcKey); return; } var imageType = typeMatch[1]; if(imageType != "jpg" && imageType !="png"){ console.log('Skipping non-image ' + srcKey); return; } //Download images from S3 s3.getObject({ Bucket: srcBucket, Key: srcKey },upload); function upload(err,images){ if(err){ console.log(err); return; } console.log(images); context.done(); } } }
//Import modules var AWS = require('aws-sdk'); var util = require('util'); var imgur = require('imgur-node-api'); var path = require('path'); //Create S3 client var s3 = new AWS.S3(); //Create event handler for S3 exports.handler = function(event, context) { console.log("Reading options from event:\n", util.inspect(event, {depth: 5})); for (i = 0; i < event.Records.length; i++){ var srcBucket = event.Records[i].s3.bucket.name; var srcKey = event.Records[i].s3.object.key; console.log("The file which you updated is " + srcKey); //Check the image type. var typeMatch = srcKey.match(/\.([^.]*)$/); if (!typeMatch) { console.error('unable to infer image type for key ' + srcKey); return; } var imageType = typeMatch[1]; if(imageType != "jpg" && imageType !="png"){ console.log('Skipping non-image ' + srcKey); return; } //Download images from S3 s3.getObject({ Bucket: srcBucket, Key: srcKey },upload); function upload(err,images){ if(err){ console.log(err); return; } console.log(images); context.done(); } } }
Add 'beta' statement in brand
<!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-light fixed-top" id="mainNav"> <div class="container"> <a class="navbar-brand js-scroll-trigger" href="#page-top">Gilles Henrard <small class="text-primary">beta</small></a> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item"><a class="nav-link js-scroll-trigger" href="#page-top">Home</a></li> <li class="nav-item"><a class="nav-link js-scroll-trigger" href="#about">About</a></li> <li class="nav-item"><a class="nav-link js-scroll-trigger" href="#skills">Skills</a></li> <li class="nav-item"><a class="nav-link js-scroll-trigger" href="#experience">Experience</a></li> <li class="nav-item"><a class="nav-link js-scroll-trigger" href="#contact">Contact</a></li> </ul> </div> </div> </nav>
<!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-light fixed-top" id="mainNav"> <div class="container"> <a class="navbar-brand js-scroll-trigger" href="#page-top">Gilles Henrard</a> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item"><a class="nav-link js-scroll-trigger" href="#page-top">Home</a></li> <li class="nav-item"><a class="nav-link js-scroll-trigger" href="#about">About</a></li> <li class="nav-item"><a class="nav-link js-scroll-trigger" href="#skills">Skills</a></li> <li class="nav-item"><a class="nav-link js-scroll-trigger" href="#experience">Experience</a></li> <li class="nav-item"><a class="nav-link js-scroll-trigger" href="#contact">Contact</a></li> </ul> </div> </div> </nav>
Reset Pager index when searching Signed-off-by: Gerco van Heerdt <[email protected]>
<?php import_lib('interactive/Form'); class Search { private $index; private $form; private $pager; function __construct($redirect = true, $pager = null) { global $s; $this->index = find_index('search'); $this->form = new Form('search', isset($pager) && $pager->drawable() ? 'left' : null); $this->form->setData(array('name' => unescape_url($s['h'][$this->index]))); $this->form->add('Name', 'text', 'name', false, array('class' => 'search')); $this->form->add('Search', 'submit'); $this->pager = $pager; if ($redirect) $this->redirect(); } function redirect() { global $s; if ($this->form->received()) { $s['h'][$this->pager->getIndex()] = 1; redirect(url(escape_url($this->form->get('name')), $this->index, false)); } } function get() { global $s; return simplify(unescape_url($s['h'][$this->index])); } function getLike() { return " LIKE '%" . secure($this->get()) . "%'"; } private function setForm() { if (isset($this->form)) return; } function getForm() { return $this->form; } function getPager() { return $this->pager; } } ?>
<?php import_lib('interactive/Form'); class Search { private $index; private $form; private $pager; function __construct($redirect = true, $pager = null) { global $s; $this->index = find_index('search'); $this->form = new Form('search', isset($pager) && $pager->drawable() ? 'left' : null); $this->form->setData(array('name' => unescape_url($s['h'][$this->index]))); $this->form->add('Name', 'text', 'name', false, array('class' => 'search')); $this->form->add('Search', 'submit'); if ($redirect) $this->redirect(); $this->pager = $pager; } function redirect() { if ($this->form->received()) redirect(url(escape_url($this->form->get('name')), $this->index, false)); } function get() { global $s; return simplify(unescape_url($s['h'][$this->index])); } function getLike() { return " LIKE '%" . secure($this->get()) . "%'"; } private function setForm() { if (isset($this->form)) return; } function getForm() { return $this->form; } function getPager() { return $this->pager; } } ?>
Fix test helper once and for all
import github3 from .helper import IntegrationHelper def find(func, iterable): return next(iter(filter(func, iterable))) class TestDeployment(IntegrationHelper): def test_create_status(self): """ Test that using a Deployment instance, a user can create a status. """ self.basic_login() cassette_name = self.cassette_name('create_status') with self.recorder.use_cassette(cassette_name): repository = self.gh.repository('sigmavirus24', 'github3.py') assert repository is not None deployment = find(lambda d: d.id == 801, repository.iter_deployments()) assert deployment is not None status = deployment.create_status('success') assert isinstance(status, github3.repos.deployment.DeploymentStatus) def test_iter_statuses(self): """ Test that using a Deployment instance, a user can retrieve statuses. """ cassette_name = self.cassette_name('statuses') with self.recorder.use_cassette(cassette_name): repository = self.gh.repository('sigmavirus24', 'github3.py') assert repository is not None deployment = find(lambda d: d.id == 801, repository.iter_deployments()) assert deployment is not None statuses = list(deployment.iter_statuses(5)) for status in statuses: assert isinstance(status, github3.repos.deployment.DeploymentStatus)
import github3 from .helper import IntegrationHelper def find(func, iterable): return next(filter(func, iterable)) class TestDeployment(IntegrationHelper): def test_create_status(self): """ Test that using a Deployment instance, a user can create a status. """ self.basic_login() cassette_name = self.cassette_name('create_status') with self.recorder.use_cassette(cassette_name): repository = self.gh.repository('sigmavirus24', 'github3.py') assert repository is not None deployment = find(lambda d: d.id == 801, repository.iter_deployments()) assert deployment is not None status = deployment.create_status('success') assert isinstance(status, github3.repos.deployment.DeploymentStatus) def test_iter_statuses(self): """ Test that using a Deployment instance, a user can retrieve statuses. """ cassette_name = self.cassette_name('statuses') with self.recorder.use_cassette(cassette_name): repository = self.gh.repository('sigmavirus24', 'github3.py') assert repository is not None deployment = find(lambda d: d.id == 801, repository.iter_deployments()) assert deployment is not None statuses = list(deployment.iter_statuses(5)) for status in statuses: assert isinstance(status, github3.repos.deployment.DeploymentStatus)
Use `latest` tag for release
var gulp = require('gulp'); var gulpBabel = require('gulp-babel'); var eslint = require('gulp-eslint'); var mocha = require('gulp-mocha'); var ll = require('gulp-ll'); var publish = require('publish-please'); var del = require('del'); ll.tasks('lint'); gulp.task('clean', function (cb) { del('lib', cb); }); // Lint gulp.task('lint', function () { return gulp .src([ 'src/**/*.js', 'test/**/**.js', 'Gulpfile.js' ]) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()); }); // Build gulp.task('build', ['clean', 'lint'], function () { return gulp .src('src/**/*.js') .pipe(gulpBabel()) .pipe(gulp.dest('lib')); }); // Test gulp.task('test-server', ['build'], function () { return gulp .src('test/server/*-test.js') .pipe(mocha({ ui: 'bdd', reporter: 'spec', timeout: typeof v8debug === 'undefined' ? 2000 : Infinity // NOTE: disable timeouts in debug })); }); // Publish gulp.task('publish', ['test-server'], function () { return publish(); });
var gulp = require('gulp'); var gulpBabel = require('gulp-babel'); var eslint = require('gulp-eslint'); var mocha = require('gulp-mocha'); var ll = require('gulp-ll'); var publish = require('publish-please'); var del = require('del'); ll.tasks('lint'); gulp.task('clean', function (cb) { del('lib', cb); }); // Lint gulp.task('lint', function () { return gulp .src([ 'src/**/*.js', 'test/**/**.js', 'Gulpfile.js' ]) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()); }); // Build gulp.task('build', ['clean', 'lint'], function () { return gulp .src('src/**/*.js') .pipe(gulpBabel()) .pipe(gulp.dest('lib')); }); // Test gulp.task('test-server', ['build'], function () { return gulp .src('test/server/*-test.js') .pipe(mocha({ ui: 'bdd', reporter: 'spec', timeout: typeof v8debug === 'undefined' ? 2000 : Infinity // NOTE: disable timeouts in debug })); }); // Publish gulp.task('publish', ['test-server'], function () { // TODO switch publish tag once we'll be ready to release return publish({ tag: 'alpha' }); });
Fix pause for per vertex lighting sample
(function() { var width, height; width = height = 600; window.samples.per_vertex_lighting = { initialize: function(canvas) { var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera( 75, width / height, 1, 1000 ); camera.position.z = 100; var geometry = new THREE.SphereGeometry( 60, 4, 4 ); var material = new THREE.MeshLambertMaterial( { color: 0xdddddd } ); var mesh = new THREE.Mesh( geometry, material ); scene.add( mesh ); var spotLight = new THREE.SpotLight ( 0xffffffff ); spotLight.position.set( 0, 100, 0 ); scene.add( spotLight ); var ambientLight = new THREE.AmbientLight( 0x22222222 ); scene.add(ambientLight); var renderer = new THREE.WebGLRenderer({canvas: canvas}); renderer.setSize( width, height); var instance = { active: false }; function animate() { requestAnimationFrame( animate, canvas ); mesh.material.wireframe = sample_defaults.wireframe; if(instance.active && !sample_defaults.paused) { // Rotate lighting around the X axis. var angle = 0.01; var matrix = new THREE.Matrix4().makeRotationX( angle ); spotLight.position = matrix.multiplyVector3( spotLight.position ); } renderer.render( scene, camera ); } animate(); return instance; } }; })();
(function() { var width, height; width = height = 600; window.samples.per_vertex_lighting = { initialize: function(canvas) { var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera( 75, width / height, 1, 1000 ); camera.position.z = 100; var geometry = new THREE.SphereGeometry( 60, 4, 4 ); var material = new THREE.MeshLambertMaterial( { color: 0xdddddd } ); var mesh = new THREE.Mesh( geometry, material ); scene.add( mesh ); var spotLight = new THREE.SpotLight ( 0xffffffff ); spotLight.position.set( 0, 100, 0 ); scene.add( spotLight ); var ambientLight = new THREE.AmbientLight( 0x22222222 ); scene.add(ambientLight); var renderer = new THREE.WebGLRenderer({canvas: canvas}); renderer.setSize( width, height); var instance = { active: false }; function animate() { requestAnimationFrame( animate, canvas ); mesh.material.wireframe = sample_defaults.wireframe; if(!instance.active || sample_defaults.paused) { // Rotate lighting around the X axis. var angle = 0.01; var matrix = new THREE.Matrix4().makeRotationX( angle ); spotLight.position = matrix.multiplyVector3( spotLight.position ); } renderer.render( scene, camera ); } animate(); return instance; } }; })();
Fix injected local 'arguments' not working in list comprehension in bind.
# python 3 support import six if six.PY3: basestring = str long = int xrange = range unicode = str class FunctionPrototype: def toString(): if not this.is_callable(): raise TypeError('toString is not generic!') args = ', '.join(this.code.__code__.co_varnames[:this.argcount]) return 'function %s(%s) ' % (this.func_name, args) + this.source def call(): arguments_ = arguments if not len(arguments): obj = this.Js(None) else: obj = arguments[0] if len(arguments) <= 1: args = () else: args = tuple([arguments_[e] for e in xrange(1, len(arguments_))]) return this.call(obj, args) def apply(): if not len(arguments): obj = this.Js(None) else: obj = arguments[0] if len(arguments) <= 1: args = () else: appl = arguments[1] args = tuple([appl[e] for e in xrange(len(appl))]) return this.call(obj, args) def bind(thisArg): arguments_ = arguments target = this if not target.is_callable(): raise this.MakeError( 'Object must be callable in order to be used with bind method') if len(arguments) <= 1: args = () else: args = tuple([arguments_[e] for e in xrange(1, len(arguments_))]) return this.PyJsBoundFunction(target, thisArg, args)
# python 3 support import six if six.PY3: basestring = str long = int xrange = range unicode = str # todo fix apply and bind class FunctionPrototype: def toString(): if not this.is_callable(): raise TypeError('toString is not generic!') args = ', '.join(this.code.__code__.co_varnames[:this.argcount]) return 'function %s(%s) ' % (this.func_name, args) + this.source def call(): arguments_ = arguments if not len(arguments): obj = this.Js(None) else: obj = arguments[0] if len(arguments) <= 1: args = () else: args = tuple([arguments_[e] for e in xrange(1, len(arguments_))]) return this.call(obj, args) def apply(): if not len(arguments): obj = this.Js(None) else: obj = arguments[0] if len(arguments) <= 1: args = () else: appl = arguments[1] args = tuple([appl[e] for e in xrange(len(appl))]) return this.call(obj, args) def bind(thisArg): target = this if not target.is_callable(): raise this.MakeError( 'Object must be callable in order to be used with bind method') if len(arguments) <= 1: args = () else: args = tuple([arguments[e] for e in xrange(1, len(arguments))]) return this.PyJsBoundFunction(target, thisArg, args)
Adjust the browser definition to the ones that actually work
module.exports = config => { const customLaunchers = { 'SL Chrome 26': { base: 'SauceLabs', browserName: 'chrome', platform: 'Linux', version: '26.0', }, 'SL Edge 13': { base: 'SauceLabs', browserName: 'MicrosoftEdge', platform: 'Windows 10', version: '13.10586', }, 'SL Firefox 4': { base: 'SauceLabs', browserName: 'firefox', platform: 'Linux', version: '4.0', }, 'SL Internet Explorer 9': { base: 'SauceLabs', browserName: 'internet explorer', platform: 'Windows 7', version: '9.0', }, 'SL Safari 8': { base: 'SauceLabs', browserName: 'safari', platform: 'OS X 10.10', version: '8.0', } }; config.set({ browserify: { debug: true }, files: ['test.js'], frameworks: ['browserify', 'sinon', 'tape'], preprocessors: { 'test.js': ['browserify'] }, reporters: ['dots'] }); if (!config.local) { config.set({ browsers: Object.keys(customLaunchers), customLaunchers, reporters: [...config.reporters, 'saucelabs'] }); } };
module.exports = config => { const customLaunchers = { 'SL Chrome 26': { base: 'SauceLabs', browserName: 'chrome', version: '26' }, 'SL Edge 13': { base: 'SauceLabs', browserName: 'microsoftedge', version: '13' }, 'SL Firefox 4': { base: 'SauceLabs', browserName: 'firefox', version: '4' }, 'SL Internet Explorer 9': { base: 'SauceLabs', browserName: 'internet explorer', version: '9' }, 'SL iOS 8.1': { base: 'SauceLabs', browserName: 'iphone', version: '8.1' }, 'SL Safari 6': { base: 'SauceLabs', browserName: 'safari', version: '6' } }; config.set({ browserify: { debug: true }, files: ['test.js'], frameworks: ['browserify', 'sinon', 'tape'], preprocessors: { 'test.js': ['browserify'] }, reporters: ['dots'] }); if (!config.local) { config.set({ browsers: Object.keys(customLaunchers), customLaunchers, reporters: [...config.reporters, 'saucelabs'] }); } };
Use debuglog for test client
'use strict'; // This is a client that produces load on hodor-net-server. process.title = 'nodejs hodor client'; var net = require('net'); var debuglog = require('debuglog'); var log = debuglog('hodor-net-client'); var BACKOFF = 1000; function next() { var connected = false; var finished = false; var data = ""; var client = net.connect(+process.env.HODOR_PORT, 'localhost', function () { connected = true; }); client.setEncoding('utf-8'); client.on('error', function (error) { log('unexpected error', error.message); setTimeout(next, BACKOFF); }); client.on('data', function (_data) { data += _data; }); client.on('finish', function () { finished = true; }); client.on('end', function () { if (!connected) { log('unexpected end before connection'); setTimeout(next, BACKOFF); } else if (data !== 'HODOR') { log('unexpected response', JSON.stringify(data)); setTimeout(next, BACKOFF); } else if (!finished) { log('expected finish before end'); setTimeout(next, BACKOFF); } else { next(); } }); } // Five concurrent requests next(); next(); next(); next(); next();
'use strict'; // This is a client that produces load on hodor-net-server. process.title = 'nodejs hodor client'; var net = require('net'); var BACKOFF = 1000; function next() { var connected = false; var finished = false; var data = ""; var client = net.connect(+process.env.HODOR_PORT, 'localhost', function () { connected = true; }); client.setEncoding('utf-8'); client.on('error', function (error) { console.log('unexpected error', error.message); setTimeout(next, BACKOFF); }); client.on('data', function (_data) { data += _data; }); client.on('finish', function () { finished = true; }); client.on('end', function () { if (!connected) { console.log('unexpected end before connection'); setTimeout(next, BACKOFF); } else if (data !== 'HODOR') { console.log('unexpected response', data); setTimeout(next, BACKOFF); } else if (!finished) { console.log('expected finish before end'); setTimeout(next, BACKOFF); } else { next(); } }); } // Five concurrent requests next(); next(); next(); next(); next();
Move to test version for pypi-test
"""Setup for pyexperiment """ from __future__ import print_function # from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import import os from setuptools import setup try: from pypandoc import convert read_md = lambda fname: convert(fname, 'rst') except ImportError: print("Warning: pypandoc module not found") read_md = lambda fname: open( os.path.join(os.path.dirname(__file__), fname), 'r').read() LONG_DESCRIPTION = 'Framework for easy and clean experiments with python.' if os.path.exists('README.md'): LONG_DESCRIPTION = read_md('README.md') setup( name="pyexperiment", version="0.1.15-test", author="Peter Duerr", author_email="[email protected]", description="Run experiments with Python - quick and clean.", license="MIT", keywords="science experiment", url="https://github.com/duerrp/pyexperiment", # download_url="https://github.com/duerrp/pyexperiment/tarball/0.1.15", packages=['pyexperiment', 'pyexperiment.conf', 'pyexperiment.state', 'pyexperiment.utils', 'pyexperiment.log', ], long_description=LONG_DESCRIPTION, classifiers=[ "Development Status :: 3 - Alpha", "Topic :: Utilities", "License :: OSI Approved :: MIT License", ], )
"""Setup for pyexperiment """ from __future__ import print_function # from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import import os from setuptools import setup try: from pypandoc import convert read_md = lambda fname: convert(fname, 'rst') except ImportError: print("Warning: pypandoc module not found") read_md = lambda fname: open( os.path.join(os.path.dirname(__file__), fname), 'r').read() LONG_DESCRIPTION = 'Framework for easy and clean experiments with python.' if os.path.exists('README.md'): LONG_DESCRIPTION = read_md('README.md') setup( name="pyexperiment", version="0.1.15", author="Peter Duerr", author_email="[email protected]", description="Run experiments with Python - quick and clean.", license="MIT", keywords="science experiment", url="https://github.com/duerrp/pyexperiment", download_url="https://github.com/duerrp/pyexperiment/tarball/0.1.15", packages=['pyexperiment', 'pyexperiment.conf', 'pyexperiment.state', 'pyexperiment.utils', 'pyexperiment.log', ], long_description=LONG_DESCRIPTION, classifiers=[ "Development Status :: 3 - Alpha", "Topic :: Utilities", "License :: OSI Approved :: MIT License", ], )
Fix a bug of TsDescriptorEmergencyInformation
"use strict"; const TsReader = require("../reader"); const TsDescriptorBase = require("./base"); class TsDescriptorEmergencyInformation extends TsDescriptorBase { constructor(buffer) { super(buffer); } decode() { const reader = new TsReader(this._buffer); const objDescriptor = {}; objDescriptor.descriptor_tag = reader.uimsbf(8); objDescriptor.descriptor_length = reader.uimsbf(8); objDescriptor.services = []; for (const l = 2 + objDescriptor.descriptor_length; reader.position >> 3 < l; ) { const service = {}; service.service_id = reader.uimsbf(16); service.start_end_flag = reader.bslbf(1); service.signal_level = reader.bslbf(1); reader.next(6); // reserved_future_use service.area_code_length = reader.uimsbf(8); service.area_codes = []; for (const length = (reader.position >> 3) + service.area_code_length; reader.position >> 3 < length; ) { const area_code = {}; area_code.area_code = reader.bslbf(12); reader.next(4); // reserved_future_use service.area_codes.push(area_code); } objDescriptor.services.push(service); } return objDescriptor; } } module.exports = TsDescriptorEmergencyInformation;
"use strict"; const TsReader = require("../reader"); const TsDescriptorBase = require("./base"); class TsDescriptorEmergencyInformation extends TsDescriptorBase { constructor(buffer) { super(buffer); } decode() { const reader = new TsReader(this._buffer); const objDescriptor = {}; objDescriptor.descriptor_tag = reader.uimsbf(8); objDescriptor.descriptor_length = reader.uimsbf(8); objDescriptor.services = []; for (const l = 2 + objDescriptor.descriptor_length; reader.position >> 3 < l; ) { const service = {}; service.service_id = reader.uimsbf(16); service.start_end_flag = reader.bslbf(1); service.signal_level = reader.bslbf(1); reader.next(6); // reserved_future_use service.area_code_length = reader.uimsbf(8); service.area_codes = []; for (const length = (reader.position >> 3) + objDescriptor.area_code_length; reader.position >> 3 < length; ) { const area_code = {}; area_code.area_code = reader.bslbf(12); reader.next(4); // reserved_future_use service.area_codes.push(area_code); } objDescriptor.services.push(service); } return objDescriptor; } } module.exports = TsDescriptorEmergencyInformation;
Set exception code to status of HTTP response
<?php namespace Doctrine\CouchDB\HTTP; /** * Base exception class for package Doctrine\ODM\CouchDB\HTTP * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @link www.doctrine-project.com * @since 1.0 * @author Kore Nordmann <[email protected]> */ class HTTPException extends \Doctrine\CouchDB\CouchDBException { public static function connectionFailure( $ip, $port, $errstr, $errno ) { return new self( sprintf( "Could not connect to server at %s:%d: '%d: %s'", $ip, $port, $errno, $errstr ), $errno ); } public static function readFailure( $ip, $port, $errstr, $errno ) { return new static( sprintf( "Could read from server at %s:%d: '%d: %s'", $ip, $port, $errno, $errstr ), $errno ); } /** * @param Response $response */ public static function fromResponse($path, Response $response) { if (!isset($response->body['error'])) { $response->body['error'] = ''; } return new self("HTTP Error with status " . $response->status . " occoured while ". "requesting " . $path . ". Error: " . $response->body['error'] . " " . $response->body['reason'], $response->status ); } }
<?php namespace Doctrine\CouchDB\HTTP; /** * Base exception class for package Doctrine\ODM\CouchDB\HTTP * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @link www.doctrine-project.com * @since 1.0 * @author Kore Nordmann <[email protected]> */ class HTTPException extends \Doctrine\CouchDB\CouchDBException { public static function connectionFailure( $ip, $port, $errstr, $errno ) { return new self( sprintf( "Could not connect to server at %s:%d: '%d: %s'", $ip, $port, $errno, $errstr ) ); } public static function readFailure( $ip, $port, $errstr, $errno ) { return new static( sprintf( "Could read from server at %s:%d: '%d: %s'", $ip, $port, $errno, $errstr ) ); } /** * @param Response $response */ public static function fromResponse($path, Response $response) { if (!isset($response->body['error'])) { $response->body['error'] = ''; } return new self("HTTP Error with status " . $response->status . " occoured while ". "requesting " . $path . ". Error: " . $response->body['error'] . " " . $response->body['reason']); } }
Simplify invalid decode warning text The string is already displayed in the error text, so there's no reason to duplicate it.
from __future__ import unicode_literals import base32_crockford import logging from django.db.models import F from django.http import Http404 from django.http import HttpResponsePermanentRedirect from django.shortcuts import get_object_or_404 from django.utils.timezone import now from .models import ShortURL from .models import VanityURL from .utils import add_query_params logger = logging.getLogger(__name__) def redirect(request, key): """ Given the short URL key, update the statistics and redirect the user to the destination URL, including available Google Analytics parameters. """ try: alias = VanityURL.objects.select_related().get(alias=key.upper()) key_id = alias.redirect.id except VanityURL.DoesNotExist: try: key_id = base32_crockford.decode(key) except ValueError as e: logger.warning("Error decoding redirect: %s" % e) raise Http404 redirect = get_object_or_404(ShortURL, pk=key_id) ShortURL.objects.filter(pk=key_id).update(hits=F('hits') + 1, last_used=now()) # Inject Google campaign parameters utm_params = {'utm_source': redirect.key, 'utm_campaign': redirect.campaign, 'utm_content': redirect.content, 'utm_medium': redirect.medium} url = add_query_params(redirect.long_url, utm_params) return HttpResponsePermanentRedirect(url)
from __future__ import unicode_literals import base32_crockford import logging from django.db.models import F from django.http import Http404 from django.http import HttpResponsePermanentRedirect from django.shortcuts import get_object_or_404 from django.utils.timezone import now from .models import ShortURL from .models import VanityURL from .utils import add_query_params logger = logging.getLogger(__name__) def redirect(request, key): """ Given the short URL key, update the statistics and redirect the user to the destination URL, including available Google Analytics parameters. """ try: alias = VanityURL.objects.select_related().get(alias=key.upper()) key_id = alias.redirect.id except VanityURL.DoesNotExist: try: key_id = base32_crockford.decode(key) except ValueError as e: logger.warning("Error decoding redirect '%s': %s" % (key, e)) raise Http404 redirect = get_object_or_404(ShortURL, pk=key_id) ShortURL.objects.filter(pk=key_id).update(hits=F('hits') + 1, last_used=now()) # Inject Google campaign parameters utm_params = {'utm_source': redirect.key, 'utm_campaign': redirect.campaign, 'utm_content': redirect.content, 'utm_medium': redirect.medium} url = add_query_params(redirect.long_url, utm_params) return HttpResponsePermanentRedirect(url)
Change to 'newNotification', change to post
Vue.component('spark-kiosk-notify', { props: [ ], data() { return { 'notifications': [], 'users': [], 'newNotification': { "user_id": null } }; }, ready(){ this.getNotifications(); this.getUsers(); }, methods: { /** * Get all of the announcements. */ getNotifications: function(){ this.$http.get('/skn/notifications') .then(response => { this.notifications = response.data; }); }, /** * Get all of the users. */ getUsers: function(){ this.$http.get('/skn/users') .then(response => { this.users = response.data; }); }, /** * Create Notification. */ createNotification: function(){ this.$http.post('/skn/notifications/create', this.newNotification) .then(response => { this.newNotification = {}; this.getNotifications(); }); } } });
Vue.component('spark-kiosk-notify', { props: [ ], data() { return { 'notifications': [], 'users': [], 'newNotification': { "user_id": null } }; }, ready(){ this.getNotifications(); this.getUsers(); }, methods: { /** * Get all of the announcements. */ getNotifications: function(){ this.$http.get('/skn/notifications') .then(response => { this.notifications = response.data; }); }, /** * Get all of the users. */ getUsers: function(){ this.$http.get('/skn/users') .then(response => { this.users = response.data; }); }, /** * Create Notification. */ createNotification: function(){ this.$http.get('/skn/notifications/create', this.createNotification) .then(response => { this.createNotification = {}; this.getNotifications(); }); } } });
Fix Django 1.7 migration support
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.db import models, migrations, connection import django.db.models.deletion is_index = connection.vendor != 'mysql' if 'django.contrib.comments' in settings.INSTALLED_APPS: BASE_APP = 'comments' else: BASE_APP = 'django_comments' class Migration(migrations.Migration): dependencies = [ (BASE_APP, '__first__'), ] operations = [ migrations.CreateModel( name='ThreadedComment', fields=[ ('comment_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='django_comments.Comment')), ('title', models.TextField(verbose_name='Title', blank=True)), ('tree_path', models.CharField(verbose_name='Tree path', max_length=500, editable=False, db_index=is_index)), ('last_child', models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, verbose_name='Last child', blank=True, to='threadedcomments.ThreadedComment', null=True)), ('parent', models.ForeignKey(related_name='children', default=None, blank=True, to='threadedcomments.ThreadedComment', null=True, verbose_name='Parent')), ], options={ 'ordering': ('tree_path',), 'db_table': 'threadedcomments_comment', 'verbose_name': 'Threaded comment', 'verbose_name_plural': 'Threaded comments', }, bases=('{base_app}.comment'.format(base_app=BASE_APP),), ) ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations, connection import django.db.models.deletion is_index = connection.vendor != 'mysql' class Migration(migrations.Migration): dependencies = [ ('django_comments', '__first__'), ] operations = [ migrations.CreateModel( name='ThreadedComment', fields=[ ('comment_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='django_comments.Comment')), ('title', models.TextField(verbose_name='Title', blank=True)), ('tree_path', models.CharField(verbose_name='Tree path', max_length=500, editable=False, db_index=is_index)), ('last_child', models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, verbose_name='Last child', blank=True, to='threadedcomments.ThreadedComment', null=True)), ('parent', models.ForeignKey(related_name='children', default=None, blank=True, to='threadedcomments.ThreadedComment', null=True, verbose_name='Parent')), ], options={ 'ordering': ('tree_path',), 'db_table': 'threadedcomments_comment', 'verbose_name': 'Threaded comment', 'verbose_name_plural': 'Threaded comments', }, bases=('django_comments.comment',), ) ]
Fix a small bug - %d => %s Summary: easy peasy. noticed it trying to fix an image. Test Plan: can fix image by phid once more! Reviewers: epriestley Reviewed By: epriestley CC: aran, Korvin Differential Revision: https://secure.phabricator.com/D6659
<?php abstract class PhabricatorFilesManagementWorkflow extends PhutilArgumentWorkflow { public function isExecutable() { return true; } protected function buildIterator(PhutilArgumentParser $args) { if ($args->getArg('all')) { if ($args->getArg('names')) { throw new PhutilArgumentUsageException( "Specify either a list of files or `--all`, but not both."); } return new LiskMigrationIterator(new PhabricatorFile()); } if ($args->getArg('names')) { $iterator = array(); foreach ($args->getArg('names') as $name) { $name = trim($name); $id = preg_replace('/^F/i', '', $name); if (ctype_digit($id)) { $file = id(new PhabricatorFile())->loadOneWhere( 'id = %d', $id); if (!$file) { throw new PhutilArgumentUsageException( "No file exists with ID '{$name}'."); } } else { $file = id(new PhabricatorFile())->loadOneWhere( 'phid = %s', $name); if (!$file) { throw new PhutilArgumentUsageException( "No file exists with PHID '{$name}'."); } } $iterator[] = $file; } return $iterator; } return null; } }
<?php abstract class PhabricatorFilesManagementWorkflow extends PhutilArgumentWorkflow { public function isExecutable() { return true; } protected function buildIterator(PhutilArgumentParser $args) { if ($args->getArg('all')) { if ($args->getArg('names')) { throw new PhutilArgumentUsageException( "Specify either a list of files or `--all`, but not both."); } return new LiskMigrationIterator(new PhabricatorFile()); } if ($args->getArg('names')) { $iterator = array(); foreach ($args->getArg('names') as $name) { $name = trim($name); $id = preg_replace('/^F/i', '', $name); if (ctype_digit($id)) { $file = id(new PhabricatorFile())->loadOneWhere( 'id = %d', $id); if (!$file) { throw new PhutilArgumentUsageException( "No file exists with ID '{$name}'."); } } else { $file = id(new PhabricatorFile())->loadOneWhere( 'phid = %d', $name); if (!$file) { throw new PhutilArgumentUsageException( "No file exists with PHID '{$name}'."); } } $iterator[] = $file; } return $iterator; } return null; } }
fix: Test with Mockery class is compatible with PHP 5.4
<?php namespace Granam\Tests\Tools; abstract class TestWithMockery extends \PHPUnit_Framework_TestCase { protected function tearDown() { \Mockery::close(); } /** * @param string $className * @return \Mockery\MockInterface */ protected function mockery($className) { self::assertTrue( class_exists($className) || interface_exists($className), "Given class $className does not exists." ); return \Mockery::mock($className); } /** * @param mixed $expected * @return \Mockery\Matcher\Type */ protected function type($expected) { return \Mockery::type($this->getTypeOf($expected)); } /** * @param $value * @return string */ private function getTypeOf($value) { if (is_string($value)) { return $value; // not type of "string" but direct description - like class name } if (is_object($value)) { return get_class($value); } return gettype($value); } /** * Expects test class with name \Granam\Tests\Tools\TestWithMockery therefore extended by \Tests sub-namespace * and Test suffix * * @return string|TestWithMockery */ protected function getSutClass() { return preg_replace('~\\\Tests(.+)Test$~', '$1', get_class($this)); } }
<?php namespace Granam\Tests\Tools; abstract class TestWithMockery extends \PHPUnit_Framework_TestCase { protected function tearDown() { \Mockery::close(); } /** * @param string $className * @return \Mockery\MockInterface */ protected function mockery($className) { self::assertTrue( class_exists($className) || interface_exists($className), "Given class $className does not exists." ); return \Mockery::mock($className); } /** * @param mixed $expected * @return \Mockery\Matcher\Type */ protected function type($expected) { return \Mockery::type($this->getTypeOf($expected)); } /** * @param $value * @return string */ private function getTypeOf($value) { if (is_string($value)) { return $value; // not type of "string" but direct description - like class name } if (is_object($value)) { return get_class($value); } return gettype($value); } /** * Expects test class with name \Granam\Tests\Tools\TestWithMockery therefore extended by \Tests sub-namespace * and Test suffix * * @return string|TestWithMockery */ protected function getSutClass() { return preg_replace('~\\\Tests(.+)Test$~', '$1', static::class); } }
Fix bug in IE8 undefined returns as object
define([ ], function () { /** * @exports is-defined * * Helper which checks whether a variable is defined or not. * * @param {*} check The variable to check that is defined * @param {String} type The type your expecting the variable to be defined as. * * @returns {Boolean} When the variable is undefined it will pass back false otherwise pass back true. * * @example * ```js * var barney; * isDefined(barney); * // Returns false * * var barney = 'stinson'; * isDefined(barney); * // Returns true * * isDefined(barney, 'string'); * // Returns true * * isDefined(barney, 'function'); * // Returns false * ``` */ function isDefined (check, type) { // Check that the variable is a specific type && not undefined (IE8 reports undefined variables as objects) if (type && typeof check !== 'undefined') { var regex = new RegExp(/\[object (\w+)]/), string = Object.prototype.toString.call(check).toLowerCase(), matches = string.match(regex); return matches[1] === type; } return (typeof check !== 'undefined'); } return isDefined; });
define([ ], function () { /** * @exports is-defined * * Helper which checks whether a variable is defined or not. * * @param {*} check The variable to check that is defined * @param {String} type The type your expecting the variable to be defined as. * * @returns {Boolean} When the variable is undefined it will pass back false otherwise pass back true. * * @example * ```js * var barney; * isDefined(barney); * // Returns false * * var barney = 'stinson'; * isDefined(barney); * // Returns true * * isDefined(barney, 'string'); * // Returns true * * isDefined(barney, 'function'); * // Returns false * ``` */ function isDefined (check, type) { // Check that the variable is a specific type if (type) { var regex = new RegExp(/\[object (\w+)]/), string = Object.prototype.toString.call(check).toLowerCase(), matches = string.match(regex); return matches[1] === type; } return (typeof check !== 'undefined'); } return isDefined; });
Upgrade certifi 2015.11.20.1 => 2016.2.28
import sys from setuptools import find_packages, setup with open('VERSION') as version_fp: VERSION = version_fp.read().strip() install_requires = [ 'django-local-settings>=1.0a13', 'stashward', ] if sys.version_info[:2] < (3, 4): install_requires.append('enum34') setup( name='django-arcutils', version=VERSION, url='https://github.com/PSU-OIT-ARC/django-arcutils', author='PSU - OIT - ARC', author_email='[email protected]', description='Common utilities used in ARC Django projects', packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=install_requires, extras_require={ 'ldap': [ 'certifi>=2016.2.28', 'ldap3>=1.0.4', ], 'dev': [ 'django>=1.7,<1.9', 'djangorestframework>3.3', 'flake8', 'ldap3', ], }, entry_points=""" [console_scripts] arcutils = arcutils.__main__:main """, classifiers=[ 'Development Status :: 3 - Alpha', 'Framework :: Django', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], )
import sys from setuptools import find_packages, setup with open('VERSION') as version_fp: VERSION = version_fp.read().strip() install_requires = [ 'django-local-settings>=1.0a13', 'stashward', ] if sys.version_info[:2] < (3, 4): install_requires.append('enum34') setup( name='django-arcutils', version=VERSION, url='https://github.com/PSU-OIT-ARC/django-arcutils', author='PSU - OIT - ARC', author_email='[email protected]', description='Common utilities used in ARC Django projects', packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=install_requires, extras_require={ 'ldap': [ 'certifi>=2015.11.20.1', 'ldap3>=1.0.4', ], 'dev': [ 'django>=1.7,<1.9', 'djangorestframework>3.3', 'flake8', 'ldap3', ], }, entry_points=""" [console_scripts] arcutils = arcutils.__main__:main """, classifiers=[ 'Development Status :: 3 - Alpha', 'Framework :: Django', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], )
Rhymes: Fix "More at ..." link and move to group "base".
function ddg_spice_rhymes ( api_result ) { "use strict"; var query = DDG.get_query() .replace(/^(what|rhymes?( with| for)?) |\?/gi, ""); if (!api_result.length) { return; } var words = [], count=0; for(var i=0, l = api_result.length; i<l; i++) { var word = api_result[i]; if (word.score === 300 && !word.flags.match(/a/)) { words.push(word); console.log(word.word); if (++count > 15) break; } } Spice.add({ data : { words: words }, id : "rhymes", name : "Rhymes", meta: { sourceUrl : 'http://rhymebrain.com/en/What_rhymes_with_' + encodeURIComponent(query) + '.html', sourceName : 'RhymeBrain', sourceIcon: true }, templates : { group: 'base', options: { content: Spice.rhymes.item, moreAt: true } } }); }
function ddg_spice_rhymes ( api_result ) { "use strict"; var query = DDG.get_query() .replace(/^(what|rhymes?( with| for)?) |\?/gi, ""); if (!api_result.length) { return; } var words = [], count=0; for(var i=0, l = api_result.length; i<l; i++) { var word = api_result[i]; if (word.score === 300 && !word.flags.match(/a/)) { words.push(word); console.log(word.word); if (++count > 15) break; } } Spice.add({ data : { words: words }, id : "rhymes", name : "Rhymes", meta: { sourceUrl : 'http://rhymebrain.com/en/What_rhymes_with_' + encodeURIComponent(query), sourceName : 'RhymeBrain', sourceIcon: true }, templates : { group: 'info', options: { content: Spice.rhymes.item } } }); }
Fix slack 'invalid attachments' error message
from functools import wraps from celery import shared_task from django.conf import settings from integrations import slack def switchable_task(func): @wraps(func) def wrapper(*args, **kwargs): if settings.USE_SCHEDULER: return func.delay(*args, **kwargs) return func(*args, **kwargs) return wrapper @switchable_task @shared_task def notify_new_submission( title: str, elevator_pitch: str, submission_type: str, admin_url, topic: str, duration: int, ): slack.send_message( [ { "type": "section", "text": { "text": f"New _{submission_type}_ Submission", "type": "mrkdwn", }, } ], [ { "blocks": [ { "type": "section", "text": { "type": "mrkdwn", "text": f"*<{admin_url}|{title.capitalize()}>*\n" f"*Elevator Pitch*\n{elevator_pitch}", }, "fields": [ {"type": "mrkdwn", "text": "*Topic*"}, {"type": "mrkdwn", "text": "*Duration*"}, {"type": "plain_text", "text": str(duration)}, {"type": "mrkdwn", "text": str(topic)}, ], } ] } ], )
from functools import wraps from celery import shared_task from django.conf import settings from integrations import slack def switchable_task(func): @wraps(func) def wrapper(*args, **kwargs): if settings.USE_SCHEDULER: return func.delay(*args, **kwargs) return func(*args, **kwargs) return wrapper @switchable_task @shared_task def notify_new_submission( title: str, elevator_pitch: str, submission_type: str, admin_url, topic: str, duration: int, ): slack.send_message( [ { "type": "section", "text": { "text": f"New _{submission_type}_ Submission", "type": "mrkdwn", }, } ], [ { "blocks": [ { "type": "section", "text": { "type": "mrkdwn", "text": f"*<{admin_url}|{title.capitalize()}>*\n" f"*Elevator Pitch*\n{elevator_pitch}", }, "fields": [ {"type": "mrkdwn", "text": "*Topic*"}, {"type": "mrkdwn", "text": "*Duration*"}, {"type": "plain_text", "text": str(duration)}, {"type": "mrkdwn", "text": topic}, ], } ] } ], )
Remove warning for long messages
import logging logger = logging.getLogger(__name__) def strspn(source, allowed): newchrs = [] for c in source: if c in allowed: newchrs.append(c) return u''.join(newchrs) def check_cell_phone_number(number): cleaned_number = strspn(number, u'+0123456789') if not u'+' in cleaned_number[:1]: cleaned_number = u'+%s' % cleaned_number return cleaned_number def truncate_sms(text, max_length=160): if len(text) <= max_length: return text else: logger.error("Trying to send an SMS that is too long: %s", text) return text[:max_length-3] + '...' def parse_sms(content): content = content.upper().strip() from smsgateway.backends.base import hook for keyword, subkeywords in hook.iteritems(): if content[:len(keyword)] == unicode(keyword): remainder = content[len(keyword):].strip() if '*' in subkeywords: parts = remainder.split(u' ') subkeyword = parts[0].strip() if subkeyword in subkeywords: return [keyword] + parts return keyword, remainder else: for subkeyword in subkeywords: if remainder[:len(subkeyword)] == unicode(subkeyword): subremainder = remainder[len(subkeyword):].strip() return [keyword, subkeyword] + subremainder.split() return None
import logging logger = logging.getLogger(__name__) def strspn(source, allowed): newchrs = [] for c in source: if c in allowed: newchrs.append(c) return u''.join(newchrs) def check_cell_phone_number(number): cleaned_number = strspn(number, u'+0123456789') if not u'+' in cleaned_number[:1]: cleaned_number = u'+%s' % cleaned_number return cleaned_number def truncate_sms(text, max_length=160): if len(text) <= max_length: if len(text) > 140: logger.warning("SMS possibly too long (>140 chars): %s", text) return text else: logger.error("SMS is too long (>160 chars): %s", text) return text[:max_length-3] + '...' def parse_sms(content): content = content.upper().strip() from smsgateway.backends.base import hook for keyword, subkeywords in hook.iteritems(): if content[:len(keyword)] == unicode(keyword): remainder = content[len(keyword):].strip() if '*' in subkeywords: parts = remainder.split(u' ') subkeyword = parts[0].strip() if subkeyword in subkeywords: return [keyword] + parts return keyword, remainder else: for subkeyword in subkeywords: if remainder[:len(subkeyword)] == unicode(subkeyword): subremainder = remainder[len(subkeyword):].strip() return [keyword, subkeyword] + subremainder.split() return None
Remove link constraint on media display block
<?php namespace OpenOrchestra\MediaAdminBundle\GenerateForm\Strategies; use OpenOrchestra\Backoffice\GenerateForm\Strategies\AbstractBlockStrategy; use OpenOrchestra\ModelInterface\Model\BlockInterface; use Symfony\Component\Form\FormBuilderInterface; use OpenOrchestra\Media\DisplayBlock\Strategies\DisplayMediaStrategy as BaseMediaStrategy; use Symfony\Component\Validator\Constraints\NotBlank; /** * Class DisplayMediaStrategy */ class DisplayMediaStrategy extends AbstractBlockStrategy { /** * @param BlockInterface $block * * @return bool */ public function support(BlockInterface $block) { return BaseMediaStrategy::NAME == $block->getComponent(); } /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('picture', 'oo_media_choice', array( 'constraints' => new NotBlank(), 'label' => 'open_orchestra_media_admin.block.gallery.form.pictures', )) ->add('nodeToLink', 'oo_node_choice', array( 'label' => 'open_orchestra_media_admin.block.display_media.form.node_link', 'required' => false )); } /** * Return the name of this type. * * @return string The name of this type */ public function getName() { return 'display_media'; } }
<?php namespace OpenOrchestra\MediaAdminBundle\GenerateForm\Strategies; use OpenOrchestra\Backoffice\GenerateForm\Strategies\AbstractBlockStrategy; use OpenOrchestra\ModelInterface\Model\BlockInterface; use Symfony\Component\Form\FormBuilderInterface; use OpenOrchestra\Media\DisplayBlock\Strategies\DisplayMediaStrategy as BaseMediaStrategy; use Symfony\Component\Validator\Constraints\NotBlank; /** * Class DisplayMediaStrategy */ class DisplayMediaStrategy extends AbstractBlockStrategy { /** * @param BlockInterface $block * * @return bool */ public function support(BlockInterface $block) { return BaseMediaStrategy::NAME == $block->getComponent(); } /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('picture', 'oo_media_choice', array( 'constraints' => new NotBlank(), 'label' => 'open_orchestra_media_admin.block.gallery.form.pictures', )) ->add('nodeToLink', 'oo_node_choice', array( 'constraints' => new NotBlank(), 'label' => 'open_orchestra_media_admin.block.display_media.form.node_link', 'required' => false )); } /** * Return the name of this type. * * @return string The name of this type */ public function getName() { return 'display_media'; } }
Adjust chrome and chromedriver locations
package com.blackboard.testing.driver; import com.codeborne.selenide.webdriver.WebDriverFactory; import org.openqa.selenium.Proxy; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.remote.DesiredCapabilities; public class LambdaWebDriverFactory extends WebDriverFactory { private DesiredCapabilities desiredCapabilities; public LambdaWebDriverFactory() { System.setProperty("webdriver.chrome.driver", getLibLocation("chromedriver")); DesiredCapabilities capabilities = DesiredCapabilities.chrome(); capabilities.setCapability(ChromeOptions.CAPABILITY, getLambdaChromeOptions()); capabilities.setBrowserName(this.getClass().getCanonicalName()); desiredCapabilities = capabilities; } private ChromeOptions getLambdaChromeOptions() { ChromeOptions options = new ChromeOptions(); options.setBinary(getLibLocation("chrome")); options.addArguments("--disable-gpu"); options.addArguments("--headless"); options.addArguments("--window-size=1366,768"); options.addArguments("--single-process"); options.addArguments("--no-sandbox"); options.addArguments("--user-data-dir=/tmp/user-data"); options.addArguments("--data-path=/tmp/data-path"); options.addArguments("--homedir=/tmp"); options.addArguments("--disk-cache-dir=/tmp/cache-dir"); return options; } private String getLibLocation(String lib) { return String.format("%s/lib/%s", System.getenv("LAMBDA_TASK_ROOT"), lib); } @Override public WebDriver createWebDriver(Proxy proxy) { return new ChromeDriver(desiredCapabilities); } }
package com.blackboard.testing.driver; import com.codeborne.selenide.webdriver.WebDriverFactory; import org.openqa.selenium.Proxy; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.remote.DesiredCapabilities; public class LambdaWebDriverFactory extends WebDriverFactory { private DesiredCapabilities desiredCapabilities; public LambdaWebDriverFactory() { DesiredCapabilities capabilities = DesiredCapabilities.chrome(); capabilities.setCapability(ChromeOptions.CAPABILITY, getLambdaChromeOptions()); capabilities.setBrowserName(this.getClass().getCanonicalName()); desiredCapabilities = capabilities; } private ChromeOptions getLambdaChromeOptions() { ChromeOptions options = new ChromeOptions(); options.setBinary("/var/task/chrome"); options.addArguments("--disable-gpu"); options.addArguments("--headless"); options.addArguments("--window-size=1366,768"); options.addArguments("--single-process"); options.addArguments("--no-sandbox"); options.addArguments("--user-data-dir=/tmp/user-data"); options.addArguments("--data-path=/tmp/data-path"); options.addArguments("--homedir=/tmp"); options.addArguments("--disk-cache-dir=/tmp/cache-dir"); return options; } @Override public WebDriver createWebDriver(Proxy proxy) { return new ChromeDriver(desiredCapabilities); } }
Change new String() to "".
package com.griddynamics.jagger.dbapi.fetcher; import com.griddynamics.jagger.dbapi.util.ColorCodeGenerator; import com.griddynamics.jagger.dbapi.dto.*; import java.util.*; public abstract class SummaryDbMetricDataFetcher extends DbMetricDataFetcher<MetricDto> { protected PlotDatasetDto generatePlotDatasetDto(MetricDto metricDto) { //So plot draws as {(0, val0),(1, val1), (2, val2), ... (n, valn)} List<PointDto> list = new ArrayList<PointDto>(); List<MetricValueDto> metricList = new ArrayList<MetricValueDto>(); for(MetricValueDto value :metricDto.getValues()) { metricList.add(value); } Collections.sort(metricList, new Comparator<MetricValueDto>() { @Override public int compare(MetricValueDto o1, MetricValueDto o2) { return o2.getSessionId() < o1.getSessionId() ? 1 : -1; } }); for (MetricValueDto value: metricList) { double temp = Double.parseDouble(value.getValue()); list.add(new PointDto(value.getSessionId(), temp)); } String legend = metricDto.getMetricName().getMetricDisplayName(); return new PlotDatasetDto( list, legend, ColorCodeGenerator.getHexColorCode(metricDto.getMetricName().getMetricName(), "") ); } }
package com.griddynamics.jagger.dbapi.fetcher; import com.griddynamics.jagger.dbapi.util.ColorCodeGenerator; import com.griddynamics.jagger.dbapi.dto.*; import java.util.*; public abstract class SummaryDbMetricDataFetcher extends DbMetricDataFetcher<MetricDto> { protected PlotDatasetDto generatePlotDatasetDto(MetricDto metricDto) { //So plot draws as {(0, val0),(1, val1), (2, val2), ... (n, valn)} List<PointDto> list = new ArrayList<PointDto>(); List<MetricValueDto> metricList = new ArrayList<MetricValueDto>(); for(MetricValueDto value :metricDto.getValues()) { metricList.add(value); } Collections.sort(metricList, new Comparator<MetricValueDto>() { @Override public int compare(MetricValueDto o1, MetricValueDto o2) { return o2.getSessionId() < o1.getSessionId() ? 1 : -1; } }); for (MetricValueDto value: metricList) { double temp = Double.parseDouble(value.getValue()); list.add(new PointDto(value.getSessionId(), temp)); } String legend = metricDto.getMetricName().getMetricDisplayName(); return new PlotDatasetDto( list, legend, ColorCodeGenerator.getHexColorCode(metricDto.getMetricName().getMetricName(), new String()) ); } }
Append information to the zlib error
from exporters.pipeline.base_pipeline_item import BasePipelineItem import sys import zlib import six __all__ = ['BaseDecompressor', 'ZLibDecompressor', 'NoDecompressor'] class BaseDecompressor(BasePipelineItem): def decompress(self): raise NotImplementedError() def create_decompressor(): # create zlib decompressor enabling automatic header detection: # See: http://stackoverflow.com/a/22310760/149872 AUTOMATIC_HEADER_DETECTION_MASK = 32 return zlib.decompressobj(AUTOMATIC_HEADER_DETECTION_MASK | zlib.MAX_WBITS) class ZLibDecompressor(BaseDecompressor): def decompress(self, stream): try: dec = create_decompressor() for chunk in stream: rv = dec.decompress(chunk) if rv: yield rv if dec.unused_data: stream.unshift(dec.unused_data) dec = create_decompressor() except zlib.error as e: msg = str(e) if msg.startswith('Error -3 '): msg += ". Use NoDecompressor if you're using uncompressed input." six.reraise(zlib.error, zlib.error(msg), sys.exc_info()[2]) class NoDecompressor(BaseDecompressor): def decompress(self, stream): return stream # Input already uncompressed
from exporters.pipeline.base_pipeline_item import BasePipelineItem import logging import zlib __all__ = ['BaseDecompressor', 'ZLibDecompressor', 'NoDecompressor'] class BaseDecompressor(BasePipelineItem): def decompress(self): raise NotImplementedError() def create_decompressor(): # create zlib decompressor enabling automatic header detection: # See: http://stackoverflow.com/a/22310760/149872 AUTOMATIC_HEADER_DETECTION_MASK = 32 return zlib.decompressobj(AUTOMATIC_HEADER_DETECTION_MASK | zlib.MAX_WBITS) class ZLibDecompressor(BaseDecompressor): def decompress(self, stream): try: dec = create_decompressor() for chunk in stream: rv = dec.decompress(chunk) if rv: yield rv if dec.unused_data: stream.unshift(dec.unused_data) dec = create_decompressor() except zlib.error as e: logging.error('Error decoding stream using ZlibDecompressor') if str(e).startswith('Error -3 '): logging.error("Use NoDecompressor if you're using uncompressed input") raise class NoDecompressor(BaseDecompressor): def decompress(self, stream): return stream # Input already uncompressed
Disable jaeger logging by default
from jaeger_client.config import ( DEFAULT_REPORTING_HOST, DEFAULT_REPORTING_PORT, DEFAULT_SAMPLING_PORT, Config, ) from microcosm.api import binding, defaults, typed from microcosm.config.types import boolean SPAN_NAME = "span_name" @binding("tracer") @defaults( sample_type="ratelimiting", sample_param=typed(int, 10), sampling_port=typed(int, DEFAULT_SAMPLING_PORT), reporting_port=typed(int, DEFAULT_REPORTING_PORT), reporting_host=DEFAULT_REPORTING_HOST, logging_enabled=typed(boolean, False), ) def configure_tracing(graph): """ See https://www.jaegertracing.io/docs/1.12/sampling/ for more info about available sampling strategies. """ config = Config( config={ "sampler": { "type": graph.config.tracer.sample_type, "param": graph.config.tracer.sample_param, }, "local_agent": { "sampling_port": graph.config.tracer.sampling_port, "reporting_port": graph.config.tracer.reporting_port, "reporting_host": graph.config.tracer.reporting_host, }, "logging": graph.config.tracer.logging_enabled, }, service_name=graph.metadata.name, ) return config.initialize_tracer()
from jaeger_client.config import ( DEFAULT_REPORTING_HOST, DEFAULT_REPORTING_PORT, DEFAULT_SAMPLING_PORT, Config, ) from microcosm.api import binding, defaults, typed SPAN_NAME = "span_name" @binding("tracer") @defaults( sample_type="ratelimiting", sample_param=typed(int, 10), sampling_port=typed(int, DEFAULT_SAMPLING_PORT), reporting_port=typed(int, DEFAULT_REPORTING_PORT), reporting_host=DEFAULT_REPORTING_HOST, ) def configure_tracing(graph): """ See https://www.jaegertracing.io/docs/1.12/sampling/ for more info about available sampling strategies. """ config = Config( config={ "sampler": { "type": graph.config.tracer.sample_type, "param": graph.config.tracer.sample_param, }, "local_agent": { "sampling_port": graph.config.tracer.sampling_port, "reporting_port": graph.config.tracer.reporting_port, "reporting_host": graph.config.tracer.reporting_host, }, "logging": True, }, service_name=graph.metadata.name, ) return config.initialize_tracer()
Fix syntax error and reuse variable
import json import requests class PushoverNotification(object): def __init__(self, pushover_user, pushover_token): self.pushover_api = 'https://api.pushover.net/1/messages.json' self.pushover_user = pushover_user self.pushover_token = pushover_token def get_image_content(self, image_url): return requests.get(image_url, stream=True).content def notify(self, data): if not all([self.pushover_user, self.pushover_token]): return payload = { 'user': self.pushover_user, 'token': self.pushover_token, 'title': data['title'], 'url': data['book_url'], 'url_title': data['title'], 'message': 'Today\'s Free eBook\n%s\n%s' % ( data['title'], data['description']) } try: image_content = get_image_content(data['image_url'].replace(' ', '%20')) except Exception: files = None else: files = {'attachment': ('cover.jpg', image_content)} requests.post( self.pushover_api, data=payload, files=files )
import json import requests class PushoverNotification(object): def __init__(self, pushover_user, pushover_token): self.pushover_api = 'https://api.pushover.net/1/messages.json' self.pushover_user = pushover_user self.pushover_token = pushover_token def get_image_content(self, image_url): return requests.get(image_url, stream=True).content def notify(self, data): if not all([self.pushover_user, self.pushover_token]): return payload = { 'user': self.pushover_user, 'token': self.pushover_token, 'title': data['title'], 'url': data['book_url'], 'url_title': data['title'], 'message': 'Today\'s Free eBook\n%s\n%s' % data['title'], data['description'] } try: image_content = get_image_content(data['image_url'].replace(' ', '%20')) except Exception: files = None else: files = {'attachment': ('cover.jpg', image_content)} requests.post( self.pushover_api, data=payload, files={ 'attachment': ('cover.jpg', image_content) } )
Add params to instantiate aggregation
const RasterAggregation = require('./raster-aggregation'); const VectorAggregation = require('./vector-aggregation'); const RASTER_AGGREGATION = 'RasterAggregation'; const VECTOR_AGGREGATION = 'VectorAggregation'; module.exports = class AggregationProxy { constructor (mapconfig, { resolution = 256, threshold = 10e5, placement = 'centroid', columns = {}} = {}) { this.mapconfig = mapconfig; this.resolution = resolution; this.threshold = threshold; this.placement = placement; this.columns = columns; this.implementation = this._getAggregationImplementation(); } _getAggregationImplementation () { let implementation = null; switch (this._getAggregationType()) { case VECTOR_AGGREGATION: implementation = new VectorAggregation(this.resolution, this.threshold, this.placement, this.columns); break; case RASTER_AGGREGATION: implementation = new RasterAggregation(this.resolution, this.threshold, this.placement, this.columns); break; default: throw new Error('Unsupported aggregation type'); } return implementation; } _getAggregationType () { if (this.mapconfig.isVetorLayergroup()) { return VECTOR_AGGREGATION; } return RASTER_AGGREGATION; } sql () { return this.implementation.sql(); } };
const RasterAggregation = require('./raster-aggregation'); const VectorAggregation = require('./vector-aggregation'); const RASTER_AGGREGATION = 'RasterAggregation'; const VECTOR_AGGREGATION = 'VectorAggregation'; module.exports = class AggregationProxy { constructor (mapconfig, resolution = 256, threshold = 10e5, placement = 'centroid') { this.mapconfig = mapconfig; this.resolution = resolution; this.threshold = threshold; this.placement = placement; this.implementation = this._getAggregationImplementation(); } _getAggregationImplementation () { let implementation = null; switch (this._getAggregationType()) { case VECTOR_AGGREGATION: implementation = new VectorAggregation(this.resolution, this.threshold, this.placement); break; case RASTER_AGGREGATION: implementation = new RasterAggregation(this.resolution, this.threshold, this.placement); break; default: throw new Error('Unsupported aggregation type'); } return implementation; } _getAggregationType () { if (this.mapconfig.isVetorLayergroup()) { return VECTOR_AGGREGATION; } return RASTER_AGGREGATION; } sql () { return this.implementation.sql(); } };
Fix for automatic tagging, needs to return an empty list instead of null.
//note must be set in gulp .sh config. const ServiceURL = process.env.ASSET_PROCESSING_SERVICE const Endpoints = { imageTagging: ServiceURL + "/image/tags/" } var AssetActions = { getSuggestedTags(mediaObject, callback) { switch(mediaObject.type) { case "image": fetchSuggestedImageTags(mediaObject, callback); break; default: callback([]); break; }; //todo could implement video tags through AWS and text through a NLP service? need to look at adding timecode to video tags return }, } //functions that should not be user callable function fetchSuggestedImageTags(mediaObject, callback) { console.log(Endpoints.imageTagging + encodeURIComponent(mediaObject.url)) fetch(Endpoints.imageTagging + encodeURIComponent(mediaObject.url)) .then(response => {return response.json()}) .then(json => { var tags = []; json[0].forEach(fullTag => { tags.push(fullTag.tag); //NB: fulltag includes confidence/mid etc but we don't have anywhere to put this yet. }); callback(tags); }) .catch(function (err) {console.log("Error fetching from image processing service", err)}) return } module.exports = AssetActions;
//note must be set in gulp .sh config. const ServiceURL = process.env.ASSET_PROCESSING_SERVICE const Endpoints = { imageTagging: ServiceURL + "/image/tags/" } var AssetActions = { getSuggestedTags(mediaObject, callback) { switch(mediaObject.type) { case "image": fetchSuggestedImageTags(mediaObject, callback); break; default: callback(); break; }; //todo could implement video tags through AWS and text through a NLP service? need to look at adding timecode to video tags return }, } //functions that should not be user callable function fetchSuggestedImageTags(mediaObject, callback) { console.log(Endpoints.imageTagging + encodeURIComponent(mediaObject.url)) fetch(Endpoints.imageTagging + encodeURIComponent(mediaObject.url)) .then(response => {return response.json()}) .then(json => { var tags = []; json[0].forEach(fullTag => { tags.push(fullTag.tag); //NB: fulltag includes confidence/mid etc but we don't have anywhere to put this yet. }); callback(tags); }) .catch(function (err) {console.log("Error fetching from image processing service", err)}) return } module.exports = AssetActions;
Exclude data from the deploy for now
'use strict'; module.exports = function compress(grunt) { // Load task grunt.loadNpmTasks('grunt-contrib-compress'); return { 'hmda-edit-check-api': { options: { archive: './dist/hmda-edit-check-api.zip', mode: 'zip', //zip | gzip | deflate | tgz pretty: true }, files: [ { expand: true, cwd: './', //zip all files except coverage, test dirs and the grunt/test modules src: [ '**', '!data/**', '!coverage/**', '!test/**', '!node_modules/**' ] } ] }, 'codedeploy': { options: { archive: './dist/hmda-edit-check-api-codedeploy.zip', mode: 'zip', //zip | gzip | deflate | tgz pretty: true }, files: [ { expand: true, dot: true, cwd: './', //zip dist directory src: ['dist/hmda-edit-check-api.zip', 'scripts/*', 'appspec.yml'] } ] } }; };
'use strict'; module.exports = function compress(grunt) { // Load task grunt.loadNpmTasks('grunt-contrib-compress'); return { 'hmda-edit-check-api': { options: { archive: './dist/hmda-edit-check-api.zip', mode: 'zip', //zip | gzip | deflate | tgz pretty: true }, files: [ { expand: true, cwd: './', //zip all files except coverage, test dirs and the grunt/test modules src: [ '**', '!coverage/**', '!test/**', '!node_modules/**' ] } ] }, 'codedeploy': { options: { archive: './dist/hmda-edit-check-api-codedeploy.zip', mode: 'zip', //zip | gzip | deflate | tgz pretty: true }, files: [ { expand: true, dot: true, cwd: './', //zip dist directory src: ['dist/hmda-edit-check-api.zip', 'scripts/*', 'appspec.yml'] } ] } }; };
Replace date format from HH:m to HH:mm
import React, { Component, PropTypes as PT } from "react" import { ListView, Text, View, Image, TouchableOpacity } from "react-native" import moment from "moment" import myTheme from '../../themes/base-theme' import styles from "./style" class Movie extends Component { static propTypes = { image: PT.string, title: PT.string, hours: PT.array, detail: PT.func } render() { const { image, title, hours, detail } = this.props return ( <TouchableOpacity onPress={() => detail()} activeOpacity={OPACITY} underlayColor={myTheme.primary}> <View style={styles.containerList}> <Image source={{uri: image}} defaultSource={require('../../images/backdrop.png')} style={styles.image}> <View style={styles.textIntoImage}> <Text style={styles.title} numberOfLines={1}> {title} </Text> <View style={styles.hours}> <Text style={styles.hour} numberOfLines={1}> { hours.map((hour, i) => `${moment(hour).format('HH:mm')} `) } </Text> </View> </View> </Image> </View> </TouchableOpacity> ) } } const OPACITY = 0.75 export default Movie
import React, { Component, PropTypes as PT } from "react" import { ListView, Text, View, Image, TouchableOpacity } from "react-native" import myTheme from '../../themes/base-theme' import styles from "./style" class Movie extends Component { static propTypes = { image: PT.string, title: PT.string, hours: PT.array, detail: PT.func } render() { const { image, title, hours, detail } = this.props return ( <TouchableOpacity onPress={() => detail()} activeOpacity={OPACITY} underlayColor={myTheme.primary}> <View style={styles.containerList}> <Image source={{uri: image}} defaultSource={require('../../images/backdrop.png')} style={styles.image}> <View style={styles.textIntoImage}> <Text style={styles.title} numberOfLines={1}> {title} </Text> <View style={styles.hours}> <Text style={styles.hour} numberOfLines={1}> { hours.map((hour, i) => { const date = new Date(hour) const hourFormated = date.getHours() const minutesFormated = date.getMinutes() const time = `${hourFormated}:${minutesFormated} ` return time }) } </Text> </View> </View> </Image> </View> </TouchableOpacity> ) } } const OPACITY = 0.75 export default Movie
Add color method to button item
import Item from './item'; export default class ButtonItem extends Item { constructor() { super(); this._root .classed('button', true) .styles({ 'background': '#FFF', 'cursor': 'pointer', 'height': '3em', 'justify-content': 'center', 'padding': '0.5em 0' }); this._button = this._root .append('button') .attrs({ 'tabindex': -1, 'type': 'button' }) .styles({ 'background': 'none', 'border': '1px solid transparent', 'color': 'inherit', 'cursor': 'inherit', 'line-height': '2em', 'margin': 0, 'padding': '0 0.25em' }); this._text = this._button .append('span') .styles({ 'position': 'relative' }); this._padding.styles({ 'display': 'none' }); } color(value = null) { if (value === null) { return this._root.style('color'); } this._root.style('color', value); return this; } tabindex(value = null) { if (value === null) { return this._button.attr('tabindex'); } this._button.attr('tabindex', value); return this; } text(value = null) { if (value === null) { return this._text; } this._text.text(value); return this; } _click() { if (this._disabled === false && this._model) { this._model.set(this._name, this._value); } } }
import Item from './item'; export default class ButtonItem extends Item { constructor() { super(); this._root .classed('button', true) .styles({ 'background': '#FFF', 'cursor': 'pointer', 'height': '3em', 'justify-content': 'center', 'padding': '0.5em 0' }); this._button = this._root .append('button') .attrs({ 'tabindex': -1, 'type': 'button' }) .styles({ 'background': 'none', 'border': '1px solid transparent', 'color': 'inherit', 'cursor': 'inherit', 'line-height': '2em', 'margin': 0, 'padding': '0 0.25em' }); this._text = this._button .append('span') .styles({ 'position': 'relative' }); this._padding.styles({ 'display': 'none' }); } tabindex(value = null) { if (value === null) { return this._button.attr('tabindex'); } this._button.attr('tabindex', value); return this; } text(value = null) { if (value === null) { return this._text; } this._text.text(value); return this; } _click() { if (this._disabled === false && this._model) { this._model.set(this._name, this._value); } } }
Make it easier for external apps to use oauth javascript
girder.views.oauth_LoginView = girder.View.extend({ events: { 'click .g-oauth-button': function (event) { var provider = $(event.currentTarget).attr('g-provider'); window.location = this.providers[provider]; } }, initialize: function (settings) { var redirect = settings.redirect || girder.dialogs.splitRoute(window.location.href).base; girder.restRequest({ path: 'oauth/provider', data: { redirect: redirect } }).done(_.bind(function (resp) { this.providers = resp; this.render(); }, this)); }, render: function () { var buttons = []; _.each(this.providers, function (url, provider) { var btn = this._buttons[provider]; if (btn) { btn.provider = provider; buttons.push(btn); } else { console.warn('Unsupported OAuth provider: ' + provider); } }, this); this.$el.append(girder.templates.oauth_login({ buttons: buttons })); }, _buttons: { Google: { 'icon': 'gplus', 'class': 'g-oauth-button-google' } } });
girder.views.oauth_LoginView = girder.View.extend({ events: { 'click .g-oauth-button': function (event) { var provider = $(event.currentTarget).attr('g-provider'); window.location = this.providers[provider]; } }, initialize: function () { var redirect = girder.dialogs.splitRoute(window.location.href).base; girder.restRequest({ path: 'oauth/provider', data: { redirect: redirect } }).done(_.bind(function (resp) { this.providers = resp; this.render(); }, this)); }, render: function () { var buttons = []; _.each(this.providers, function (url, provider) { var btn = this._buttons[provider]; if (btn) { btn.provider = provider; buttons.push(btn); } else { console.warn('Unsupported OAuth provider: ' + provider); } }, this); this.$el.append(girder.templates.oauth_login({ buttons: buttons })); }, _buttons: { Google: { 'icon': 'gplus', 'class': 'g-oauth-button-google' } } });
Update conversation repository: get a conversation by recipient only (not by its author)
<?php namespace FD\PrivateMessageBundle\Repository; use Doctrine\ORM\EntityRepository; use Symfony\Component\Security\Core\User\UserInterface; /** * ConversationRepository */ class ConversationRepository extends EntityRepository { /** * Get all conversations of a user being involved in as recipient or author. * * @param UserInterface $user : instance of the user. * @return array */ public function getAllByRecipient(UserInterface $user) { $qb = $this->createQueryBuilder('c') ->join('c.recipients', 'r') ->where('r.id = :user') ->setParameter('user', $user) ->orderBy('c.created', 'DESC'); return $qb->getQuery()->getResult(); } /** * Get a conversation by ID. * Related private messages, authors, recipients are loaded by a JOIN statement. * * @param int $cid : technical ID of the conversation. * @return mixed * @throws \Doctrine\ORM\NonUniqueResultException */ public function getOneById($cid) { $qb = $this->createQueryBuilder('c') ->join('c.recipients', 'r') ->join('c.messages', 'm') ->join('m.author', 'a') ->addSelect('r') ->addSelect('m') ->addSelect('a') ->where('c.id = :cid') ->setParameter('cid', $cid) ->orderBy('m.created', 'ASC'); return $qb->getQuery()->getOneOrNullResult(); } }
<?php namespace FD\PrivateMessageBundle\Repository; use Doctrine\ORM\EntityRepository; use Symfony\Component\Security\Core\User\UserInterface; /** * ConversationRepository */ class ConversationRepository extends EntityRepository { /** * Get all conversations of a user being involved in as recipient or author. * * @param UserInterface $user : instance of the user. * @return array */ public function getAllByRecipient(UserInterface $user) { $qb = $this->createQueryBuilder('c') ->join('c.recipients', 'r') ->where('r.id = :user OR c.author = :user') ->setParameter('user', $user) ->orderBy('c.created', 'DESC'); return $qb->getQuery()->getResult(); } /** * Get a conversation by ID. * Related private messages, authors, recipients are loaded by a JOIN statement. * * @param int $cid : technical ID of the conversation. * @return mixed * @throws \Doctrine\ORM\NonUniqueResultException */ public function getOneById($cid) { $qb = $this->createQueryBuilder('c') ->join('c.recipients', 'r') ->join('c.messages', 'm') ->join('m.author', 'a') ->addSelect('r') ->addSelect('m') ->addSelect('a') ->where('c.id = :cid') ->setParameter('cid', $cid) ->orderBy('m.created', 'ASC'); return $qb->getQuery()->getOneOrNullResult(); } }
Allow ValueError as a notify exception
from dbus.exceptions import DBusException try: import gi gi.require_version('Notify', '0.7') from gi.repository import Notify except (ImportError, AttributeError, ValueError): from scudcloud import notify2 Notify = None class Notifier(object): def __init__(self, app_name, icon): self.icon = icon try: if Notify is not None: Notify.init(app_name) self.notifier = Notify else: notify2.init(app_name) self.notifier = notify2 self.enabled = True except DBusException: print("WARNING: No notification daemon found! " "Notifications will be ignored.") self.enabled = False def notify(self, title, message, icon=None): if not self.enabled: return if icon is None: icon = self.icon if Notify is not None: notice = self.notifier.Notification.new(title, message, icon) else: notice = notify2.Notification(title, message, icon) notice.set_hint_string('x-canonical-append', '') try: notice.show() except: pass
from dbus.exceptions import DBusException try: import gi gi.require_version('Notify', '0.7') from gi.repository import Notify except (ImportError, AttributeError): from scudcloud import notify2 Notify = None class Notifier(object): def __init__(self, app_name, icon): self.icon = icon try: if Notify is not None: Notify.init(app_name) self.notifier = Notify else: notify2.init(app_name) self.notifier = notify2 self.enabled = True except DBusException: print("WARNING: No notification daemon found! " "Notifications will be ignored.") self.enabled = False def notify(self, title, message, icon=None): if not self.enabled: return if icon is None: icon = self.icon if Notify is not None: notice = self.notifier.Notification.new(title, message, icon) else: notice = notify2.Notification(title, message, icon) notice.set_hint_string('x-canonical-append', '') try: notice.show() except: pass
Hide the label settings for Panels since they have a title field.
export default [ { key: 'label', hidden: true, calculateValue: 'value = data.title' }, { weight: 1, type: 'textfield', input: true, placeholder: 'Panel Title', label: 'Title', key: 'title', tooltip: 'The title text that appears in the header of this panel.' }, { weight: 20, type: 'textarea', input: true, key: 'tooltip', label: 'Tooltip', placeholder: 'To add a tooltip to this field, enter text here.', tooltip: 'Adds a tooltip to the side of this field.' }, { weight: 30, type: 'select', input: true, label: 'Theme', key: 'theme', dataSrc: 'values', data: { values: [ { label: 'Default', value: 'default' }, { label: 'Primary', value: 'primary' }, { label: 'Info', value: 'info' }, { label: 'Success', value: 'success' }, { label: 'Danger', value: 'danger' }, { label: 'Warning', value: 'warning' } ] } }, { weight: 40, type: 'select', input: true, label: 'Show Breadcrumb', key: 'breadcrumb', dataSrc: 'values', data: { values: [ { label: 'Yes', value: 'default' }, { label: 'No', value: 'none' } ] } } ];
export default [ { weight: 10, type: 'textfield', input: true, placeholder: 'Panel Title', label: 'Title', key: 'title', tooltip: 'The title text that appears in the header of this panel.' }, { weight: 20, type: 'textarea', input: true, key: 'tooltip', label: 'Tooltip', placeholder: 'To add a tooltip to this field, enter text here.', tooltip: 'Adds a tooltip to the side of this field.' }, { weight: 30, type: 'select', input: true, label: 'Theme', key: 'theme', dataSrc: 'values', data: { values: [ { label: 'Default', value: 'default' }, { label: 'Primary', value: 'primary' }, { label: 'Info', value: 'info' }, { label: 'Success', value: 'success' }, { label: 'Danger', value: 'danger' }, { label: 'Warning', value: 'warning' } ] } }, { weight: 40, type: 'select', input: true, label: 'Show Breadcrumb', key: 'breadcrumb', dataSrc: 'values', data: { values: [ { label: 'Yes', value: 'default' }, { label: 'No', value: 'none' } ] } } ];
Remove unnecessary call to angular.extend.
(function (root, factory) { if (typeof define === 'function' && define.amd) { define(['exports', 'angular'], factory); } else if (typeof exports === 'object') { factory(exports, require('angular')); } else { factory((root.commonJsStrict = {}), root.angular); } }(this, function (intersect, angular) { var root = this, extendInjection = function (module, attribute) { var original = module[attribute]; return (function (name, dependencies, fn) { if (typeof fn === 'function' && angular.isArray(dependencies)) { dependencies = angular.copy(dependencies); dependencies.push(fn); } return original.call(module, name, dependencies); }); }, getWrappedComponent = function (module) { return angular.extend({}, module, { provider: extendInjection(module, 'provider'), factory: extendInjection(module, 'factory'), service: extendInjection(module, 'service'), value: extendInjection(module, 'value'), constant: extendInjection(module, 'constant'), directive: extendInjection(module, 'directive'), }); }; angular.extend(intersect, angular, { module: function () { var module = angular.extend({}, angular.module.apply(angular, arguments)); return getWrappedComponent(module); }, conflict: function (providedRoot) { if (typeof providedRoot === 'undefined') { providedRoot = root; } root.angular = intersect; } }); return intersect; }));
(function (root, factory) { if (typeof define === 'function' && define.amd) { define(['exports', 'angular'], factory); } else if (typeof exports === 'object') { factory(exports, require('angular')); } else { factory((root.commonJsStrict = {}), root.angular); } }(this, function (intersect, angular) { var root = this, extendInjection = function (module, attribute) { var original = module[attribute]; return (function (name, dependencies, fn) { if (typeof fn === 'function' && angular.isArray(dependencies)) { dependencies = angular.copy(dependencies); dependencies.push(fn); } return original.call(module, name, dependencies); }); }, getWrappedComponent = function (module) { return angular.extend({}, module, { provider: extendInjection(module, 'provider'), factory: extendInjection(module, 'factory'), service: extendInjection(module, 'service'), value: extendInjection(module, 'value'), constant: extendInjection(module, 'constant'), directive: extendInjection(module, 'directive'), }); }; angular.extend(intersect, angular); angular.extend(intersect, { module: function () { var module = angular.extend({}, angular.module.apply(angular, arguments)); return getWrappedComponent(module); }, conflict: function (providedRoot) { if (typeof providedRoot === 'undefined') { providedRoot = root; } root.angular = intersect; } }); return intersect; }));
Simplify tests for custom tokens via IAM
<?php declare(strict_types=1); namespace Kreait\Firebase\Tests\Integration\Auth; use Kreait\Firebase\Auth\CustomTokenViaGoogleIam; use Kreait\Firebase\Exception\AuthException; use Kreait\Firebase\Tests\IntegrationTestCase; use PHPUnit\Framework\AssertionFailedError; use Throwable; /** * @internal */ class CustomTokenViaGoogleIamTest extends IntegrationTestCase { /** * @var CustomTokenViaGoogleIam */ private $generator; protected function setUp() { $this->generator = new CustomTokenViaGoogleIam( self::$serviceAccount->getClientEmail(), self::$factory->createApiClient() ); } public function testCreateCustomToken() { $this->generator->createCustomToken('some-uid', ['a-claim' => 'a-value']); $this->addToAssertionCount(1); } public function testCreateCustomTokenWithAnInvalidClientEmail() { $generator = new CustomTokenViaGoogleIam('[email protected]', self::$factory->createApiClient()); try { $generator->createCustomToken('some-uid', ['kid' => '$&§']); $this->fail('An exception should have been thrown'); } catch (AuthException $e) { $this->addToAssertionCount(1); } catch (AssertionFailedError $e) { $this->fail($e->getMessage()); } catch (Throwable $e) { echo \get_class($e); $this->fail('An '.AuthException::class.' should have been thrown'); } } }
<?php declare(strict_types=1); namespace Kreait\Firebase\Tests\Integration\Auth; use Kreait\Firebase\Auth; use Kreait\Firebase\Auth\CustomTokenViaGoogleIam; use Kreait\Firebase\Tests\IntegrationTestCase; use Kreait\Firebase\Util\JSON; /** * @internal */ class CustomTokenViaGoogleIamTest extends IntegrationTestCase { /** * @var CustomTokenViaGoogleIam */ private $generator; /** * @var Auth */ private $auth; protected function setUp() { $this->generator = new CustomTokenViaGoogleIam( self::$serviceAccount->getClientEmail(), self::$factory->createApiClient() ); $this->auth = self::$firebase->getAuth(); } public function testCreateCustomToken() { $user = $this->auth->createUser([]); $idTokenResponse = $this->auth->getApiClient()->exchangeCustomTokenForIdAndRefreshToken( $this->generator->createCustomToken($user->uid, ['a-claim' => 'a-value']) ); $idToken = JSON::decode($idTokenResponse->getBody()->getContents(), true)['idToken']; $verifiedToken = $this->auth->verifyIdToken($idToken); $this->assertTrue($verifiedToken->hasClaim('a-claim')); $this->assertSame('a-value', $verifiedToken->getClaim('a-claim')); $this->assertTrue($verifiedToken->hasClaim('user_id')); $this->assertSame($user->uid, $verifiedToken->getClaim('user_id')); $this->auth->deleteUser($user->uid); } }
Fix not found page returning wrong status code
import express from 'express'; import React from 'react'; import { renderToString } from 'react-dom/server' import { RouterContext , match } from 'react-router'; import appRoutes from './shared/routes' const app = express(); app.use((req, res) => { let initialComponentHtml, isNotFoundPage = false; match({ routes: appRoutes(), location: req.url }, (error, redirectLocation, renderProps) => { if (error) { res.status(500).send(error.message); } else if (redirectLocation) { res.redirect(302, redirectLocation.pathname + redirectLocation.search); } else if (renderProps) { isNotFoundPage = renderProps.routes[1].path === '*'; initialComponentHtml = renderToString(<RouterContext {...renderProps} />); } }); const HTML = ` <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Universal Redux Demo</title> </head> <body> <div id="react-view">${initialComponentHtml}</div> <script type="application/javascript" src="/bundle.js"></script> </body> </html>`; res.status(isNotFoundPage ? 404 : 200).send(HTML); }); export default app;
import express from 'express'; import React from 'react'; import { renderToString } from 'react-dom/server' import { RouterContext , match } from 'react-router'; import appRoutes from './shared/routes' const app = express(); app.use((req, res) => { let initialComponentHtml, isNotFoundPage = false; match({ routes: appRoutes(), location: req.url }, (error, redirectLocation, renderProps) => { if (error) { res.status(500).send(error.message); } else if (redirectLocation) { res.redirect(302, redirectLocation.pathname + redirectLocation.search); } else if (renderProps) { isNotFoundPage = !renderProps.routes; initialComponentHtml = renderToString(<RouterContext {...renderProps} />); } }); const HTML = ` <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Universal Redux Demo</title> </head> <body> <div id="react-view">${initialComponentHtml}</div> <script type="application/javascript" src="/bundle.js"></script> </body> </html>`; res.status(isNotFoundPage ? 404 : 200).end(HTML); }); export default app;
Remove leftover from deleted examples
from nose.tools import * from openpassword import EncryptionKey from openpassword import Keychain from openpassword.exceptions import InvalidPasswordException import fudge class KeychainSpec: def it_unlocks_the_keychain_with_the_right_password(self): EncryptionKey = fudge.Fake('encryption_key') EncryptionKey.provides("decrypt") keychain = Keychain(EncryptionKey) keychain.unlock('rightpassword') eq_(keychain.is_locked(), False) @raises(InvalidPasswordException) def it_raises_invalidpasswordexception_with_wrong_password(self): EncryptionKey = fudge.Fake('encryption_key') EncryptionKey.provides("decrypt").raises(InvalidPasswordException) keychain = Keychain(EncryptionKey) keychain.unlock('wrongpassword') def it_fails_to_unlock_with_wrong_password(self): EncryptionKey = fudge.Fake('encryption_key') EncryptionKey.provides("decrypt").raises(InvalidPasswordException) keychain = Keychain(EncryptionKey) try: keychain.unlock('wrongpassword') except: pass eq_(keychain.is_locked(), True) def it_locks_when_lock_is_called(self): EncryptionKey = fudge.Fake('encryption_key') EncryptionKey.provides("decrypt") keychain = Keychain(EncryptionKey) keychain.unlock('rightpassword') eq_(keychain.is_locked(), False) keychain.lock() eq_(keychain.is_locked(), True)
from nose.tools import * from openpassword import EncryptionKey from openpassword import Keychain from openpassword.exceptions import InvalidPasswordException import fudge import time class KeychainSpec: def it_unlocks_the_keychain_with_the_right_password(self): EncryptionKey = fudge.Fake('encryption_key') EncryptionKey.provides("decrypt") keychain = Keychain(EncryptionKey) keychain.unlock('rightpassword') eq_(keychain.is_locked(), False) @raises(InvalidPasswordException) def it_raises_invalidpasswordexception_with_wrong_password(self): EncryptionKey = fudge.Fake('encryption_key') EncryptionKey.provides("decrypt").raises(InvalidPasswordException) keychain = Keychain(EncryptionKey) keychain.unlock('wrongpassword') def it_fails_to_unlock_with_wrong_password(self): EncryptionKey = fudge.Fake('encryption_key') EncryptionKey.provides("decrypt").raises(InvalidPasswordException) keychain = Keychain(EncryptionKey) try: keychain.unlock('wrongpassword') except: pass eq_(keychain.is_locked(), True) def it_locks_when_lock_is_called(self): EncryptionKey = fudge.Fake('encryption_key') EncryptionKey.provides("decrypt") keychain = Keychain(EncryptionKey) keychain.unlock('rightpassword') eq_(keychain.is_locked(), False) keychain.lock() eq_(keychain.is_locked(), True) class Spy: def __init__(self): self.called = False def callback(self): self.called = True
Fix source map file property
"use strict"; var gutil = require("gulp-util"); var through = require("through2"); var ngAnnotate = require("ng-annotate"); var applySourceMap = require("vinyl-sourcemaps-apply"); var merge = require("merge"); module.exports = function (options) { options = options || {add: true}; return through.obj(function (file, enc, cb) { if (file.isNull()) { this.push(file); return cb(); } if (file.isStream()) { this.emit("error", new gutil.PluginError("gulp-ng-annotate", "Streaming not supported")); return cb(); } var opts = merge({sourcemap: !!file.sourceMap}, options); if (file.path) { opts.inFile = file.relative; } var res = ngAnnotate(file.contents.toString(), opts); if (res.errors) { var filename = ""; if (file.path) { filename = file.relative + ": "; } this.emit("error", new gutil.PluginError("gulp-ng-annotate", filename + res.errors.join("\n"))); return cb(); } file.contents = new Buffer(res.src); if (opts.sourcemap && file.sourceMap) { var sourceMap = JSON.parse(res.map); sourceMap.file = file.relative.replace(/\\/g, ''); applySourceMap(file, sourceMap); } this.push(file); cb(); }); };
"use strict"; var gutil = require("gulp-util"); var through = require("through2"); var ngAnnotate = require("ng-annotate"); var applySourceMap = require("vinyl-sourcemaps-apply"); var merge = require("merge"); module.exports = function (options) { options = options || {add: true}; return through.obj(function (file, enc, cb) { if (file.isNull()) { this.push(file); return cb(); } if (file.isStream()) { this.emit("error", new gutil.PluginError("gulp-ng-annotate", "Streaming not supported")); return cb(); } var opts = merge({sourcemap: !!file.sourceMap}, options); if (file.path) { opts.inFile = file.relative; } var res = ngAnnotate(file.contents.toString(), opts); if (res.errors) { var filename = ""; if (file.path) { filename = file.relative + ": "; } this.emit("error", new gutil.PluginError("gulp-ng-annotate", filename + res.errors.join("\n"))); return cb(); } file.contents = new Buffer(res.src); if (opts.sourcemap && file.sourceMap) { var fileprop = file.sourceMap.file; applySourceMap(file, res.map); // Restore file property because source-map generator loose it for // some reason. See // <https://github.com/terinjokes/gulp-uglify/issues/53> for more // details. file.sourceMap.file = fileprop; } this.push(file); cb(); }); };
Change log priority to 'debug' when no items are available in a queue
<?php namespace Phive\TaskQueue; use Phive\Queue\Exception\ExceptionInterface; use Phive\Queue\Exception\NoItemException; abstract class AbstractExecutor { protected $context; public function __construct(ExecutionContextInterface $context) { $this->context = $context; } /** * @return bool True if a task was processed, false otherwise. */ public function execute() { $logger = $this->context->getLogger(); try { $task = $this->context->getQueue()->pop(); } catch (ExceptionInterface $e) { $e instanceof NoItemException ? $logger->debug('Nothing to execute.') : $logger->error($e->getMessage()); return false; } if (!$task instanceof TaskInterface) { $task = new Task($task); } $logger->debug(sprintf('Dequeued "%s".', $task)); try { $this->doExecute($task); $logger->info(sprintf('Task "%s" was successfully executed.', $task)); } catch (TaskFailedException $e) { $logger->error(sprintf('Task "%s" failed: %s', $task, $e->getMessage())); } catch (\Exception $e) { if ($eta = $task->reschedule()) { $logger->error(sprintf('An error occurred while executing task "%s": %s', $task, $e->getMessage())); $this->context->getQueue()->push($task, $eta); } else { $logger->error(sprintf('Task "%s" failed: %s.', $task, $e->getMessage())); } } return true; } abstract protected function doExecute(TaskInterface $task); }
<?php namespace Phive\TaskQueue; use Phive\Queue\Exception\ExceptionInterface; abstract class AbstractExecutor { protected $context; public function __construct(ExecutionContextInterface $context) { $this->context = $context; } /** * @return bool True if a task was processed, false otherwise. */ public function execute() { try { $task = $this->context->getQueue()->pop(); } catch (ExceptionInterface $e) { $this->context->getLogger()->error($e->getMessage()); return false; } if (!$task instanceof TaskInterface) { $task = new Task($task); } $logger = $this->context->getLogger(); $logger->debug(sprintf('Dequeued "%s".', $task)); try { $this->doExecute($task); $logger->info(sprintf('Task "%s" was successfully executed.', $task)); } catch (TaskFailedException $e) { $logger->error(sprintf('Task "%s" failed: %s', $task, $e->getMessage())); } catch (\Exception $e) { if ($eta = $task->reschedule()) { $logger->error(sprintf('An error occurred while executing task "%s": %s', $task, $e->getMessage())); $this->context->getQueue()->push($task, $eta); } else { $logger->error(sprintf('Task "%s" failed: %s.', $task, $e->getMessage())); } } return true; } abstract protected function doExecute(TaskInterface $task); }
chore(eslint): Add correct enviroments to eslint config
module.exports = { env: { browser: true, node: true, es6: true, mocha: true, jasmine: true, jquery: true, }, extends: 'eslint:recommended', parserOptions: { sourceType: 'script', impliedStrict: true }, rules: { 'indent': ['error', 4], 'linebreak-style': ['error', 'unix'], 'quotes': ['error', 'single'], 'semi': ['error', 'always'], 'curly': 'error', 'eqeqeq': ['error', 'always'], 'no-empty': 'error', 'no-undef': 'error', 'no-eq-null': 'error', 'no-extend-native': 'error', 'no-caller': 'error', 'new-cap': ['error', { capIsNew: false }] }, globals: { angular: true, module: true, inject: true, tagsInput: true, range: true, changeElementValue: true, customMatchers: true, KEYS: true, MAX_SAFE_INTEGER: true, SUPPORTED_INPUT_TYPES: true } };
module.exports = { env: { browser: true, node: true, es6: true }, extends: 'eslint:recommended', parserOptions: { sourceType: 'module' }, rules: { 'indent': ['error', 4], 'linebreak-style': ['error', 'unix'], 'quotes': ['error', 'single'], 'semi': ['error', 'always'], 'curly': 'error', 'eqeqeq': ['error', 'always'], 'no-empty': 'error', 'no-undef': 'error', 'no-eq-null': 'error', 'no-extend-native': 'error', 'no-caller': 'error', 'new-cap': ['error', { capIsNew: false }] }, globals: { angular: true, module: true, inject: true, jQuery: true, document: true, $: true, beforeEach: true, afterEach: true, describe: true, it: true, expect: true, jasmine: true, spyOn: true, require: true, tagsInput: true, range: true, changeElementValue: true, customMatchers: true, KEYS: true, MAX_SAFE_INTEGER: true, SUPPORTED_INPUT_TYPES: true } };
Add default value for env var
<?php return [ /* |-------------------------------------------------------------------------- | Third Party Services |-------------------------------------------------------------------------- | | This file is for storing the credentials for third party services such | as Stripe, Mailgun, Mandrill, 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' => '', 'secret' => '', ], 'mandrill' => [ 'secret' => '', ], 'ses' => [ 'key' => '', 'secret' => '', 'region' => 'us-east-1', ], 'stripe' => [ 'model' => 'App\User', 'key' => '', 'secret' => '', ], // buildkite service config for efrane/buildkite 'buildkite' => [ 'project' => env('BUILDKITE_PROJECT', ''), 'access_token' => env('BUILDKITE_ACCESS_TOKEN', ''), ], // akismet service config for efrane/akismet 'akismet' => [ 'key' => env('AKISMET_KEY'), ], 'repositories' => [ 'spec' => [ 'user' => 'OParl', 'repository' => 'spec', ], ], ];
<?php return [ /* |-------------------------------------------------------------------------- | Third Party Services |-------------------------------------------------------------------------- | | This file is for storing the credentials for third party services such | as Stripe, Mailgun, Mandrill, 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' => '', 'secret' => '', ], 'mandrill' => [ 'secret' => '', ], 'ses' => [ 'key' => '', 'secret' => '', 'region' => 'us-east-1', ], 'stripe' => [ 'model' => 'App\User', 'key' => '', 'secret' => '', ], // buildkite service config for efrane/buildkite 'buildkite' => [ 'project' => env('BUILDKITE_PROJECT'), 'access_token' => env('BUILDKITE_ACCESS_TOKEN', ''), ], // akismet service config for efrane/akismet 'akismet' => [ 'key' => env('AKISMET_KEY'), ], 'repositories' => [ 'spec' => [ 'user' => 'OParl', 'repository' => 'spec', ], ], ];
Fix failing update on change test Regression was not ran before last commit. When testing the view standalone the liveUpdate configuration ahd to be set.
/* global jasmine atom beforeEach waitsForPromise waitsFor runs describe it expect */ 'use strict' var PlantumlViewerEditor = require('../lib/plantuml-viewer-editor') var PlantumlViewerView = require('../lib/plantuml-viewer-view') describe('PlantumlViewerView', function () { var editor var view beforeEach(function () { jasmine.useRealClock() atom.config.set('plantuml-viewer.liveUpdate', true) waitsForPromise(function () { return atom.workspace.open('file.puml') }) runs(function () { editor = atom.workspace.getActiveTextEditor() }) waitsFor(function (done) { editor.onDidStopChanging(done) }) runs(function () { var viewerEditor = new PlantumlViewerEditor('uri', editor.id) view = new PlantumlViewerView(viewerEditor) jasmine.attachToDOM(view.element) }) waitsFor(function () { return view.html().indexOf('svg') !== -1 }) }) it('should contain svg generated from text editor', function () { runs(function () { expect(view.html()).toContain('svg') }) }) describe('when the editor text is modified', function () { it('should display an updated image', function () { var previousHtml runs(function () { previousHtml = view.html() editor.getBuffer().setText('A -> C') }) waitsFor(function () { return view.html() !== previousHtml }) runs(function () { expect(view.html()).not.toBe(previousHtml) }) }) }) })
/* global jasmine atom beforeEach waitsForPromise waitsFor runs describe it expect */ 'use strict' var PlantumlViewerEditor = require('../lib/plantuml-viewer-editor') var PlantumlViewerView = require('../lib/plantuml-viewer-view') describe('PlantumlViewerView', function () { var editor var view beforeEach(function () { jasmine.useRealClock() waitsForPromise(function () { return atom.workspace.open('file.puml') }) runs(function () { editor = atom.workspace.getActiveTextEditor() }) waitsFor(function (done) { editor.onDidStopChanging(done) }) runs(function () { var viewerEditor = new PlantumlViewerEditor('uri', editor.id) view = new PlantumlViewerView(viewerEditor) jasmine.attachToDOM(view.element) }) waitsFor(function () { return view.html().indexOf('svg') !== -1 }) }) it('should contain svg generated from text editor', function () { runs(function () { expect(view.html()).toContain('svg') }) }) describe('when the editor text is modified', function () { it('should display an updated image', function () { var previousHtml runs(function () { previousHtml = view.html() editor.getBuffer().setText('A -> C') }) waitsFor(function () { return view.html() !== previousHtml }) runs(function () { expect(view.html()).not.toBe(previousHtml) }) }) }) })
Fix issue with unknown "this"
define([ 'urlutils', '../../components/vue/dist/vue.min' ], function (urlutils, Vue) { 'use strict'; /* Create application_list ViewModel (will next be wrapped in a main ViewModel which will contain the applicationListView and the applicationView) */ var ApplicationListView = Vue.extend({ el: '#applist', data: function() { return { loading: true, model: { app_list: [], selected_index: null }, selected_app_callback: function() {}, // Temporary stop_application_callback: function() {} // Temporary }; }, methods: { stop_application: function(index) { this.stop_application_callback(index); } }, filters: { icon_src: function(icon_data) { return ( icon_data ? 'data:image/png;base64,' + icon_data : urlutils.path_join( window.apidata.base_url, 'static', 'images', 'generic_appicon_128.png' ) ); }, app_name: function(image) { return image.ui_name? image.ui_name: image.name; } } }); return { ApplicationListView : ApplicationListView }; });
define([ 'urlutils', '../../components/vue/dist/vue.min' ], function (urlutils, Vue) { 'use strict'; /* Create application_list ViewModel (will next be wrapped in a main ViewModel which will contain the applicationListView and the applicationView) */ var ApplicationListView = Vue.extend({ el: '#applist', data: function() { return { loading: true, model: { app_list: [], selected_index: null }, selected_app_callback: function() {}, // Temporary stop_application_callback: function() {} // Temporary }; }, methods: { stop_application: function(index) { this.stop_application_callback(index); } }, filters: { icon_src: function(icon_data) { return ( icon_data ? 'data:image/png;base64,' + icon_data : urlutils.path_join( this.base_url, 'static', 'images', 'generic_appicon_128.png' ) ); }, app_name: function(image) { return image.ui_name? image.ui_name: image.name; } } }); return { ApplicationListView : ApplicationListView }; });
Fix addColorizer and add isColorizer in gS
"use strict"; angular.module('arethusa.core').service('globalSettings', [ 'configurator', 'plugins', function(configurator, plugins) { var self = this; var confKeys = [ "alwaysDeselect", "colorizer" ]; self.defaultConf = { alwaysDeselect: false, colorizer: 'morph' }; function configure() { self.conf = configurator.configurationFor('main').globalSettings || {}; configurator.delegateConf(self, confKeys, true); // true makes them sticky self.settings = {}; self.colorizers = {}; defineSettings(); } function Conf(property, type, options) { this.property = property; this.label = "globalSettings." + property; this.type = type || 'checkbox'; if (this.type === 'select') { this.options = options; } } function defineSettings() { defineSetting('alwaysDeselect'); defineSetting('colorizer', 'select', self.colorizers); } function defineSetting(property, type, options) { self.settings[property] = new Conf(property, type, options); } this.toggle = function() { self.active = !self.active; }; this.addColorizer = function(pluginName) { self.colorizers[pluginName] = true; }; this.isColorizer = function(pluginName) { return self.colorizer === pluginName; }; configure(); } ]);
"use strict"; angular.module('arethusa.core').service('globalSettings', [ 'configurator', 'plugins', function(configurator, plugins) { var self = this; // Need to do this lazy to avoid circular dependencies! var lazyState; function state() { if (!lazyState) lazyState = $injector.get('state'); return lazyState; } var confKeys = [ "alwaysDeselect", "colorizer" ]; self.defaultConf = { alwaysDeselect: false, colorizer: 'morph' }; function configure() { self.conf = configurator.configurationFor('main').globalSettings || {}; configurator.delegateConf(self, confKeys, true); // true makes them sticky self.settings = {}; self.colorizers = {}; defineSettings(); } function Conf(property, type, options) { this.property = property; this.label = "globalSettings." + property; this.type = type || 'checkbox'; if (this.type === 'select') { this.options = options; } } function defineSettings() { defineSetting('alwaysDeselect'); defineSetting('colorizer', 'select', self.colorizers); } function defineSetting(property, type, options) { self.settings[property] = new Conf(property, type, options); } this.toggle = function() { self.active = !self.active; }; configure(); } ]);
[StarQuest] Update only the changed Vault service
package com.starquestminecraft.bukkit; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.server.ServiceRegisterEvent; import org.bukkit.event.server.ServiceUnregisterEvent; import org.bukkit.plugin.java.JavaPlugin; import net.milkbowl.vault.chat.Chat; import net.milkbowl.vault.economy.Economy; import net.milkbowl.vault.permission.Permission; public class SQBase extends JavaPlugin { private static SQBase instance; public static SQBase getInstance() { return instance; } @Override public void onLoad() { instance = this; saveDefaultConfig(); StarQuest.initialize(this); } @Override public void onEnable() { StarQuest.setupVault(this); } @EventHandler(priority = EventPriority.MONITOR) void onServiceRegister(final ServiceRegisterEvent event) { onServiceChange(event.getProvider().getService()); } @EventHandler(priority = EventPriority.MONITOR) void onServiceRegister(final ServiceUnregisterEvent event) { onServiceChange(event.getProvider().getService()); } private void onServiceChange(final Class<?> service) { if(service.equals(Chat.class)) { StarQuest.setupVaultChat(this); } else if(service.equals(Economy.class)) { StarQuest.setupVaultEconomy(this); } else if(service.equals(Permission.class)) { StarQuest.setupVaultPermission(this); } } }
package com.starquestminecraft.bukkit; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.server.ServiceRegisterEvent; import org.bukkit.event.server.ServiceUnregisterEvent; import org.bukkit.plugin.java.JavaPlugin; import net.milkbowl.vault.chat.Chat; import net.milkbowl.vault.economy.Economy; import net.milkbowl.vault.permission.Permission; public class SQBase extends JavaPlugin { private static SQBase instance; public static SQBase getInstance() { return instance; } @Override public void onLoad() { instance = this; saveDefaultConfig(); StarQuest.initialize(this); } @Override public void onEnable() { StarQuest.setupVault(this); } @EventHandler(priority = EventPriority.MONITOR) void onServiceRegister(final ServiceRegisterEvent event) { Class<?> service = event.getProvider().getService(); if(service.equals(Chat.class) || service.equals(Economy.class) || service.equals(Permission.class)) { StarQuest.setupVault(this); } } @EventHandler(priority = EventPriority.MONITOR) void onServiceRegister(final ServiceUnregisterEvent event) { Class<?> service = event.getProvider().getService(); if(service.equals(Chat.class) || service.equals(Economy.class) || service.equals(Permission.class)) { StarQuest.setupVault(this); } } }
Support setLevel() with a stub
// Miscellaneous helpers // // log4js is optional. function getLogger(label) { var log; try { log = require('log4js')().getLogger(scrub_creds(label || 'audit_couchdb')); log.setLevel('info'); } catch(e) { log = { "trace": function() {} , "debug": function() {} , "info" : console.log , "warn" : console.log , "error": console.log , "fatal": console.log } log.setLevel = function noop() {}; } // Scrub credentials. ; ['trace', 'debug', 'info', 'warn', 'error', 'fatal'].forEach(function(level) { var inner = log[level]; log[level] = function log_scrubbed() { var args = Array.prototype.slice.apply(arguments); args[0] = scrub_creds(args[0]); return inner.apply(this, args); } }) return log; } function scrub_creds(url) { if(typeof url === 'string') url = url.replace(/(https?:\/\/)[^:]+:[^@]+@(.*)$/, '$1$2'); // Scrub username and password return url; } function join_and_fix_slashes() { return Array.prototype.map.apply(arguments, [function trimmed(arg) { return arg.replace(/^\/+/, "").replace(/\/+$/, ""); }]).join('/'); } module.exports = { "getLogger" : getLogger , "join" : join_and_fix_slashes };
// Miscellaneous helpers // // log4js is optional. function getLogger(label) { var log; try { log = require('log4js')().getLogger(scrub_creds(label || 'audit_couchdb')); log.setLevel('info'); } catch(e) { log = { "trace": function() {} , "debug": function() {} , "info" : console.log , "warn" : console.log , "error": console.log , "fatal": console.log } } // Scrub credentials. ; ['trace', 'debug', 'info', 'warn', 'error', 'fatal'].forEach(function(level) { var inner = log[level]; log[level] = function log_scrubbed() { var args = Array.prototype.slice.apply(arguments); args[0] = scrub_creds(args[0]); return inner.apply(this, args); } }) return log; } function scrub_creds(url) { if(typeof url === 'string') url = url.replace(/(https?:\/\/)[^:]+:[^@]+@(.*)$/, '$1$2'); // Scrub username and password return url; } function join_and_fix_slashes() { return Array.prototype.map.apply(arguments, [function trimmed(arg) { return arg.replace(/^\/+/, "").replace(/\/+$/, ""); }]).join('/'); } module.exports = { "getLogger" : getLogger , "join" : join_and_fix_slashes };
Add default argument for profile
import argparse import os import re from firefed import Firefed from feature import feature_map, Summary def feature_type(val): try: return feature_map()[val] except KeyError as key: raise argparse.ArgumentTypeError( 'Feature %s not found. Choose from: {%s}' % (key, ', '.join(feature_map()))) def profile_dir(dirname): if dirname is None: dirname = 'default' if os.path.isdir(dirname): return dirname if re.match('^[\\w-]+$', dirname): home = os.path.expanduser('~/.mozilla/firefox') profile_names = os.listdir(home) for name in profile_names: if name.endswith('.%s' % dirname): return os.path.join(home, name) raise argparse.ArgumentTypeError('Profile %s not found.' % dirname) def main(): parser = argparse.ArgumentParser( 'firefed', description= 'Firefed is a Firefox profile analyzer focusing on privacy and security.', ) parser.add_argument( '-p', '--profile', help='profile name or directory', type=profile_dir, default='default') parser.add_argument( '-f', '--feature', type=feature_type, default=Summary, help='{%s}' % ', '.join(feature_map())) parser.add_argument( '-s', '--summarize', action='store_true', help='summarize results') args = parser.parse_args() Firefed(args) if __name__ == '__main__': main()
import argparse import os import re from firefed import Firefed from feature import feature_map, Summary def feature_type(val): try: return feature_map()[val] except KeyError as key: raise argparse.ArgumentTypeError( 'Feature %s not found. Choose from: {%s}' % (key, ', '.join(feature_map()))) def profile_dir(dirname): if dirname is None: dirname = 'default' if os.path.isdir(dirname): return dirname if re.match('^[\\w-]+$', dirname): home = os.path.expanduser('~/.mozilla/firefox') profile_names = os.listdir(home) for name in profile_names: if name.endswith('.%s' % dirname): return os.path.join(home, name) raise argparse.ArgumentTypeError('Profile %s not found.' % dirname) def main(): parser = argparse.ArgumentParser( 'firefed', description= 'Firefed is a Firefox profile analyzer focusing on privacy and security.', ) parser.add_argument( '-p', '--profile', help='profile name or directory', type=profile_dir, required=True) parser.add_argument( '-f', '--feature', type=feature_type, default=Summary, help='{%s}' % ', '.join(feature_map())) parser.add_argument( '-s', '--summarize', action='store_true', help='summarize results') args = parser.parse_args() Firefed(args) if __name__ == '__main__': main()
Use Config in bind function
<?php namespace Adldap\Laravel; use Adldap\Adldap; use Adldap\Laravel\Exceptions\ConfigurationMissingException; use Illuminate\Support\ServiceProvider; class AdldapServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Run service provider boot operations. */ public function boot() { $config = __DIR__.'/Config/config.php'; $this->mergeConfigFrom($config, 'adldap'); $this->publishes([ $config => config_path('adldap.php'), ], 'adldap'); } /** * Register the service provider. */ public function register() { // Bind the Adldap instance to the IoC $this->app->bind('adldap', function() { $config = $this->app['config']->get('adldap'); // Verify configuration if(is_null($config)) { $message = 'Adldap configuration could not be found. Try re-publishing using `php artisan vendor:publish`.'; throw new ConfigurationMissingException($message); } return new Adldap($config['connection_settings'], new $config['connection'], $config['auto_connect']); }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return ['adldap']; } }
<?php namespace Adldap\Laravel; use Adldap\Adldap; use Adldap\Laravel\Exceptions\ConfigurationMissingException; use Illuminate\Support\ServiceProvider; class AdldapServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Run service provider boot operations. */ public function boot() { $config = __DIR__.'/Config/config.php'; $this->mergeConfigFrom($config, 'adldap'); $this->publishes([ $config => config_path('adldap.php'), ], 'adldap'); } /** * Register the service provider. */ public function register() { $config = $this->app['config']->get('adldap'); // Bind the Adldap instance to the IoC $this->app->bind('adldap', function() use ($config) { // Verify configuration if(is_null($config)) { $message = 'Adldap configuration could not be found. Try re-publishing using `php artisan vendor:publish`.'; throw new ConfigurationMissingException($message); } return new Adldap($config['connection_settings'], new $config['connection'], $config['auto_connect']); }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return ['adldap']; } }
Create a financial year to test with
import json from infrastructure.models import FinancialYear from django.test import ( TransactionTestCase, Client, override_settings, ) from . import ( import_data, ) from .resources import ( GeographyResource, MunicipalityProfileResource, MedianGroupResource, RatingCountGroupResource, ) @override_settings( SITE_ID=2, STATICFILES_STORAGE="django.contrib.staticfiles.storage.StaticFilesStorage", ) class GeographyDetailViewTestCase(TransactionTestCase): serialized_rollback = True def test_context(self): # Import sample data import_data( GeographyResource, "views/scorecard_geography.csv", ) import_data( MunicipalityProfileResource, "views/municipality_profile.csv", ) import_data( MedianGroupResource, "views/median_group.csv", ) import_data( RatingCountGroupResource, "views/rating_count_group.csv", ) fy = FinancialYear.objects.create(budget_year="2019/2020") # Make request client = Client() response = client.get("/profiles/municipality-CPT-city-of-cape-town/") context = response.context page_data = json.loads(context["page_data_json"]) # Test for amount types self.assertIsInstance(page_data["amount_types_v1"], dict) # Test for cube names self.assertIsInstance(page_data["cube_names"], dict) # Test for municipality category descriptions self.assertIsInstance(page_data["municipal_category_descriptions"], dict)
import json from django.test import ( TransactionTestCase, Client, override_settings, ) from . import ( import_data, ) from .resources import ( GeographyResource, MunicipalityProfileResource, MedianGroupResource, RatingCountGroupResource, ) @override_settings( SITE_ID=2, STATICFILES_STORAGE="django.contrib.staticfiles.storage.StaticFilesStorage", ) class GeographyDetailViewTestCase(TransactionTestCase): serialized_rollback = True def test_context(self): # Import sample data import_data( GeographyResource, "views/scorecard_geography.csv", ) import_data( MunicipalityProfileResource, "views/municipality_profile.csv", ) import_data( MedianGroupResource, "views/median_group.csv", ) import_data( RatingCountGroupResource, "views/rating_count_group.csv", ) # Make request client = Client() response = client.get("/profiles/municipality-CPT-city-of-cape-town/") context = response.context page_data = json.loads(context["page_data_json"]) # Test for amount types self.assertIsInstance(page_data["amount_types_v1"], dict) # Test for cube names self.assertIsInstance(page_data["cube_names"], dict) # Test for municipality category descriptions self.assertIsInstance(page_data["municipal_category_descriptions"], dict)
Fix environment:delete, don't allow it to delete master.
<?php namespace CommerceGuys\Platform\Cli\Command; use Guzzle\Http\ClientInterface; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Yaml\Dumper; class EnvironmentDeleteCommand extends EnvironmentCommand { protected function configure() { $this ->setName('environment:delete') ->setDescription('Delete an environment.') ->addOption( 'project', null, InputOption::VALUE_OPTIONAL, 'The project id' ) ->addOption( 'environment', null, InputOption::VALUE_OPTIONAL, 'The environment id' ); } protected function execute(InputInterface $input, OutputInterface $output) { if (!$this->validateInput($input, $output)) { return; } if ($this->environment['id'] == 'master') { $output->writeln("<error>Can't delete master.</error>"); return; } $client = $this->getPlatformClient($this->environment['endpoint']); $client->deleteEnvironment(); // Refresh the stored environments, to trigger a drush alias rebuild. $this->getEnvironments($this->project, TRUE); $environmentId = $this->environment['id']; $message = '<info>'; $message = "\nThe environment $environmentId has been deleted. \n"; $message .= "</info>"; $output->writeln($message); } }
<?php namespace CommerceGuys\Platform\Cli\Command; use Guzzle\Http\ClientInterface; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Yaml\Dumper; class EnvironmentDeleteCommand extends EnvironmentCommand { protected function configure() { $this ->setName('environment:delete') ->setDescription('Delete an environment.') ->addArgument( 'environment', InputArgument::OPTIONAL, 'The environment id' ) ->addOption( 'project', null, InputOption::VALUE_OPTIONAL, 'The project id' ); } protected function execute(InputInterface $input, OutputInterface $output) { if (!$this->validateInput($input, $output)) { return; } $client = $this->getPlatformClient($this->environment['endpoint']); $client->deleteEnvironment(); // Refresh the stored environments, to trigger a drush alias rebuild. $this->getEnvironments($this->project, TRUE); $environmentId = $input->getArgument('environment-id'); $message = '<info>'; $message = "\nThe environment $environmentId has been deleted. \n"; $message .= "</info>"; $output->writeln($message); } }
Add strings and function definitions, attributions.
/* Language: AppleScript Authors: Nathan Grigg <[email protected]> Dr. Drang <[email protected]> */ function(hljs) { var STRINGS = [ hljs.APOS_STRING_MODE, hljs.QUOTE_STRING_MODE ]; var TITLE = { className: 'title', begin: hljs.UNDERSCORE_IDENT_RE }; var PARAMS = { className: 'params', begin: '\\(', end: '\\)', contains: ['self', hljs.C_NUMBER_MODE].concat(STRINGS) }; return { defaultMode: { keywords: { keyword: 'about above after against and around as at back before beginning ' + 'behind below beneath beside between but by considering contain ' + 'contain contains continue copy div does eighth else end equal ' + 'equals error every exit fifth first for fourth from front ' + 'get given global if ignoring in into is it its last local ' + 'middle mod ninth not of on onto or over prop property put ref ' + 'reference repeat return returning script second set seventh since ' + 'since sixth some tell tenth that the then third through thru ' + 'timeout times to transaction try until where while whose with ' + 'without', built_in: 'true false me my' }, contains: [ hljs.inherit(hljs.QUOTE_STRING_MODE, {illegal: ''}), hljs.HASH_COMMENT_MODE, { className: 'comment', begin: '--', end: '$' }, { className: 'comment', begin: '\\(\\*', end: '\\*\\)' }, hljs.C_NUMBER_MODE, { className: 'function_start', beginWithKeyword: true, keywords: 'on', illegal: '[${=;\\n]', contains: [TITLE, PARAMS], relevance: 10 } ] } }; }
/* Language: AppleScript */ function(hljs) { return { defaultMode: { keywords: { keyword: 'about above after against and around as at back before beginning ' + 'behind below beneath beside between but by considering contain ' + 'contain contains continue copy div does eighth else end equal ' + 'equals error every exit fifth first for fourth from front ' + 'get given global if ignoring in into is it its last local ' + 'middle mod ninth not of on onto or over prop property put ref ' + 'reference repeat return returning script second set seventh since ' + 'since sixth some tell tenth that the then third through thru ' + 'timeout times to transaction try until where while whose with ' + 'without', built_in: 'true false me my' }, contains: [ hljs.inherit(hljs.QUOTE_STRING_MODE, {illegal: ''}), hljs.HASH_COMMENT_MODE, { className: 'comment', begin: '--', end: '$' }, { className: 'comment', begin: '\\(\\*', end: '\\*\\)' }, hljs.C_NUMBER_MODE, ] } }; }