text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Test is still disabled, but access through public module
from test.test_support import vereq, TestFailed import symtable symbols = symtable.symtable("def f(x): return x", "?", "exec") ## XXX ## Test disabled because symtable module needs to be rewritten for new compiler ##vereq(symbols[0].name, "global") ##vereq(len([ste for ste in symbols.values() if ste.name == "f"]), 1) ### Bug tickler: SyntaxError file name correct whether error raised ### while parsing or building symbol table. ##def checkfilename(brokencode): ## try: ## _symtable.symtable(brokencode, "spam", "exec") ## except SyntaxError, e: ## vereq(e.filename, "spam") ## else: ## raise TestFailed("no SyntaxError for %r" % (brokencode,)) ##checkfilename("def f(x): foo)(") # parse-time ##checkfilename("def f(x): global x") # symtable-build-time
from test.test_support import vereq, TestFailed import _symtable symbols = _symtable.symtable("def f(x): return x", "?", "exec") ## XXX ## Test disabled because symtable module needs to be rewritten for new compiler ##vereq(symbols[0].name, "global") ##vereq(len([ste for ste in symbols.values() if ste.name == "f"]), 1) ### Bug tickler: SyntaxError file name correct whether error raised ### while parsing or building symbol table. ##def checkfilename(brokencode): ## try: ## _symtable.symtable(brokencode, "spam", "exec") ## except SyntaxError, e: ## vereq(e.filename, "spam") ## else: ## raise TestFailed("no SyntaxError for %r" % (brokencode,)) ##checkfilename("def f(x): foo)(") # parse-time ##checkfilename("def f(x): global x") # symtable-build-time
Complete the information for the help-plugin
<?php require_once __DIR__ . '/vendor/autoload.php'; use jlawrence\eos\Parser; use jlawrence\eos\Graph; class math extends Script { protected $helpMessage = "'graph EXPRESSION': Returns a plotted graph of the expression\n" ."'math EXPRESSION': Returns the solvement of the given expression\n"; protected $description = 'Solve mathematical expressions'; public function run() { if(strtolower(split(' ', $this->matches[0])[0]) === 'math') { return $this->send(Parser::solve($this->matches[1])); } else { $filepath = __DIR__ . '/ouput.png'; Graph::init(640, 840); Graph::graph($this->matches[1], -10, 10, 0.01, true, false, -10, 10); if(file_exists($filepath)) { unlink($filepath); } if(imagepng(Graph::getImage(), $filepath)) { return $this->send($filepath, 'image'); } else { return $this->send('Graph generation unsuccessful'); } } } }
<?php require_once __DIR__ . '/vendor/autoload.php'; use jlawrence\eos\Parser; use jlawrence\eos\Graph; class math extends Script { public function run() { if(strtolower(split(' ', $this->matches[0])[0]) === 'math') { return $this->send(Parser::solve($this->matches[1])); } else { $filepath = __DIR__ . '/ouput.png'; Graph::init(640, 840); Graph::graph($this->matches[1], -10, 10, 0.01, true, false, -10, 10); if(file_exists($filepath)) { unlink($filepath); } if(imagepng(Graph::getImage(), $filepath)) { return $this->send($filepath, 'image'); } else { return $this->send('Graph generation unsuccessful'); } } } }
Make surveyId a number input type field (HTML5)
<!-- resources/views/surveys/surveys_addReport.blade.php --> @extends('layouts.app') @section('content') <h2>Add survey report</h2> <form class="form-inline" action="/surveys/storeReport" method="post" enctype="multipart/form-data"> <div class="form-group"> {{ csrf_field() }} {{ method_field('PUT') }} <p><label for="surveyId">Survey ID: </label> <input class="form-control" type="number" id="surveyId" name="surveyId"></p> <p><label for="surveyReport">Upload survey report: </label> <input class="form-control" type="file" id="surveyReport" name="surveyReport" ></p> <p><button type="submit">Submit survey report</button> / <a href="/">Main</a></p> </div> </form> @endsection
<!-- resources/views/surveys/surveys_addReport.blade.php --> @extends('layouts.app') @section('content') <h2>Add survey report</h2> <form class="form-inline" action="/surveys/storeReport" method="post" enctype="multipart/form-data"> <div class="form-group"> {{ csrf_field() }} {{ method_field('PUT') }} <p><label for="surveyId">Survey ID: </label> <input class="form-control" type="text" id="surveyId" name="surveyId"></p> <p><label for="surveyReport">Upload survey report: </label> <input class="form-control" type="file" id="surveyReport" name="surveyReport" ></p> <p><button type="submit">Submit survey report</button> / <a href="/">Main</a></p> </div> </form> @endsection
Remove css import, add global styles
import React from "react"; import { render } from "react-dom"; import { applyRouterMiddleware, Router, Route, browserHistory, IndexRoute } from "react-router"; import { useScroll } from 'react-router-scroll'; import App from "./components/App.react"; import TagList from "./components/TagList.react"; import NotFound from "./components/NotFound"; import PluginList from "./components/PluginList.react"; import { syncHistoryWithStore } from "react-router-redux"; import store from "./stores/CreateStore"; import { Provider } from "react-redux"; import "whatwg-fetch"; import globalStyes from './global-styles'; import Tags from "./tags"; const history = syncHistoryWithStore(browserHistory, store); var routes = ( <Router history={history} render={applyRouterMiddleware(useScroll())}> <Route path="/" component={App}> <IndexRoute component={TagList} /> { Tags.map((tag) => <Route key={tag} path={`tag/${tag}`} component={PluginList} tag={tag} />) } <Route path="*" component={NotFound} /> </Route> </Router> ) render( <Provider store={store}> {routes} </Provider>, document.getElementById('app') );
import React from "react"; import { render } from "react-dom"; import { applyRouterMiddleware, Router, Route, browserHistory, IndexRoute } from "react-router"; import { useScroll } from 'react-router-scroll'; import App from "./components/App.react"; import TagList from "./components/TagList.react"; import NotFound from "./components/NotFound"; import PluginList from "./components/PluginList.react"; import { syncHistoryWithStore } from "react-router-redux"; import store from "./stores/CreateStore"; import { Provider } from "react-redux"; import "whatwg-fetch"; import Css from "../css/main.css"; import Tags from "./tags"; const history = syncHistoryWithStore(browserHistory, store); var routes = ( <Router history={history} render={applyRouterMiddleware(useScroll())}> <Route path="/" component={App}> <IndexRoute component={TagList} /> { Tags.map((tag) => <Route key={tag} path={`tag/${tag}`} component={PluginList} tag={tag} />) } <Route path="*" component={NotFound} /> </Route> </Router> ) render( <Provider store={store}> {routes} </Provider>, document.getElementById('app') );
Fix Django dependency: update Django version from 1.4 to 1.8
from distutils.core import setup import sslserver setup(name="django-sslserver", version=sslserver.__version__, author="Ted Dziuba", author_email="tjdziuba@gmail.com", description="An SSL-enabled development server for Django", url="https://github.com/teddziuba/django-sslserver", packages=["sslserver", "sslserver.management", "sslserver.management.commands"], package_dir={"sslserver": "sslserver"}, package_data={"sslserver": ["certs/development.crt", "certs/development.key", "certs/server.csr"]}, install_requires=["setuptools", "Django >= 1.8"], license="MIT" )
from distutils.core import setup import sslserver setup(name="django-sslserver", version=sslserver.__version__, author="Ted Dziuba", author_email="tjdziuba@gmail.com", description="An SSL-enabled development server for Django", url="https://github.com/teddziuba/django-sslserver", packages=["sslserver", "sslserver.management", "sslserver.management.commands"], package_dir={"sslserver": "sslserver"}, package_data={"sslserver": ["certs/development.crt", "certs/development.key", "certs/server.csr"]}, install_requires=["setuptools", "Django >= 1.4"], license="MIT" )
feat(client): Use localForage instead of localStorage
const localForage = require('localforage') class persist { static get SESSION_TOKEN_KEY() { return 'sessionToken' } static get ACCESS_TOKEN_KEY() { return 'accessToken' } static async willGetSessionToken() { return localForage.getItem(persist.SESSION_TOKEN_KEY).catch(err => err) } static async willSetSessionToken(value) { return localForage.setItem(persist.SESSION_TOKEN_KEY, value).catch(err => err) } static async willRemoveSessionToken() { return localForage.removeItem(persist.SESSION_TOKEN_KEY).catch(err => err) } static async willGetAccessToken() { return localForage.getItem(persist.ACCESS_TOKEN_KEY).catch(err => err) } static async willSetAccessToken(value) { return localForage.setItem(persist.ACCESS_TOKEN_KEY, value).catch(err => err) } static async willRemoveAccessToken() { return localForage.removeItem(persist.ACCESS_TOKEN_KEY).catch(err => err) } } module.exports = persist
class persist { static get SESSION_TOKEN_KEY () { return 'sessionToken' } static willGetSessionToken() { return new Promise(resolve => { try { resolve(localStorage && localStorage.getItem(persist.SESSION_TOKEN_KEY)) } catch (err) { resolve(null) } }) } static willSetSessionToken(sessionToken) { return !sessionToken ? persist.willRemoveSessionToken : new Promise(resolve => { try { localStorage && localStorage.setItem(persist.SESSION_TOKEN_KEY, sessionToken) } catch (err) { // Ignore } resolve(sessionToken) }) } static willRemoveSessionToken() { return new Promise(resolve => { try { localStorage && localStorage.removeItem(persist.SESSION_TOKEN_KEY) } catch (err) { // Ignore } resolve(null) }) } } module.exports = persist
Fix retrieval of model under viewsets without a statically defined queryset
from rest_framework.exceptions import APIException from rest_framework.serializers import ModelSerializer WRITE_OPERATIONS = ['create', 'update', 'partial_update', 'delete'] class ServiceUnavailable(APIException): status_code = 503 default_detail = "Service temporarily unavailable, please try again later." class WritableSerializerMixin(object): """ Returns a flat Serializer from the given model suitable for write operations (POST, PUT, PATCH). This is necessary to allow write operations on objects which utilize nested serializers. """ def get_serializer_class(self): class WritableSerializer(ModelSerializer): class Meta: model = self.get_queryset().model fields = '__all__' if self.action in WRITE_OPERATIONS: return WritableSerializer return self.serializer_class
from rest_framework.exceptions import APIException from rest_framework.serializers import ModelSerializer WRITE_OPERATIONS = ['create', 'update', 'partial_update', 'delete'] class ServiceUnavailable(APIException): status_code = 503 default_detail = "Service temporarily unavailable, please try again later." class WritableSerializerMixin(object): """ Returns a flat Serializer from the given model suitable for write operations (POST, PUT, PATCH). This is necessary to allow write operations on objects which utilize nested serializers. """ def get_serializer_class(self): class WritableSerializer(ModelSerializer): class Meta: model = self.queryset.model fields = '__all__' if self.action in WRITE_OPERATIONS: return WritableSerializer return self.serializer_class
Trim surrounding whitespace before validating HTML with slowparse Slowparse incorrectly reports an error if the `DOCTYPE` is preceded by a line of whitespace.
var Promise = require('es6-promise').Promise; var groupBy = require('lodash/groupBy'); var values = require('lodash/values'); var flatten = require('lodash/flatten'); var flatMap = require('lodash/flatMap'); var sortBy = require('lodash/sortBy'); var omit = require('lodash/omit'); var trim = require('lodash/trim'); var validateWithHtmllint = require('./html/htmllint.js'); var validateWithSlowparse = require('./html/slowparse.js'); function filterErrors(errors) { var groupedErrors = groupBy(errors, 'reason'); var suppressedTypes = flatMap( flatten(values(groupedErrors)), 'suppresses' ); return flatten(values(omit(groupedErrors, suppressedTypes))); } module.exports = function(source) { return Promise.all([ validateWithSlowparse(trim(source)), validateWithHtmllint(source), ]).then(function(results) { var filteredErrors = filterErrors(flatten(results)); return sortBy(filteredErrors, 'row'); }); };
var Promise = require('es6-promise').Promise; var groupBy = require('lodash/groupBy'); var values = require('lodash/values'); var flatten = require('lodash/flatten'); var flatMap = require('lodash/flatMap'); var sortBy = require('lodash/sortBy'); var omit = require('lodash/omit'); var validateWithHtmllint = require('./html/htmllint.js'); var validateWithSlowparse = require('./html/slowparse.js'); function filterErrors(errors) { var groupedErrors = groupBy(errors, 'reason'); var suppressedTypes = flatMap( flatten(values(groupedErrors)), 'suppresses' ); return flatten(values(omit(groupedErrors, suppressedTypes))); } module.exports = function(source) { return Promise.all([ validateWithSlowparse(source), validateWithHtmllint(source), ]).then(function(results) { var filteredErrors = filterErrors(flatten(results)); return sortBy(filteredErrors, 'row'); }); };
Fix networkx 1.11 compatibility issue
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str import json from os import path from indra.util.kappa_util import im_json_to_graph def test_kappy_influence_json_to_graph(): with open(path.join(path.dirname(path.abspath(__file__)), 'kappy_influence.json'), 'r') as f: imap = json.load(f) graph = im_json_to_graph(imap) assert graph is not None, 'No graph produced.' n_nodes = len(graph.nodes()) n_edges = len(graph.edges()) assert n_nodes == 13, \ 'Wrong number (%d vs. %d) of nodes on the graph.' % (n_nodes, 13) assert n_edges == 6, \ "Wrong number (%d vs. %d) of edges on graph." % (n_edges, 4)
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str import json from os import path from indra.util.kappa_util import im_json_to_graph def test_kappy_influence_json_to_graph(): with open(path.join(path.dirname(path.abspath(__file__)), 'kappy_influence.json'), 'r') as f: imap = json.load(f) graph = im_json_to_graph(imap) assert graph is not None, 'No graph produced.' n_nodes = len(graph.nodes) n_edges = len(graph.edges) assert n_nodes == 13, \ 'Wrong number (%d vs. %d) of nodes on the graph.' % (n_nodes, 13) assert n_edges == 6, \ "Wrong number (%d vs. %d) of edges on graph." % (n_edges, 4)
Add some blank lines for readability
<?php namespace Opdavies\Sculpin\Bundle\ContentGeneratorBundle\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Filesystem\Filesystem; trait CreateTrait { private function createFile( InputInterface $input, OutputInterface $output, $subDir, $content ) { $path[] = $this->getContainer()->getParameter('sculpin.source_dir'); $path[] = $subDir; $path[] = $filename = $input->getOption('filename'); $path = implode(DIRECTORY_SEPARATOR, $path); /** @var Filesystem $filesystem */ $filesystem = $this->getContainer()->get('filesystem'); if (!$filesystem->exists($path) || $input->getOption('force')) { $filesystem->dumpFile($path, $content); $output->writeln('<info>' . sprintf('%s has been created.', $filename) . '</info>'); } else { $output->writeln('<error>' . sprintf('%s already exists.', $filename) . '</error>'); } } }
<?php namespace Opdavies\Sculpin\Bundle\ContentGeneratorBundle\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Filesystem\Filesystem; trait CreateTrait { private function createFile( InputInterface $input, OutputInterface $output, $subDir, $content ) { $path[] = $this->getContainer()->getParameter('sculpin.source_dir'); $path[] = $subDir; $path[] = $filename = $input->getOption('filename'); $path = implode(DIRECTORY_SEPARATOR, $path); /** @var Filesystem $filesystem */ $filesystem = $this->getContainer()->get('filesystem'); if (!$filesystem->exists($path) || $input->getOption('force')) { $filesystem->dumpFile($path, $content); $output->writeln('<info>' . sprintf('%s has been created.', $filename) . '</info>'); } else { $output->writeln('<error>' . sprintf('%s already exists.', $filename) . '</error>'); } } }
Disable form submitting when personal request selected For keyboard using people (like me) this avoids a confusing situation where you hit enter for some reason on the form and it submits.
$(document).ready(function() { $switcherFieldGroup = $("#request_personal_switch"); $formSubmitButton = $("#request_form input[type='submit']")[0]; if ($switcherFieldGroup.length) { // If an error is showing they must have selected 'no' // so set this and don't hide the form. if ($(".errorExplanation").length) { $("#request_personal_switch_no").prop("checked", true); } else { $switcherFieldGroup.addClass("personal_request_switcher_focused"); $formSubmitButton.disabled = true; } $("#request_personal_switch_no").click(function(e) { $switcherFieldGroup.removeClass("personal_request_switcher_focused"); $formSubmitButton.disabled = false; }); $("#request_personal_switch_yes").click(function(e) { $switcherFieldGroup.addClass("personal_request_switcher_focused"); $formSubmitButton.disabled = true; }); } });
$(document).ready(function() { $switcherFieldGroup = $("#request_personal_switch"); if ($switcherFieldGroup.length) { // If an error is showing they must have selected 'no' // so set this and don't hide the form. if ($(".errorExplanation").length) { $("#request_personal_switch_no").prop("checked", true); } else { $switcherFieldGroup.addClass("personal_request_switcher_focused"); $("#request_personal_switch_no").click(function(e) { $switcherFieldGroup.removeClass("personal_request_switcher_focused"); }); $("#request_personal_switch_yes").click(function(e) { $switcherFieldGroup.addClass("personal_request_switcher_focused"); }); } } });
Fix the logic of the check for the phrase preload rebuild
<?php namespace wcf\system\language\preload; use wcf\data\language\Language; use wcf\system\language\preload\command\CachePreloadPhrases; use wcf\system\WCF; /** * Provides the URL to the preload cache for * phrases and creates it if it is missing. * * @author Alexander Ebert * @copyright 2001-2022 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\System\Language\Preload * @since 6.0 */ final class PhrasePreloader { /** * Returns the URL to the preload cache. Will implicitly * create the cache if it does not exist. */ public function getUrl(Language $language): string { if ($this->needsRebuild($language)) { $this->rebuild($language); } return \sprintf( '%s%s?v=%d', WCF::getPath(), $language->getPreloadCacheFilename(), \LAST_UPDATE_TIME ); } private function needsRebuild(Language $language): bool { return !\file_exists(\WCF_DIR . $language->getPreloadCacheFilename()); } private function rebuild(Language $language): void { $command = new CachePreloadPhrases($language); $command(); } }
<?php namespace wcf\system\language\preload; use wcf\data\language\Language; use wcf\system\language\preload\command\CachePreloadPhrases; use wcf\system\WCF; /** * Provides the URL to the preload cache for * phrases and creates it if it is missing. * * @author Alexander Ebert * @copyright 2001-2022 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\System\Language\Preload * @since 6.0 */ final class PhrasePreloader { /** * Returns the URL to the preload cache. Will implicitly * create the cache if it does not exist. */ public function getUrl(Language $language): string { if (!$this->needsRebuild($language)) { $this->rebuild($language); } return \sprintf( '%s%s?v=%d', WCF::getPath(), $language->getPreloadCacheFilename(), \LAST_UPDATE_TIME ); } private function needsRebuild(Language $language): bool { return \file_exists(\WCF_DIR . $language->getPreloadCacheFilename()); } private function rebuild(Language $language): void { $command = new CachePreloadPhrases($language); $command(); } }
Revert "Add tideways config to getcomposer.org" This reverts commit 134f749534d8ecabd8c42e1e2cf10df9a7057edf.
<?php use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\RedirectResponse; if (!isset($env) || $env !== 'dev') { // force ssl $app->before(function (Request $request) { // skip SSL & non-GET/HEAD requests if (strtolower($request->server->get('HTTPS')) == 'on' || strtolower($request->headers->get('X_FORWARDED_PROTO')) == 'https' || !$request->isMethodSafe()) { return; } return new RedirectResponse('https://'.substr($request->getUri(), 7)); }); $app->after(function (Request $request, Response $response) { if (!$response->headers->has('Strict-Transport-Security')) { $response->headers->set('Strict-Transport-Security', 'max-age=31104000'); } }); }
<?php use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\RedirectResponse; if (class_exists('Tideways\Profiler')) { \Tideways\Profiler::start(array('api_key' => trim(file_get_contents(__DIR__.'/tideways.key')))); } if (!isset($env) || $env !== 'dev') { // force ssl $app->before(function (Request $request) { // skip SSL & non-GET/HEAD requests if (strtolower($request->server->get('HTTPS')) == 'on' || strtolower($request->headers->get('X_FORWARDED_PROTO')) == 'https' || !$request->isMethodSafe()) { return; } return new RedirectResponse('https://'.substr($request->getUri(), 7)); }); $app->after(function (Request $request, Response $response) { if (!$response->headers->has('Strict-Transport-Security')) { $response->headers->set('Strict-Transport-Security', 'max-age=31104000'); } }); }
Make db upgrade step 20 more robust. git-svn-id: eda3d06fcef731589ace1b284159cead3416df9b@5815 af82e41b-90c4-0310-8c96-b1721e28e2e2
from trac.db import Table, Column, Index, DatabaseManager from trac.core import TracError from trac.versioncontrol.cache import CACHE_YOUNGEST_REV def do_upgrade(env, ver, cursor): """Modify the repository cache scheme (if needed) Now we use the 'youngest_rev' entry in the system table to explicitly store the youngest rev in the cache. """ db = env.get_db_cnx() try: repos = env.get_repository() youngest = repos.get_youngest_rev_in_cache(db) or '' except TracError: # no repository available youngest = '' # deleting first, for the 0.11dev and 0.10.4dev users cursor.execute("DELETE FROM system WHERE name=%s", (CACHE_YOUNGEST_REV,)) cursor.execute("INSERT INTO system (name, value) VALUES (%s, %s)", (CACHE_YOUNGEST_REV, youngest))
from trac.db import Table, Column, Index, DatabaseManager from trac.core import TracError from trac.versioncontrol.cache import CACHE_YOUNGEST_REV def do_upgrade(env, ver, cursor): """Modify the repository cache scheme (if needed) Now we use the 'youngest_rev' entry in the system table to explicitly store the youngest rev in the cache. """ db = env.get_db_cnx() try: repos = env.get_repository() youngest = repos.get_youngest_rev_in_cache(db) or '' # deleting first, for the 0.11dev and 0.10.4dev users cursor.execute("DELETE FROM system WHERE name=%s", (CACHE_YOUNGEST_REV,)) cursor.execute("INSERT INTO system (name, value) VALUES (%s, %s)", (CACHE_YOUNGEST_REV, youngest)) except TracError: # no repository available pass
Fix typo in man pages
#!/usr/bin/python # Format the output from various oiio command line "$tool --help" invocations, # and munge such that txt2man generates a simple man page with not-too-horrible # formatting. from __future__ import print_function from __future__ import absolute_import import sys lines = [l.rstrip().replace('\t', ' '*8) for l in sys.stdin.readlines()] print('TITLE') print(lines[0]) print() print('SYNOPSIS') for i,line in enumerate(lines[2:]): if line.lstrip().startswith('-') or line.lstrip().startswith('Options'): optStart = i+2 break print(line) print('''DESCRIPTION This program is part of the OpenImageIO (http://www.openimageio.org) tool suite. Detailed documentation is available in pdf format with the OpenImageIO distribution. ''') print('OPTIONS') for line in lines[optStart:]: if not line.startswith(' '): print() print(line) elif not line.lstrip().startswith('-'): print(line.lstrip()) else: print(line) print()
#!/usr/bin/python # Format the output from various oiio command line "$tool --help" invocations, # and munge such that txt2man generates a simple man page with not-too-horrible # formatting. from __future__ import print_function from __future__ import absolute_import import sys lines = [l.rstrip().replace('\t', ' '*8) for l in sys.stdin.readlines()] print('TITLE') print(lines[0]) print() print('SYNOPSIS') for i,line in enumerate(lines[2:]): if line.lstrip().startswith('-') or line.lstrip().startswith('Options'): optStart = i+2 break print(line) print('''DESCRIPTION This program is part of the OpenImageIO (http://www.openimageio.org) tool suite. Detailed documentation is avaliable in pdf format with the OpenImageIO distribution. ''') print('OPTIONS') for line in lines[optStart:]: if not line.startswith(' '): print() print(line) elif not line.lstrip().startswith('-'): print(line.lstrip()) else: print(line) print()
Update API error handling for empty responses
import apiClient from 'panoptes-client/lib/api-client'; import counterpart from 'counterpart'; counterpart.setFallbackLocale('en'); const translations = { strings: { project: {}, workflow: {} }, load: (translated_type, translated_id, language) => { counterpart.setLocale(language); return apiClient .type('translations') .get({ translated_type, translated_id, language }) .then(([translation]) => { if (translation && translation.strings) { translations.strings[translated_type] = translation.strings; } }) .catch(error => { console.warn(language.toUpperCase(), translated_type, translated_id, 'translation fetch error:', error.message); }); } }; export default translations;
import apiClient from 'panoptes-client/lib/api-client'; import counterpart from 'counterpart'; counterpart.setFallbackLocale('en'); const translations = { strings: { project: {}, workflow: {} }, load: (translated_type, translated_id, language) => { translations.strings[translated_type] = {}; return apiClient .type('translations') .get({ translated_type, translated_id, language }) .then(([translation]) => { translations.strings[translated_type] = translation.strings; counterpart.setLocale(language); }) .catch(error => { console.log(error.status); switch (error.status) { case 404: translations.strings[translated_type] = {}; break; } }); } }; export default translations;
Make DotDict repr() use class name so that it doesn't print misleading results if subclassed
class DotDict(dict): __getattr__ = dict.__getitem__ __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ def __init__(self, d={}): for key, value in d.items(): if hasattr(value, 'keys'): value = DotDict(value) if isinstance(value, list): value = [DotDict(el) if hasattr(el, 'keys') else el for el in value] self[key] = value def __repr__(self): return '<%s(%s)>' % (self.__class__.__name__, dict.__repr__(self))
class DotDict(dict): __getattr__ = dict.__getitem__ __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ def __init__(self, d={}): for key, value in d.items(): if hasattr(value, 'keys'): value = DotDict(value) if isinstance(value, list): value = [DotDict(el) if hasattr(el, 'keys') else el for el in value] self[key] = value def __repr__(self): return '<DotDict(%s)>' % dict.__repr__(self)
Use '==' because '===' causes undesired behavior
window.onload=function(){ var theNumber = _.random(1, 100); var theList = $("#list"); var theBanner = $("#triumph"); $("#submit").click(function() { var theGuess = $("#guess").val(); $("#guess").val(""); if (theGuess == theNumber) { $("#submit").prop('disabled', true); $("#guess").prop('disabled', true); theBanner.text("That's right! " + theGuess + " is the number of which I am thinking."); theBanner.append('<br /><button onClick="location.reload(true);" >Play again</button>'); } else if (theGuess < theNumber) { theList.append("<li>" + getRandomPhrase() + theGuess + " is too low.</li>"); } else { theList.append("<li>" + getRandomPhrase() + theGuess + " is too high</li>"); } }); $("#guess").keyup(function(event) { if (event.keyCode === 13) { $("#submit").click(); } }); function getRandomPhrase() { var phrases = [ "No. ", "Nope. ", "Guess again. ", "Give it another try. ", "That's not it. ", "Well, not quite. ", "Okay. You can try again. ", "No reason to give up now. ", "Nah. ", "Naw. ", "I hope you get it next time. " ] var index = _.random(0, phrases.length - 1); return phrases[index]; } }
window.onload=function(){ var theNumber = _.random(1, 100); var theList = $("#list"); var theBanner = $("#triumph"); $("#submit").click(function() { var theGuess = $("#guess").val(); $("#guess").val(""); if (theGuess === theNumber) { $("#submit").prop('disabled', true); $("#guess").prop('disabled', true); theBanner.text("That's right! " + theGuess + " is the number of which I am thinking."); theBanner.append('<br /><button onClick="location.reload(true);" >Play again</button>'); } else if (theGuess < theNumber) { theList.append("<li>" + getRandomPhrase() + theGuess + " is too low.</li>"); } else { theList.append("<li>" + getRandomPhrase() + theGuess + " is too high</li>"); } }); $("#guess").keyup(function(event) { if (event.keyCode === 13) { $("#submit").click(); } }); function getRandomPhrase() { var phrases = [ "No. ", "Nope. ", "Guess again. ", "Give it another try. ", "That's not it. ", "Well, not quite. ", "Okay. You can try again. ", "No reason to give up now. ", "Nah. ", "Naw. ", "I hope you get it next time. " ] var index = _.random(0, phrases.length - 1); return phrases[index]; } }
Update host to use Pi’s static address
#!/usr/bin/env python3 import socket import atexit import pygame from message import Message PRECISION = 3 host = "192.168.0.1" port = 9999 # create a socket object and connect to specified host/port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) def close_socket(): s.close() def send_message(controller, type, index, value): m = Message() m.controller_index = controller m.input_type = type m.input_index = index m.input_value = value s.send(bytes(m)) response = s.recv(1024) print(response.decode('ascii')) atexit.register(close_socket) pygame.init() pygame.joystick.init() stick = pygame.joystick.Joystick(0) stick.init() done = False controller = 0 type = 0 while done is False: for event in pygame.event.get(): value = None if event.type == pygame.QUIT: done = True elif event.type == pygame.JOYAXISMOTION: index = event.axis value = round(event.value, PRECISION) if value is not None: send_message(controller, type, index, value)
#!/usr/bin/env python3 import socket import atexit import pygame from message import Message PRECISION = 3 host = "localhost" port = 9999 # create a socket object and connect to specified host/port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) def close_socket(): s.close() def send_message(controller, type, index, value): m = Message() m.controller_index = controller m.input_type = type m.input_index = index m.input_value = value s.send(bytes(m)) response = s.recv(1024) print(response.decode('ascii')) atexit.register(close_socket) pygame.init() pygame.joystick.init() stick = pygame.joystick.Joystick(0) stick.init() done = False controller = 0 type = 0 while done is False: for event in pygame.event.get(): value = None if event.type == pygame.QUIT: done = True elif event.type == pygame.JOYAXISMOTION: index = event.axis value = round(event.value, PRECISION) if value is not None: send_message(controller, type, index, value)
Add the apiKeyService to the frontend.
/** * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var userServices = angular.module('userServices', ['ngResource']); userServices.service('userService', [ '$resource', function($resource) { return $resource('/api/users/:uid', {}, { 'save': {method: 'PUT'}, 'create': {method: 'POST'} }); }]); userServices.service('passwordResetService', [ '$resource', function($resource) { return $resource('/api/pwreset/:email'); }]); userServices.service('apiKeyService', [ '$resource', function($resource) { return $resource('/api/apikey/:keyid', {}, { 'create': {method: 'POST'}, 'deleteAll': {method: 'DELETE', params:{}} }); }]);
/** * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var userServices = angular.module('userServices', ['ngResource']); userServices.service('userService', [ '$resource', function($resource) { return $resource('/api/users/:uid', {}, { 'save': {method: 'PUT'}, 'create': {method: 'POST'} }); }]); userServices.service('passwordResetService', [ '$resource', function($resource) { return $resource('/api/pwreset/:email'); }]);
Add support for browsersync configuration in external rc file
'use strict'; var historyFallback = require('connect-history-api-fallback'); var log = require('connect-logger'); var yargs = require('yargs'); var sync = require('browser-sync').create(); var path = require('path'); // Load optional browser-sync config file var bsConfigPath = path.resolve('bs-config'); var options = {}; try { options = require(bsConfigPath); } catch (err) { } // silent error // Process CLI arguments yargs.option('files', { describe: 'array of file paths to watch', type: 'array' }); var argv = yargs.argv; setArgOverrides(options, argv); function setArgOverrides(o, argv) { o.port = argv.port || o.port || 3000; o.openPath = argv.open || o.openPath || '.'; o.files = argv.files || o.files || [ o.openPath + '/**/*.html', o.openPath + '/**/*.css', o.openPath + '/**/*.js' ]; o.server = o.server || {}; o.server.baseDir = argv.baseDir || o.server.baseDir || './'; o.server.middleware = o.server.middleware || [ log(), historyFallback({ index: '/' + o.openPath + '/' + (argv.indexFile || 'index.html') }) ] } if (argv.verbose) { console.log('options', options); } // Run browser-sync sync.init(options);
var historyFallback = require('connect-history-api-fallback'); var log = require('connect-logger'); var yargs = require('yargs'); var sync = require('browser-sync').create(); var defaultOpenPath = ''; yargs.option('files', { describe: 'array of file paths to watch', type: 'array' }); var argv = yargs.argv; var openPath = getOpenPath(); var indexFile = argv.indexFile || 'index.html' var options = { openPath: openPath, files: argv.files ? argv.files : [ openPath + '/**/*.html', openPath + '/**/*.css', openPath + '/**/*.js' ], baseDir: argv.baseDir || './', fallback: '/' + openPath + '/' + indexFile }; if (argv.verbose) { console.log('options', options); } function getOpenPath() { var src = argv.open || defaultOpenPath; if (!src) { return '.' } return src; } sync.init({ port: argv.port || 3000, server: { baseDir: options.baseDir, middleware: [ log(), historyFallback({ index: options.fallback }) ] }, files: options.files, });
Revert "Declare scipy as dep" This reverts commit 1e8bc12e0a6ea2ffefe580b63133b88f4db045a7.
""" CartoDB Spatial Analysis Python Library See: https://github.com/CartoDB/crankshaft """ from setuptools import setup, find_packages setup( name='crankshaft', version='0.0.0', description='CartoDB Spatial Analysis Python Library', url='https://github.com/CartoDB/crankshaft', author='Data Services Team - CartoDB', author_email='dataservices@cartodb.com', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Mapping comunity', 'Topic :: Maps :: Mapping Tools', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', ], keywords='maps mapping tools spatial analysis geostatistics', packages=find_packages(exclude=['contrib', 'docs', 'tests']), extras_require={ 'dev': ['unittest'], 'test': ['unittest', 'nose', 'mock'], }, # The choice of component versions is dictated by what's # provisioned in the production servers. install_requires=['pysal==1.9.1', 'scikit-learn==0.17.1'], requires=['pysal', 'numpy', 'sklearn' ], test_suite='test' )
""" CartoDB Spatial Analysis Python Library See: https://github.com/CartoDB/crankshaft """ from setuptools import setup, find_packages setup( name='crankshaft', version='0.0.0', description='CartoDB Spatial Analysis Python Library', url='https://github.com/CartoDB/crankshaft', author='Data Services Team - CartoDB', author_email='dataservices@cartodb.com', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Mapping comunity', 'Topic :: Maps :: Mapping Tools', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', ], keywords='maps mapping tools spatial analysis geostatistics', packages=find_packages(exclude=['contrib', 'docs', 'tests']), extras_require={ 'dev': ['unittest'], 'test': ['unittest', 'nose', 'mock'], }, # The choice of component versions is dictated by what's # provisioned in the production servers. install_requires=['scipy==0.17.1', 'pysal==1.9.1', 'scikit-learn==0.17.1'], requires=['scipy', 'pysal', 'numpy', 'sklearn'], test_suite='test' )
:hammer: Update the request builder interface.
<?php namespace Risan\OAuth1\Request; interface RequestBuilderInterface { /** * Get the ConfigInterface instance. * * @return \Risan\OAuth1\ConfigInterface */ public function getConfig(); /** * Get the SignerInterface instance. * * @return \Risan\OAuth1\Signature\SignerInterface */ public function getSigner(); /** * Get the NonceGeneratorInterface instance. * * @return \Risan\OAuth1\Request\NonceGeneratorInterface */ public function getNonceGenerator(); /** * Get current timestamp in seconds since Unix Epoch. * * @return int */ public function getCurrentTimestamp(); /** * Get base protocol parameters for the authorization header. * * @return array */ public function getBaseProtocolParameters(); /** * Add signature parameter to the given protocol parameters. * * @param array &$parameters * @param string $uri * @param string $httpMethod */ public function addSignatureParameter(array &$parameters, $uri, $httpMethod = 'POST'); /** * Normalize protocol parameters to be used as authorization header. * * @param array $parameters * @return string */ public function normalizeProtocolParameters(array $parameters); }
<?php namespace Risan\OAuth1\Request; interface RequestBuilderInterface { /** * Get the ConfigInterface instance. * * @return \Risan\OAuth1\ConfigInterface */ public function getConfig(); /** * Get the SignerInterface instance. * * @return \Risan\OAuth1\Signature\SignerInterface */ public function getSigner(); /** * Get the NonceGeneratorInterface instance. * * @return \Risan\OAuth1\Request\NonceGeneratorInterface */ public function getNonceGenerator(); /** * Get current timestamp in seconds since Unix Epoch. * * @return int */ public function getCurrentTimestamp(); /** * Get url for obtaining temporary credentials. * * @return string */ public function getTemporaryCredentialsUrl(); /** * Get authorization header for obtaining temporary credentials. * * @return string */ public function getTemporaryCredentialsAuthorizationHeader(); }
Add convenience methods for calling prot/priv methods.
<?php /* * This file is part of Sesshin library. * * (c) Przemek Sobstel <http://sobstel.org> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace Sesshin\Tests; class TestCase extends \PHPUnit_Framework_TestCase { public function setPropertyAccessible($object, $property_name) { $ref_prop = new \ReflectionProperty(get_class($object), $property_name); $ref_prop->setAccessible(true); return $ref_prop; } /** * @return \ReflectionProperty */ public function setPropertyValue($object, $property_name, $value) { $ref_prop = $this->setPropertyAccessible($object, $property_name); $ref_prop->setValue($object, $value); return $ref_prop; } public function setMethodAccessible($object, $method_name) { $ref_method = new \ReflectionMethod($object, $method_name); $ref_method->setAccessible(true); return $ref_method; } public function invokeMethod($object, $method_name, $args = array()) { $ref_method = $this->setMethodAccessible($object, $method_name); return $ref_method->invokeArgs($object, $args); } }
<?php /* * This file is part of Sesshin library. * * (c) Przemek Sobstel <http://sobstel.org> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace Sesshin\Tests; class TestCase extends \PHPUnit_Framework_TestCase { public function setPropertyAccessible($object, $property_name) { $ref_prop = new \ReflectionProperty(get_class($object), $property_name); $ref_prop->setAccessible(true); return $ref_prop; } /** * @return \ReflectionProperty */ public function setPropertyValue($object, $property_name, $value) { $ref_prop = $this->setPropertyAccessible($object, $property_name); $ref_prop->setValue($object, $value); return $ref_prop; } }
Change discarded badge class to danger
(function () { 'use strict'; angular.module('documents') .component('scientillaDocumentLabel', { templateUrl: 'partials/scientilla-document-label.html', controller: scientillaDocumentLabel, controllerAs: 'vm', bindings: { label: "<" } }); function scientillaDocumentLabel() { var vm = this; vm.badges = []; vm.badges.external = 'success'; vm.badges.new = 'success'; vm.badges.discarded = 'danger'; vm.badges.duplicate = 'warning'; vm.badges['already verified'] = 'warning'; vm.badges['already in drafts'] = 'warning'; vm.badges.unverifying = 'secondary'; activate(); function activate() { } } })();
(function () { 'use strict'; angular.module('documents') .component('scientillaDocumentLabel', { templateUrl: 'partials/scientilla-document-label.html', controller: scientillaDocumentLabel, controllerAs: 'vm', bindings: { label: "<" } }); function scientillaDocumentLabel() { var vm = this; vm.badges = []; vm.badges.external = 'success'; vm.badges.new = 'success'; vm.badges.discarded = 'error'; vm.badges.duplicate = 'warning'; vm.badges['already verified'] = 'warning'; vm.badges['already in drafts'] = 'warning'; vm.badges.unverifying = 'secondary'; activate(); function activate() { } } })();
Add lesson, and link to section.
Template.addLesson.events({ 'click .add-lesson-button': function (event, template) { // Get lesson name var lessonName = template.find("#lesson-name").value; // Get section ID from current data context var sectionID = String(this); // Create temporary lesson object var lessonObject = { 'name': lessonName }; // Add lesson to database, // getting lesson ID in return var lessonId = Lessons.insert(lessonObject); // Add lesson ID to section record Sections.update(sectionID, {$push: {'lessonIDs': lessonId}}); // Clear the lesson name field $("#lesson-name").val(''); } });
Template.addLesson.events({ 'click .add-lesson-button': function (event, template) { // Get lesson name var lessonName = template.find("#lesson-name").value; // Get course ID from parent template var courseID = Template.parentData()._id; // Create temporary lesson object var lessonObject = { 'name': lessonName, 'courseIDs': [courseID] // add course ID to lesson object, for collection helper }; // Add lesson to database, // getting lesson ID in return var lessonId = Lessons.insert(lessonObject); if (!this.lessonIDs) { this.lessonIDs = []; } // Add lesson ID to array this.lessonIDs.push(lessonId); // Get course sections array from parent template var courseSections = Template.parentData().sections; // Save course.lessonIDs array to database Courses.update(courseID, {$set: {"sections": courseSections}}); // Clear the lesson name field $("#lesson-name").val(''); } });
Fix warnings in build task
var classes = require("./classes"); var gRex = require("./grex"); var grex = function(options, callback){ try { if(typeof options === 'function'){ callback = options; options = undefined; } var db = new gRex(options); connect = db.connect().then().nodeify(callback); } catch(error) { console.error(error); return callback(error); } return connect; }; module.exports = { "connect": grex, "T": classes.T, "Contains": classes.Contains, "Vertex": classes.Vertex, "Edge": classes.Edge, "String": classes.String, "Direction": classes.Direction, "Geoshape": classes.Geoshape, "TitanKey": classes.TitanKey, "TitanLabel": classes.TitanLabel };
var classes = require("./classes"); var gRex = require("./grex"); var grex = function(options, callback){ try { if(typeof options === 'function'){ callback = options; options = undefined; } var db = new gRex(options); connect = db.connect().then().nodeify(callback); } catch(error) { return callback(error); console.error(error); } return connect; }; module.exports = { "connect": grex, "T": classes.T, "Contains": classes.Contains, "Vertex": classes.Vertex, "Edge": classes.Edge, "String": classes["String"], "Direction": classes.Direction, "Geoshape": classes.Geoshape, "TitanKey": classes.TitanKey, "TitanLabel": classes.TitanLabel };
Update fn call for unset to work.
/** * WidgetNull component. * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * External dependencies */ import PropTypes from 'prop-types'; /** * Internal dependencies */ import useWidgetStateEffect from '../hooks/useWidgetStateEffect'; import Null from '../../../components/Null'; // The supported props must match `Null` (except `widgetSlug`). export default function WidgetNull( { widgetSlug } ) { useWidgetStateEffect( widgetSlug, Null, null ); return <Null />; } WidgetNull.propTypes = { widgetSlug: PropTypes.string.isRequired, ...Null.propTypes, };
/** * WidgetNull component. * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * External dependencies */ import PropTypes from 'prop-types'; /** * Internal dependencies */ import useWidgetStateEffect from '../hooks/useWidgetStateEffect'; import Null from '../../../components/Null'; // The supported props must match `Null` (except `widgetSlug`). export default function WidgetNull( { widgetSlug } ) { useWidgetStateEffect( widgetSlug, Null ); return <Null />; } WidgetNull.propTypes = { widgetSlug: PropTypes.string.isRequired, ...Null.propTypes, };
Revert "PS-147 adapted image resource to new interface" This reverts commit 29a8ca7c1e496eb4fc473c3fb5d2123d5c211be5.
/* * Copyright (c) 2014-2015 University of Ulm * * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package cloud.resources; import de.uniulm.omi.cloudiator.sword.api.domain.Image; import models.Cloud; import models.CloudCredential; import models.service.ModelService; /** * Created by daniel on 28.05.15. */ public class ImageInLocation extends ResourceWithCredential implements Image { public ImageInLocation(Image image, String cloud, String credential, ModelService<Cloud> cloudModelService, ModelService<CloudCredential> cloudCredentialModelService) { super(image, cloud, credential, cloudModelService, cloudCredentialModelService); } }
/* * Copyright (c) 2014-2015 University of Ulm * * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package cloud.resources; import de.uniulm.omi.cloudiator.common.os.OperatingSystem; import de.uniulm.omi.cloudiator.sword.api.domain.Image; import models.Cloud; import models.CloudCredential; import models.service.ModelService; import java.util.Optional; /** * Created by daniel on 28.05.15. */ public class ImageInLocation extends ResourceWithCredential implements Image { private final Image image; public ImageInLocation(Image image, String cloud, String credential, ModelService<Cloud> cloudModelService, ModelService<CloudCredential> cloudCredentialModelService) { super(image, cloud, credential, cloudModelService, cloudCredentialModelService); this.image = image; } @Override public Optional<OperatingSystem> operatingSystem() { return image.operatingSystem(); } }
Fix tests on python 3.3
import os import sys from nose.tools import * try: from importlib import reload except ImportError: try: from imp import reload except ImportError: pass def setup_yamlmod(): import yamlmod reload(yamlmod) def teardown_yamlmod(): import yamlmod for hook in sys.meta_path: if isinstance(hook, yamlmod.YamlImportHook): sys.meta_path.remove(hook) break @with_setup(setup_yamlmod, teardown_yamlmod) def test_import_installs_hook(): import yamlmod hooks = [] for hook in sys.meta_path: if isinstance(hook, yamlmod.YamlImportHook): hooks.append(hook) eq_(len(hooks), 1, 'did not find exactly one hook') @with_setup(setup_yamlmod, teardown_yamlmod) def test_import_fixture(): import fixture eq_(fixture.debug, True) eq_(fixture.domain, 'example.com') eq_(fixture.users, ['alice', 'bob', 'cathy']) @with_setup(setup_yamlmod, teardown_yamlmod) def test_hidden_attributes(): import fixture eq_(fixture.__name__, 'fixture') eq_(fixture.__file__, os.path.join(os.path.dirname(__file__), 'fixture.yml'))
import os import sys from nose.tools import * try: from importlib import reload except ImportError: pass def setup_yamlmod(): import yamlmod reload(yamlmod) def teardown_yamlmod(): import yamlmod for hook in sys.meta_path: if isinstance(hook, yamlmod.YamlImportHook): sys.meta_path.remove(hook) break @with_setup(setup_yamlmod, teardown_yamlmod) def test_import_installs_hook(): import yamlmod hooks = [] for hook in sys.meta_path: if isinstance(hook, yamlmod.YamlImportHook): hooks.append(hook) eq_(len(hooks), 1, 'did not find exactly one hook') @with_setup(setup_yamlmod, teardown_yamlmod) def test_import_fixture(): import fixture eq_(fixture.debug, True) eq_(fixture.domain, 'example.com') eq_(fixture.users, ['alice', 'bob', 'cathy']) @with_setup(setup_yamlmod, teardown_yamlmod) def test_hidden_attributes(): import fixture eq_(fixture.__name__, 'fixture') eq_(fixture.__file__, os.path.join(os.path.dirname(__file__), 'fixture.yml'))
Add video bucket to artist model
import DS from 'ember-data'; const { attr, Model } = DS; export default Model.extend({ artistLocation: attr(), biographies: attr(), // echonest-biography blogs: attr(), // echonest-blog discovery: attr('number'), discoveryRank: attr('number'), doc_counts: attr(), familiarity: attr('number'), familiarityRank: attr('number'), genres: attr(), // echonest-genre hotttnesss: attr('number'), hotttnesssRank: attr('number'), images: attr(), name: attr('string'), news: attr(), // echonest-news reviews: attr(), // echonest-reviews songs: attr(), // echonest-songs teams: attr(), twitter: attr('string'), urls: attr(), // echonest-urls video: attr(), // echonest-video yearsActive: attr() });
import DS from 'ember-data'; const { attr, Model } = DS; export default Model.extend({ artistLocation: attr(), biographies: attr(), // echonest-biography blogs: attr(), // echonest-blog discovery: attr('number'), discoveryRank: attr('number'), doc_counts: attr(), familiarity: attr('number'), familiarityRank: attr('number'), genres: attr(), // echonest-genre hotttnesss: attr('number'), hotttnesssRank: attr('number'), images: attr(), name: attr('string'), news: attr(), // echonest-news reviews: attr(), // echonest-reviews songs: attr(), // echonest-songs teams: attr(), twitter: attr('string'), urls: attr(), video: attr(), yearsActive: attr() });
Use the public IP for lb_fqdn in NFS test The helm installation fails because the lb_fqdn is pointing to the machine's hostname, which ends up in the kubeconfig that is used by helm to initialize tiller. Given that this hostname is not resolvable from the testing machine, the test fails.
package integration import . "github.com/onsi/ginkgo" func testNFSShare(aws infrastructureProvisioner, distro linuxDistro) { nfsServers, err := aws.CreateNFSServers() FailIfError(err, "Couldn't set up NFS shares") WithMiniInfrastructure(distro, aws, func(node NodeDeets, sshKey string) { By("Setting up a plan file with NFS Shares and no storage") plan := PlanAWS{ Etcd: []NodeDeets{node}, Master: []NodeDeets{node}, Worker: []NodeDeets{node}, MasterNodeFQDN: node.PublicIP, MasterNodeShortName: node.PublicIP, SSHKeyFile: sshKey, SSHUser: node.SSHUser, NFSVolume: []NFSVolume{ {Host: nfsServers[0].IpAddress}, }, } err := installKismaticWithPlan(plan, sshKey) FailIfError(err, "Error installing cluster with NFS shares") }) }
package integration import . "github.com/onsi/ginkgo" func testNFSShare(aws infrastructureProvisioner, distro linuxDistro) { nfsServers, err := aws.CreateNFSServers() FailIfError(err, "Couldn't set up NFS shares") WithMiniInfrastructure(distro, aws, func(node NodeDeets, sshKey string) { By("Setting up a plan file with NFS Shares and no storage") plan := PlanAWS{ Etcd: []NodeDeets{node}, Master: []NodeDeets{node}, Worker: []NodeDeets{node}, MasterNodeFQDN: node.Hostname, MasterNodeShortName: node.Hostname, SSHKeyFile: sshKey, SSHUser: node.SSHUser, NFSVolume: []NFSVolume{ {Host: nfsServers[0].IpAddress}, }, } err := installKismaticWithPlan(plan, sshKey) FailIfError(err, "Error installing cluster with NFS shares") }) }
Switch out to use the new GenericKeyInline
from django.conf import settings from django.contrib import admin from django.contrib.contenttypes import generic from reversion.admin import VersionAdmin from armstrong.hatband.options import GenericKeyInline from . import models class NodeAdmin(VersionAdmin): pass class NodeInline(GenericKeyInline): model = models.Node extra = 1 # This is for Grappelli sortable_field_name = "order" related_lookup_fields = { 'generic': ['content_type', 'object_id', ] } class WellAdmin(VersionAdmin): list_display = ('type', 'pub_date', 'expires', 'active', ) inlines = [ NodeInline, ] class WellTypeAdmin(VersionAdmin): pass admin.site.register(models.Node, NodeAdmin) admin.site.register(models.Well, WellAdmin) admin.site.register(models.WellType, WellTypeAdmin)
from django.conf import settings from django.contrib import admin from django.contrib.contenttypes import generic from reversion.admin import VersionAdmin from . import models class NodeAdmin(VersionAdmin): pass class NodeInline(admin.TabularInline): model = models.Node extra = 1 # This is for Grappelli sortable_field_name = "order" related_lookup_fields = { 'generic': ['content_type', 'object_id', ] } class WellAdmin(VersionAdmin): list_display = ('type', 'pub_date', 'expires', 'active', ) inlines = [ NodeInline, ] class WellTypeAdmin(VersionAdmin): pass admin.site.register(models.Node, NodeAdmin) admin.site.register(models.Well, WellAdmin) admin.site.register(models.WellType, WellTypeAdmin)
GEODE-209: Change subTearDown to destroy process
package com.gemstone.gemfire.test.golden; import static org.junit.Assert.*; import org.junit.Test; import org.junit.experimental.categories.Category; import com.gemstone.gemfire.test.process.ProcessWrapper; import com.gemstone.gemfire.test.junit.categories.IntegrationTest; @Category(IntegrationTest.class) public class FailWithTimeoutOfWaitForOutputToMatchJUnitTest extends FailOutputTestCase { private static final long timeoutMillis = 1000; private ProcessWrapper process; public void subTearDown() throws Exception { this.process.destroy(); } @Override String problem() { return "This is an extra line"; } @Override void outputProblemInProcess(final String message) { System.out.println(message); } /** * Process output has an extra line and should fail */ @Test public void testFailWithTimeoutOfWaitForOutputToMatch() throws Exception { this.process = createProcessWrapper(new ProcessWrapper.Builder().timeoutMillis(timeoutMillis), getClass()); this.process.execute(createProperties()); this.process.waitForOutputToMatch("Begin " + name() + "\\.main"); try { this.process.waitForOutputToMatch(problem()); fail("assertOutputMatchesGoldenFile should have failed due to " + problem()); } catch (AssertionError expected) { assertTrue(expected.getMessage().contains(problem())); } } public static void main(String[] args) throws Exception { new FailWithTimeoutOfWaitForOutputToMatchJUnitTest().executeInProcess(); } }
package com.gemstone.gemfire.test.golden; import static org.junit.Assert.*; import org.junit.Test; import org.junit.experimental.categories.Category; import com.gemstone.gemfire.test.process.ProcessWrapper; import com.gemstone.gemfire.test.junit.categories.IntegrationTest; @Category(IntegrationTest.class) public class FailWithTimeoutOfWaitForOutputToMatchJUnitTest extends FailOutputTestCase { private static final long timeoutMillis = 1000; private ProcessWrapper process; public void subTearDown() throws Exception { this.process.waitFor(); assertFalse(this.process.isAlive()); } @Override String problem() { return "This is an extra line"; } @Override void outputProblemInProcess(final String message) { System.out.println(message); } /** * Process output has an extra line and should fail */ @Test public void testFailWithTimeoutOfWaitForOutputToMatch() throws Exception { this.process = createProcessWrapper(new ProcessWrapper.Builder().timeoutMillis(timeoutMillis), getClass()); this.process.execute(createProperties()); this.process.waitForOutputToMatch("Begin " + name() + "\\.main"); try { this.process.waitForOutputToMatch(problem()); fail("assertOutputMatchesGoldenFile should have failed due to " + problem()); } catch (AssertionError expected) { assertTrue(expected.getMessage().contains(problem())); } } public static void main(String[] args) throws Exception { new FailWithTimeoutOfWaitForOutputToMatchJUnitTest().executeInProcess(); } }
Use path.relative to create the bundles glob
var NwBuilder = require("node-webkit-builder"); var asap = require("pdenodeify"); var path = require("path"); var rimraf = require("rimraf"); module.exports = function(options, buildResult){ var nwOptions = {}; // Convert the options to camelcase Object.keys(options).forEach(function(optName){ nwOptions[toCamelcase(optName)] = options[optName]; }); // Set the bundlesPath as a file to use. var files = nwOptions.files || nwOptions.glob || []; files = Array.isArray(files) ? files : [files]; if(buildResult && buildResult.configuration && buildResult.configuration.bundlesPath) { var bundlesPath = buildResult.configuration.bundlesPath; var globPath = path.relative(process.cwd(), bundlesPath) + "/**/*"; files.unshift(globPath); } nwOptions.files = files; var nw = new NwBuilder(nwOptions); nw.on("log", function(msg){ console.error(msg); }); var buildPromise = asap(rimraf)(nwOptions.buildDir); var builder = asap(nw.build.bind(nw)); return buildPromise.then(builder); }; function toCamelcase(str) { return str.replace(/\_+([a-z])/g, function (x, chr) { return chr.toUpperCase(); }); }
var NwBuilder = require("node-webkit-builder"); var asap = require("pdenodeify"); var path = require("path"); var rimraf = require("rimraf"); module.exports = function(options, buildResult){ var nwOptions = {}; // Convert the options to camelcase Object.keys(options).forEach(function(optName){ nwOptions[toCamelcase(optName)] = options[optName]; }); // Set the bundlesPath as a file to use. var files = nwOptions.files || nwOptions.glob || []; files = Array.isArray(files) ? files : [files]; if(buildResult && buildResult.configuration && buildResult.configuration.bundlesPath) { var bundlesPath = buildResult.configuration.bundlesPath; files.unshift(path.join(bundlesPath, "**/*")); } nwOptions.files = files; var nw = new NwBuilder(nwOptions); nw.on("log", function(msg){ console.error(msg); }); var buildPromise = asap(rimraf)(nwOptions.buildDir); var builder = asap(nw.build.bind(nw)); return buildPromise.then(builder); }; function toCamelcase(str) { return str.replace(/\_+([a-z])/g, function (x, chr) { return chr.toUpperCase(); }); }
Update the version to 1.7.1
__version_info__ = { 'major': 1, 'minor': 7, 'micro': 1, 'releaselevel': 'final', 'serial': 1 } def get_version(short=False): assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final') vers = ["%(major)i.%(minor)i" % __version_info__, ] if __version_info__['micro'] and not short: vers.append(".%(micro)i" % __version_info__) if __version_info__['releaselevel'] != 'final' and not short: vers.append('%s%i' % (__version_info__['releaselevel'][0], __version_info__['serial'])) return ''.join(vers) __version__ = get_version() default_app_config = 'categories.apps.CategoriesConfig'
__version_info__ = { 'major': 1, 'minor': 7, 'micro': 0, 'releaselevel': 'final', 'serial': 1 } def get_version(short=False): assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final') vers = ["%(major)i.%(minor)i" % __version_info__, ] if __version_info__['micro'] and not short: vers.append(".%(micro)i" % __version_info__) if __version_info__['releaselevel'] != 'final' and not short: vers.append('%s%i' % (__version_info__['releaselevel'][0], __version_info__['serial'])) return ''.join(vers) __version__ = get_version() default_app_config = 'categories.apps.CategoriesConfig'
Fix not required let statment
const Report = require('./Report'); const Notification = require('./Notification'); async function Reporter( request, reply ) { // Params https://sites.google.com/a/webpagetest.org/docs/advanced-features/webpagetest-restful-apis const base = process.env.BASE || 'http://localhost:8080'; const result = await new Report({ k: process.env.WEB_PAGE_TEST_KEY || '', // k means KEY url: request.query.site, pingback: `${base}/verification/?hipchat=${request.query.hipchat}`, }).run(); // Set error as default. let notificationOpts = { status: 'Error', description: `There was an error proccesing ${request.query.site}`, room: request.query.hipchat, url: request.query.site, } // Update notificationOptions if was a success if ( 'statusCode' in result && result.statusCode === 200 ) { notificationOpts = Object.assign({}, notificationOpts, { status: 'Started', description: 'Your web page performance test has started.', url: result.data.userUrl, }); } const notificationResult = await Notification(notificationOpts); return reply(notificationResult); } module.exports = Reporter;
const Report = require('./Report'); const Notification = require('./Notification'); async function Reporter( request, reply ) { // Params https://sites.google.com/a/webpagetest.org/docs/advanced-features/webpagetest-restful-apis const base = process.env.BASE || 'http://localhost:8080'; const result = await new Report({ k: process.env.WEB_PAGE_TEST_KEY || '', // k means KEY url: request.query.site, pingback: `${base}/verification/?hipchat=${request.query.hipchat}`, }).run(); // Set error as default. let notificationOpts = { status: 'Error', description: `There was an error proccesing ${request.query.site}`, room: request.query.hipchat, url: request.query.site, } // Update notificationOptions if was a success if ( 'statusCode' in result && result.statusCode === 200 ) { let notificationOpts = Object.assign({}, notificationOpts, { status: 'Started', description: 'Your web page performance test has started.', url: result.data.userUrl, }); } const notificationResult = await Notification(notificationOpts); return reply(notificationResult); } module.exports = Reporter;
Make script injection more abstract
function createScript(property, source) { let scriptElement = document.createElement('script'); scriptElement['property'] = source; return scriptElement; } function injectScript(script) { (document.head || document.documentElement).appendChild(script); } chrome .runtime .sendMessage({ msg: 'getStatus' }, function (response) { if (response.status) { let storage = chrome.storage.local; storage.get(['type', 'freq', 'q', 'gain'], function (items) { type = items.type || 'highshelf'; freq = items.freq || '17999'; q = items.q || '0'; gain = items.gain || '-70'; let actualCode = ` var st_type = '${type}', st_freq = '${freq}', st_q = '${q}', st_gain = '${gain}'; console.log('Settings loaded...'); `; let script = createScript('textConetent', actualCode); injectScript(script); script.parentNode.removeChild(script); }); let script = createScript('src', chrome.extension.getURL('intercept.js')); script.onload = function () { this.parentNode.removeChild(this); }; injectScript(script); } });
chrome .runtime .sendMessage({ msg: 'getStatus' }, function (response) { if (response.status) { let storage = chrome.storage.local; storage.get(['type', 'freq', 'q', 'gain'], function (items) { type = items.type || 'highshelf'; freq = items.freq || '17999'; q = items.q || '0'; gain = items.gain || '-70'; let actualCode = ` var st_type = '${type}', st_freq = '${freq}', st_q = '${q}', st_gain = '${gain}'; console.log('Settings loaded...'); `; let script = document.createElement('script'); script.textContent = actualCode; (document.head || document.documentElement).appendChild(script); script.parentNode.removeChild(script); }); let s = document.createElement('script'); s.src = chrome.extension.getURL('intercept.js'); s.onload = function () { this.parentNode.removeChild(this); }; (document.head || document.documentElement).appendChild(s); } });
Fix indentation on comments block
<?php /** * The template for displaying all pages. * * This is the template that displays all pages by default. * Please note that this is the WordPress construct of pages * and that other 'pages' on your WordPress site will use a * different template. * * @package _s * @since _s 1.0 */ get_header(); ?> <div id="primary" class="content-area"> <div id="content" class="site-content" role="main"> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', 'page' ); ?> <?php // If comments are open or we have at least one comment, load up the comment template if ( comments_open() || '0' != get_comments_number() ) comments_template( '', true ); ?> <?php endwhile; // end of the loop. ?> </div><!-- #content .site-content --> </div><!-- #primary .content-area --> <?php get_sidebar(); ?> <?php get_footer(); ?>
<?php /** * The template for displaying all pages. * * This is the template that displays all pages by default. * Please note that this is the WordPress construct of pages * and that other 'pages' on your WordPress site will use a * different template. * * @package _s * @since _s 1.0 */ get_header(); ?> <div id="primary" class="content-area"> <div id="content" class="site-content" role="main"> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', 'page' ); ?> <?php // If comments are open or we have at least one comment, load up the comment template if ( comments_open() || '0' != get_comments_number() ) comments_template( '', true ); ?> <?php endwhile; // end of the loop. ?> </div><!-- #content .site-content --> </div><!-- #primary .content-area --> <?php get_sidebar(); ?> <?php get_footer(); ?>
Add default value to variant enabled column migration
<?php declare(strict_types=1); namespace Sylius\Migrations; use Doctrine\DBAL\Schema\Schema; use Doctrine\Migrations\AbstractMigration; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20200309172908 extends AbstractMigration { public function getDescription() : string { return ''; } public function up(Schema $schema) : void { // this up() migration is auto-generated, please modify it to your needs $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.'); $this->addSql('ALTER TABLE sylius_product_variant ADD enabled TINYINT(1) DEFAULT 1 NOT NULL'); } public function down(Schema $schema) : void { // this down() migration is auto-generated, please modify it to your needs $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.'); $this->addSql('ALTER TABLE sylius_product_variant DROP enabled'); } }
<?php declare(strict_types=1); namespace Sylius\Migrations; use Doctrine\DBAL\Schema\Schema; use Doctrine\Migrations\AbstractMigration; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20200309172908 extends AbstractMigration { public function getDescription() : string { return ''; } public function up(Schema $schema) : void { // this up() migration is auto-generated, please modify it to your needs $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.'); $this->addSql('ALTER TABLE sylius_product_variant ADD enabled TINYINT(1) NOT NULL'); } public function down(Schema $schema) : void { // this down() migration is auto-generated, please modify it to your needs $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.'); $this->addSql('ALTER TABLE sylius_product_variant DROP enabled'); } }
Add an array into Board.initial to store the initial state of the boar when the game is started
// Model var Board = { // initialize generates the pieces to display on the board to start the game initial: function initial(){ var board = []; // this will save the initial state of the board // Creates all the 32 squares where pieces can be placed for (i = 0; i <= 31; i++){ if (i <= 11){ // Creates all 12 green pieces $(".board").append($.parseHTML('<a href="'+(i+1)+'" id="square'+(i+1)+'" class="green"></a>')); board.push("green"); } else if (i >= 12 && i <= 19){ // creates all 12 empty squares $(".board").append($.parseHTML('<a href="'+(i+1)+'" id="square'+(i+1)+'" class="empty"></a>')); board.push("empty"); } else if (i >= 20){ // creates all 12 blue pieces $(".board").append($.parseHTML('<a href="'+(i+1)+'" id="square'+(i+1)+'" class="blue"></a>')); board.push("blue"); } } return board; }, // end of initial } // end of Board
// Model var Board = { // initialize generates the pieces to display on the board to start the game initial: function initial(){ // Creates all the 32 squares where pieces can be placed for (i = 0; i <= 31; i++){ if (i <= 11){ // Creates all 12 green pieces $(".board").append($.parseHTML('<a href="'+(i+1)+'" id="square'+(i+1)+'" class="green"></a>')); } else if (i >= 12 && i <= 19){ // creates all 12 empty squares $(".board").append($.parseHTML('<a href="'+(i+1)+'" id="square'+(i+1)+'" class="empty"></a>')); } else if (i >= 20){ // creates all 12 blue pieces $(".board").append($.parseHTML('<a href="'+(i+1)+'" id="square'+(i+1)+'" class="blue"></a>')); } } }, }
Remove extra unneeded empty line.
from __future__ import unicode_literals, division, absolute_import import logging import urllib from flexget import plugin from flexget.event import event log = logging.getLogger('cinemageddon') class UrlRewriteCinemageddon(object): """Cinemageddon urlrewriter.""" def url_rewritable(self, task, entry): return entry['url'].startswith('http://cinemageddon.net/details.php?id=') def url_rewrite(self, task, entry): entry['url'] = entry['url'].replace('details.php?id=', 'download.php?id=') entry['url'] += '&name=%s.torrent' % (urllib.quote(entry['title'], safe='')) @event('plugin.register') def register_plugin(): plugin.register(UrlRewriteCinemageddon, 'cinemageddon', groups=['urlrewriter'], api_ver=2)
from __future__ import unicode_literals, division, absolute_import import logging import urllib from flexget import plugin from flexget.event import event log = logging.getLogger('cinemageddon') class UrlRewriteCinemageddon(object): """Cinemageddon urlrewriter.""" def url_rewritable(self, task, entry): return entry['url'].startswith('http://cinemageddon.net/details.php?id=') def url_rewrite(self, task, entry): entry['url'] = entry['url'].replace('details.php?id=', 'download.php?id=') entry['url'] += '&name=%s.torrent' % (urllib.quote(entry['title'], safe='')) @event('plugin.register') def register_plugin(): plugin.register(UrlRewriteCinemageddon, 'cinemageddon', groups=['urlrewriter'], api_ver=2)
Add search for a user to later modify a profile
var express = require('express'); var router = express.Router(); var User = require('../models/user'); module.exports = function(app, mountPoint) { router.get('/', function(req, res) { User.find(function(err, data) { if (err) throw err; res.json(data); }); }); router.get('/:id', function(req, res) { User.findOne({_id: req.body._id}, function(err, data) { if (err) throw err; res.json(data); }); }); router.post('/', function(req, res) { User.create(req.body, function(err, data) { if (err) throw err; res.json(data); }); }); router.put('/', function(req, res) { User.update({_id: req.body._id}, req.body, function(err, data) { if (err) throw err; res.json(data); console.log(req.body); }); }); router.delete('/', function(req, res) { User.remove({_id: req.body._id}, function(err, data) { if (err) throw err; console.log('The user has been removed'); }); }); app.use(mountPoint, router) }
var express = require('express'); var router = express.Router(); var User = require('../models/user'); module.exports = function(app, mountPoint) { router.get('/', function(req, res) { User.find(function(err, data) { if (err) throw err; res.json(data); }); }); router.post('/', function(req, res) { User.create(req.body, function(err, data) { if (err) throw err; res.json(data); }); }); router.put('/', function(req, res) { User.update({_id: req.body._id}, req.body, function(err, data) { if (err) throw err; res.json(data); console.log(req.body); }); }); router.delete('/', function(req, res) { User.remove({_id: req.body._id}, function(err, data) { if (err) throw err; console.log('The user has been removed'); }); }); app.use(mountPoint, router) }
[FIND-46] Add click types to Javascript [rev: matthew.gordon]
/* * Copyright 2014-2016 Hewlett-Packard Development Company, L.P. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. */ define([ 'jquery' ], function($) { return { types: { ABANDONMENT: 'abandonment', CLICK_THROUGH: 'clickthrough', PAGE: 'page' }, clickTypes: { FULL_PREVIEW: 'full_preview', ORIGINAL: 'original', PREVIEW: 'preview' }, log: function (event) { $.ajax('../api/public/stats', { contentType: 'application/json', data: JSON.stringify(event), method: 'POST' }); } }; });
/* * Copyright 2014-2016 Hewlett-Packard Development Company, L.P. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. */ define([ 'jquery' ], function($) { return { types: { ABANDONMENT: 'abandonment', CLICK_THROUGH: 'clickthrough', PAGE: 'page' }, log: function (event) { $.ajax('../api/public/stats', { contentType: 'application/json', data: JSON.stringify(event), method: 'POST' }); } }; });
Add CamelCase to the code
<?php // ****************************** // Access to current order object // ****************************** // Get entity manager $entityManager = \Drupal::entityManager(); // Get order type $orderStorage = $entityManager->getStorage('commerce_order_type'); $orderType = $orderStorage->load('consumer_products')->id(); // Get store $store = $entityManager->getStorage('commerce_store')->loadDefault(); // Currrent user $uid = \Drupal::currentUser(); // Get Cart provider $cartProvider = Drupal::service('commerce_cart.cart_provider'); // Get Cart $order = $cartProvider->getCart($orderType, $store, $uid); // ****************************** // Get path object // ****************************** $path = '/node/3' $pathObbject = \Drupal::service('path.validator')->getUrlIfValid($path); // ****************************** // Checkout Btn by order // ****************************** $routeName = 'commerce_checkout.form'; $routeNameParameterKey = 'commerce_order'; $routeNameParameterValue = 'orderId'; //Ex: // <a href="{{ path('commerce_checkout.form', {'commerce_order': order_id}) }}" class='link'>{{ 'Buy'|t }}</a>
<?php // ****************************** // Access to current order object // ****************************** // Get entity manager $entity_manager = \Drupal::entityManager(); // Get order type $order_storage = $entity_manager->getStorage('commerce_order_type'); $order_type = $order_storage->load('consumer_products')->id(); // Get store $store = $entity_manager->getStorage('commerce_store')->loadDefault(); // Currrent user $uid = \Drupal::currentUser(); // Get Cart provider $cartProvider = Drupal::service('commerce_cart.cart_provider'); // Get Cart $order = $cartProvider->getCart($order_type, $store, $uid); // ****************************** // Get path object // ****************************** $path = '/node/3' $path_object = \Drupal::service('path.validator')->getUrlIfValid($path); // ****************************** // Checkout Btn by order // ****************************** $routeName = 'commerce_checkout.form'; $routeNameParameterKey = 'commerce_order'; $routeNameParameterValue = 'orderId'; //Ex: // <a href="{{ path('commerce_checkout.form', {'commerce_order': order_id}) }}" class='link'>{{ 'Buy'|t }}</a>
Update the client manipulator interface's user return to match up with the security token types
<?php declare(strict_types=1); namespace Gos\Bundle\WebSocketBundle\Client; use Ratchet\ConnectionInterface; use Ratchet\Wamp\Topic; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\User\UserInterface; interface ClientManipulatorInterface { /** * @return ClientConnection[] */ public function findAllByUsername(Topic $topic, string $username): array; /** * @return ClientConnection[] */ public function findByRoles(Topic $topic, array $roles): array; /** * @return ClientConnection[] */ public function getAll(Topic $topic, bool $anonymous = false): array; public function getClient(ConnectionInterface $connection): TokenInterface; /** * @return string|\Stringable|UserInterface */ public function getUser(ConnectionInterface $connection); }
<?php declare(strict_types=1); namespace Gos\Bundle\WebSocketBundle\Client; use Ratchet\ConnectionInterface; use Ratchet\Wamp\Topic; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; interface ClientManipulatorInterface { /** * @return ClientConnection[] */ public function findAllByUsername(Topic $topic, string $username): array; /** * @return ClientConnection[] */ public function findByRoles(Topic $topic, array $roles): array; /** * @return ClientConnection[] */ public function getAll(Topic $topic, bool $anonymous = false): array; public function getClient(ConnectionInterface $connection): TokenInterface; /** * @return string|object */ public function getUser(ConnectionInterface $connection); }
Fix messages in NDEx client
import requests import json import time ndex_base_url = 'http://services.bigmech.ndexbio.org' def send_request(url_suffix, params): res = requests.post(ndex_base_url + url_suffix, data=json.dumps(params)) res_json = get_result(res) return res_json def get_result(res): status = res.status_code if status == 200: return res.text task_id = res.json()['task_id'] print 'NDEx task submitted...' time_used = 0 try: while status != 200: res = requests.get(ndex_base_url + '/task/' + task_id) status = res.status_code if status != 200: time.sleep(5) time_used += 5 except KeyError: next return None print 'NDEx task complete.' return res.text
import requests import json import time ndex_base_url = 'http://services.bigmech.ndexbio.org' def send_request(url_suffix, params): res = requests.post(ndex_base_url + url_suffix, data=json.dumps(params)) res_json = get_result(res) return res_json def get_result(res): status = res.status_code if status == 200: return res.text task_id = res.json()['task_id'] print 'NDEx services task submitted...' % task_id time_used = 0 try: while status != 200: res = requests.get(ndex_base_url + '/task/' + task_id) status = res.status_code if status != 200: time.sleep(5) time_used += 5 except KeyError: next return None print 'NDEx services task complete.' % task_id return res.text
common: Change GetConfiguration query not to refresh session Bug-Url: https://bugzilla.redhat.com/1168842 Change-Id: I9ec8cb46e3fba206d9e1a93df9f985d5c2477fa8 Signed-off-by: Yair Zaslavsky <e2db7378c71f96998c1e6c0ce01fa87adf291bd0@redhat.com>
package org.ovirt.engine.core.common.queries; public class GetConfigurationValueParameters extends VdcQueryParametersBase { private static final long serialVersionUID = -5889171970595969719L; public GetConfigurationValueParameters(ConfigurationValues cVal) { this(cVal, null); } private ConfigurationValues _configValue; public ConfigurationValues getConfigValue() { return _configValue; } private String privateVersion; public String getVersion() { return privateVersion; } public void setVersion(String value) { privateVersion = value; } public GetConfigurationValueParameters(ConfigurationValues cVal, String version) { _configValue = cVal; privateVersion = version; setRefresh(false); } public GetConfigurationValueParameters() { this(ConfigurationValues.MaxNumOfVmCpus); } @Override public String toString() { StringBuilder builder = new StringBuilder(50); builder.append("version: "); //$NON-NLS-1$ builder.append(getVersion()); builder.append(", configuration value: "); builder.append(getConfigValue()); builder.append(", "); builder.append(super.toString()); return builder.toString(); } }
package org.ovirt.engine.core.common.queries; public class GetConfigurationValueParameters extends VdcQueryParametersBase { private static final long serialVersionUID = -5889171970595969719L; public GetConfigurationValueParameters(ConfigurationValues cVal) { _configValue = cVal; } private ConfigurationValues _configValue; public ConfigurationValues getConfigValue() { return _configValue; } private String privateVersion; public String getVersion() { return privateVersion; } public void setVersion(String value) { privateVersion = value; } public GetConfigurationValueParameters(ConfigurationValues cVal, String version) { _configValue = cVal; privateVersion = version; } public GetConfigurationValueParameters() { _configValue = ConfigurationValues.MaxNumOfVmCpus; } @Override public String toString() { StringBuilder builder = new StringBuilder(50); builder.append("version: "); //$NON-NLS-1$ builder.append(getVersion()); builder.append(", configuration value: "); builder.append(getConfigValue()); builder.append(", "); builder.append(super.toString()); return builder.toString(); } }
Clean up fixtures on exit too.
Object.freeze(Object.prototype); require.paths.unshift('../lib'); global.assert = require('assert'); global.fs = require('fs'); global.Step = require('step'); global.nStore = require('nstore'); // A mini expectations module to ensure expected callback fire at all. var expectations = {}; global.expect = function expect(message) { expectations[message] = new Error("Missing expectation: " + message); } global.fulfill = function fulfill(message) { delete expectations[message]; } process.addListener('exit', function () { Object.keys(expectations).forEach(function (message) { throw expectations[message]; }); }); function clean() { fs.writeFileSync("fixtures/toDelete.db", fs.readFileSync("fixtures/sample.db", "binary"), "binary"); try { fs.unlinkSync('fixtures/new.db'); } catch (err) { if (err.errno !== process.ENOENT) { throw err; } } } // Clean the test environment at startup clean(); // Clean on exit too process.addListener('exit', clean);
Object.freeze(Object.prototype); require.paths.unshift('../lib'); global.assert = require('assert'); global.fs = require('fs'); global.Step = require('step'); global.nStore = require('nstore'); // A mini expectations module to ensure expected callback fire at all. var expectations = {}; global.expect = function expect(message) { expectations[message] = new Error("Missing expectation: " + message); } global.fulfill = function fulfill(message) { delete expectations[message]; } process.addListener('exit', function () { Object.keys(expectations).forEach(function (message) { throw expectations[message]; }); }); function clean() { fs.writeFileSync("fixtures/toDelete.db", fs.readFileSync("fixtures/sample.db", "binary"), "binary"); try { fs.unlinkSync('fixtures/new.db'); } catch (err) { if (err.errno !== process.ENOENT) { throw err; } } } // Clean the test environment at startup clean(); // Clean on exit too // process.addListener('exit', clean);
Rename from select to map
from six import add_metaclass from rx import Observable from rx.internal import ExtensionMethod class AverageValue(object): def __init__(self, sum, count): self.sum = sum self.count = count @add_metaclass(ExtensionMethod) class ObservableAverage(Observable): """Uses a meta class to extend Observable with the methods in this class""" def average(self, key_selector=None): """Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present. Example res = source.average(); res = source.average(lambda x: x.value) key_selector -- A transform function to apply to each element. Returns an observable sequence containing a single element with the average of the sequence of values.""" if key_selector: return self.select(key_selector).average() def accumulator(prev, cur): return AverageValue(sum=prev.sum+cur, count=prev.count+1) def mapper(s): if s.count == 0: raise Exception('The input sequence was empty') return s.sum / float(s.count) seed = AverageValue(sum=0, count=0) return self.scan(accumulator, seed).last().map(mapper)
from six import add_metaclass from rx import Observable from rx.internal import ExtensionMethod class AverageValue(object): def __init__(self, sum, count): self.sum = sum self.count = count @add_metaclass(ExtensionMethod) class ObservableAverage(Observable): """Uses a meta class to extend Observable with the methods in this class""" def average(self, key_selector=None): """Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present. Example res = source.average(); res = source.average(lambda x: x.value) key_selector -- A transform function to apply to each element. Returns an observable sequence containing a single element with the average of the sequence of values.""" if key_selector: return self.select(key_selector).average() def accumulator(prev, cur): return AverageValue(sum=prev.sum+cur, count=prev.count+1) def selector(s): if s.count == 0: raise Exception('The input sequence was empty') return s.sum / float(s.count) seed = AverageValue(sum=0, count=0) return self.scan(accumulator, seed).last().select(selector)
Remove -e in favor of --from
#!/usr/bin/env node import yargs from 'yargs'; import path from 'path'; import fs from 'fs'; import * as pose from '.'; import actions from './actions'; const opts = yargs .usage('$ pose <action> [options]') .help('help') .epilog(actions.trim()) .options({ name: { alias: ['as'], default: path.basename(process.cwd()), desc: 'Name of template', }, entry: { alias: ['from'], default: process.cwd(), defaultDescription: 'cwd', desc: 'Entry of template', }, help: { alias: ['h'], }, }).argv; const action = opts._[0]; if (!action) { console.log('Type "pose help" to get started.'); process.exit(); } [ opts._pose = path.join(process.env.HOME, '.pose'), opts._templates = path.join(opts._pose, 'templates'), ].forEach(dir => { fs.mkdir(dir, () => null); }); if (typeof pose[action] === 'function') { pose[action](opts); } else { console.error(`Unknown action "${action}"`); } export { action, opts };
#!/usr/bin/env node import yargs from 'yargs'; import path from 'path'; import fs from 'fs'; import * as pose from '.'; import actions from './actions'; const opts = yargs .usage('$ pose <action> [options]') .help('help') .epilog(actions.trim()) .options({ name: { alias: ['as'], default: path.basename(process.cwd()), desc: 'Name of template', }, entry: { alias: ['e'], default: process.cwd(), defaultDescription: 'cwd', desc: 'Entry of template', }, help: { alias: ['h'], }, }).argv; const action = opts._[0]; if (!action) { console.log('Type "pose help" to get started.'); process.exit(); } [ opts._pose = path.join(process.env.HOME, '.pose'), opts._templates = path.join(opts._pose, 'templates'), ].forEach(dir => { fs.mkdir(dir, () => null); }); if (typeof pose[action] === 'function') { pose[action](opts); } else { console.error(`Unknown action "${action}"`); } export { action, opts };
Use the default modal command. Set title and href.
<?php /** * @version $Id$ * @category Nooku * @package Nooku_Server * @subpackage Weblinks * @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net) * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link http://www.nooku.org */ /** * Weblinks Toolbar Class * * @author Jeremy Wilken <http://nooku.assembla.com/profile/gnomeontherun> * @category Nooku * @package Nooku_Server * @subpackage Weblinks */ class ComWeblinksControllerToolbarWeblinks extends ComDefaultControllerToolbarDefault { public function getCommands() { $this->addSeperator() ->addEnable() ->addDisable() ->addSeperator() ->addModal(array( 'label' => 'Preferences', 'href' => 'index.php?option=com_config&controller=component&component=com_weblinks') ); return parent::getCommands(); } }
<?php /** * @version $Id$ * @category Nooku * @package Nooku_Server * @subpackage Weblinks * @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net) * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link http://www.nooku.org */ /** * Weblinks Toolbar Class * * @author Jeremy Wilken <http://nooku.assembla.com/profile/gnomeontherun> * @category Nooku * @package Nooku_Server * @subpackage Weblinks */ class ComWeblinksControllerToolbarWeblinks extends ComDefaultControllerToolbarDefault { public function getCommands() { $this->addSeperator() ->addEnable() ->addDisable() ->addSeperator() ->addPreferences(); return parent::getCommands(); } }
Change access requirements for view holders View holders don't need to have public accessibility.
package com.kasparpeterson.simplerecyclerview; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.lang.reflect.Constructor; /** * Created by kaspar on 18/02/2017. */ class SimpleViewType { private final int viewType; private final int layoutId; private final Class viewHolderClass; /** * Attention! Please make sure to always provide different view types when having multiple view * types in same recycler view adapter. Also make sure that view types start from 0. */ SimpleViewType(int viewType, int layoutId, Class viewHolderClass) { this.viewType = viewType; this.layoutId = layoutId; this.viewHolderClass = viewHolderClass; } int getViewTypeAsInt() { return viewType; } SimpleRecyclerViewAdapter.SimpleViewHolder getViewHolder(LayoutInflater layoutInflater, ViewGroup parent) throws Exception { View view = getView(layoutInflater, parent); Class<?> klass = Class.forName(viewHolderClass.getName()); Constructor<?> constructor = klass.getDeclaredConstructor(View.class); constructor.setAccessible(true); return (SimpleRecyclerViewAdapter.SimpleViewHolder) constructor.newInstance(view); } private View getView(LayoutInflater layoutInflater, ViewGroup parent) { return layoutInflater.inflate(layoutId, parent, false); } }
package com.kasparpeterson.simplerecyclerview; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.lang.reflect.Constructor; /** * Created by kaspar on 18/02/2017. */ class SimpleViewType { private final int viewType; private final int layoutId; private final Class viewHolderClass; /** * Attention! Please make sure to always provide different view types when having multiple view * types in same recycler view adapter. Also make sure that view types start from 0. */ SimpleViewType(int viewType, int layoutId, Class viewHolderClass) { this.viewType = viewType; this.layoutId = layoutId; this.viewHolderClass = viewHolderClass; } int getViewTypeAsInt() { return viewType; } SimpleRecyclerViewAdapter.SimpleViewHolder getViewHolder(LayoutInflater layoutInflater, ViewGroup parent) throws Exception { View view = getView(layoutInflater, parent); Class<?> klass = Class.forName(viewHolderClass.getName()); Constructor<?> constructor = klass.getConstructor(View.class); return (SimpleRecyclerViewAdapter.SimpleViewHolder) constructor.newInstance(view); } private View getView(LayoutInflater layoutInflater, ViewGroup parent) { return layoutInflater.inflate(layoutId, parent, false); } }
Convert crossorigin attribute tests to use dynamic imports
it("should load script without crossorigin attribute", function(done) { import("./empty?a" /* webpackChunkName: "chunk-with-crossorigin-attr" */); // if in browser context, test that crossorigin attribute was not added. if (typeof document !== 'undefined') { var script = document.querySelector('script[src="js/chunk-with-crossorigin-attr.web.js"]'); script.getAttribute('crossorigin').should.be.exactly(null); } done(); }); it("should load script with crossorigin attribute 'anonymous'", function(done) { var originalValue = __webpack_public_path__; __webpack_public_path__ = 'https://example.com/'; import("./empty?b" /* webpackChunkName: "chunk-without-crossorigin-attr" */); __webpack_public_path__ = originalValue; // if in browser context, test that crossorigin attribute was added. if (typeof document !== 'undefined') { var script = document.querySelector('script[src="https://example.com/js/chunk-without-crossorigin-attr.web.js"]'); script.getAttribute('crossorigin').should.be.exactly('anonymous'); } __webpack_public_path__ = originalValue; done(); });
it("should load script without crossorigin attribute", function(done) { require.ensure([], function(require) { require("./empty?a"); }, "chunk-with-crossorigin-attr"); // if in browser context, test that crossorigin attribute was not added. if (typeof document !== 'undefined') { var script = document.querySelector('script[src="js/chunk-with-crossorigin-attr.web.js"]'); script.getAttribute('crossorigin').should.be.exactly(null); } done(); }); it("should load script with crossorigin attribute 'anonymous'", function(done) { var originalValue = __webpack_public_path__; __webpack_public_path__ = 'https://example.com/'; require.ensure([], function(require) { require("./empty?b"); }, "chunk-with-crossorigin-attr"); __webpack_public_path__ = originalValue; // if in browser context, test that crossorigin attribute was added. if (typeof document !== 'undefined') { var script = document.querySelector('script[src="https://example.com/js/chunk-with-crossorigin-attr.web.js"]'); script.getAttribute('crossorigin').should.be.exactly('anonymous'); } __webpack_public_path__ = originalValue; done(); });
Remove more unnecessary files in dist/node_modules/
const shell = require('shelljs'); const path = require('path'); const { rebuild } = require('electron-rebuild'); function rebuildModules(buildPath) { if (process.platform === 'darwin') { return rebuild({ buildPath, // eslint-disable-next-line electronVersion: require('electron/package.json').version, extraModules: [], force: true, types: ['prod', 'optional'], }); } } async function run() { shell.cd('npm-package'); shell.exec('yarn'); shell.cd('-'); await rebuildModules(path.resolve(__dirname, '..')); shell.cd('dist'); shell.exec('yarn'); await rebuildModules(path.resolve(__dirname, '../dist')); shell.rm( '-rf', 'node_modules/*/{example,examples,test,tests,*.md,*.markdown,CHANGELOG*,.*,Makefile}' ); // Remove unnecessary files in apollo-client-devtools shell.rm( '-rf', 'node_modules/apollo-client-devtools/{assets,build,development,shells/dev,src}' ); // eslint-disable-next-line require('./patch-modules'); } run();
const shell = require('shelljs'); const path = require('path'); const { rebuild } = require('electron-rebuild'); function rebuildModules(buildPath) { if (process.platform === 'darwin') { return rebuild({ buildPath, // eslint-disable-next-line electronVersion: require('electron/package.json').version, extraModules: [], force: true, types: ['prod', 'optional'], }); } } async function run() { shell.cd('npm-package'); shell.exec('yarn'); shell.cd('-'); await rebuildModules(path.resolve(__dirname, '..')); shell.cd('dist'); shell.exec('yarn'); await rebuildModules(path.resolve(__dirname, '../dist')); shell.rm( '-rf', 'node_modules/*/{example,examples,test,tests,*.md,*.markdown,CHANGELOG*,.*,Makefile}' ); // eslint-disable-next-line require('./patch-modules'); } run();
Fix issue with 'EventEmitter' max listener limit being reached.
'use strict'; var assign = require('object-assign'); var EventEmitter = require('events').EventEmitter; var Dispatcher = require('../dispatcher'); var CHANGE_EVENT = 'change'; /** * Creates a Flux Store. * * @param {object} exports Defines the 'public' interface of the store. * @param {function} callback Callback registered to listen to the Dispatcher. * * @returns {object} Store object, which is also an EventEmitter. */ function createStore(exports, callback) { // Make sure EventEmitter has unlimited listeners! var emitter = new EventEmitter(); emitter.setMaxListeners(0); var store = assign(emitter, { emitChange: function() { this.emit(CHANGE_EVENT); }, addChangeListener: function(callback) { this.addListener(CHANGE_EVENT, callback); }, removeChangeListener: function(callback) { this.removeListener(CHANGE_EVENT, callback); }, }); store = assign(store, exports); store.dispatchToken = Dispatcher.register(callback.bind(store)); return store; } module.exports = createStore;
'use strict'; var assign = require('object-assign'); var EventEmitter = require('events').EventEmitter; var Dispatcher = require('../dispatcher'); var CHANGE_EVENT = 'change'; /** * Creates a Flux Store. * * @param {object} exports Defines the 'public' interface of the store. * @param {function} callback Callback registered to listen to the Dispatcher. * * @returns {object} Store object, which is also an EventEmitter. */ function createStore(exports, callback) { var store = assign(new EventEmitter(), { emitChange: function() { this.emit(CHANGE_EVENT); }, addChangeListener: function(callback) { this.addListener(CHANGE_EVENT, callback); }, removeChangeListener: function(callback) { this.removeListener(CHANGE_EVENT, callback); }, }); store = assign(store, exports); store.dispatchToken = Dispatcher.register(callback.bind(store)); return store; } module.exports = createStore;
Fix session in CLI on Debian systems Change-Id: I4b1a3e45417a8d8442e097d440ebee8a09a8aaa2
# Copyright 2015 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Starts single seession, and ends it with `atexit` can be used from cli / examples shouldn't be used from long running processes (workers etc) """ def create_all(): import sys if sys.executable.split('/')[-1] not in ['python', 'python2']: # auto add session to only standalone python runs return from solar.dblayer.model import ModelMeta import atexit ModelMeta.session_start() atexit.register(ModelMeta.session_end)
# Copyright 2015 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Starts single seession, and ends it with `atexit` can be used from cli / examples shouldn't be used from long running processes (workers etc) """ def create_all(): import sys if not sys.executable.endswith(('python', )): # auto add session to only standalone python runs return from solar.dblayer.model import ModelMeta import atexit ModelMeta.session_start() atexit.register(ModelMeta.session_end)
Use the user service to persist or modify state
'use strict'; import { removeUserService, saveUserService } from '../../../utils/userService'; import { userModel } from '../../../models/index'; const buildResponse = (statusCode, data, res) => { if (statusCode === 200) { return res.status(200).json({ data: { user: { _id: data._id, fullname: data.fullname, } } }); } else { return res.status(statusCode).json({ data: data }); } } export const getUser = (req, res) => { const user = req.user; if (!user) { buildResponse(401, req.err, res); } else { buildResponse(200, user, res); } }; export const updateUser = async (req, res) => { const errorMessage = 'Sorry. I could not update that user'; const user = req.user; user.name = req.body.name; user.fullname = req.body.fullname; user.initials = req.body.initials; saveUserService(user, res); }; export const removeUser = (req, res) => { const errorMessage = 'Sorry. I could not remove that user'; const user = req.user; removeUserService(user, res); };
'use strict'; import { userModel } from '../../../models/index'; const buildResponse = (statusCode, data, res) => { if (statusCode === 200) { return res.status(200).json({ data: { user: { _id: data._id, fullname: data.fullname, } } }); } else { return res.status(statusCode).json({ data: data }); } } export const getUser = (req, res) => { const user = req.user; if (!user) { buildResponse(401, req.err, res); } else { buildResponse(200, user, res); } }; export const updateUser = (req, res) => { const errorMessage = 'Sorry. I could not update that user'; const user = req.user; user.name = req.body.name; user.fullname = req.body.fullname; user.initials = req.body.initials; user.save() .then(user => buildResponse(200, user, res)) .catch(error => buildResponse(404, errorMessage, res)); }; export const removeUser = (req, res) => { const errorMessage = 'Sorry. I could not remove that user'; const user = req.user; user.remove() .then(user => buildResponse(200, user, res)) .catch(error => buildResponse(404, errorMessage, res)); };
[test] Add a failing test for `content-type` header
var http = require('http'), assert = require('assert'), cb = require('assert-called'), resourceful = require('resourceful'); require('../'); var PORT = 8123, gotCallbacks = 0; function maybeEnd() { if (++gotCallbacks === 2) { server.close(); } } var server = http.createServer(function (req, res) { assert.equal(req.url, '/?event=create'); assert.equal(req.headers['content-type'], 'application/json'); var data = ''; req.on('data', function (chunk) { data += chunk; }); req.on('end', function () { data = JSON.parse(data); if (data.hello === 'world') { res.writeHead(200); res.end(); } else if (data.hello === 'universe') { res.writeHead(400); res.end(); } else { assert(false); } maybeEnd(); }); }).listen(PORT); var Resource = resourceful.define('Resource', function () { this.webhooks({ url: 'http://127.0.0.1:' + PORT.toString(), events: ['create'] }); }); Resource.create({ id: 'resource/good', hello: 'world' }, cb(function goodCb(err) { assert(!err); })); Resource.create({ id: 'resource/bad', hello: 'universe' }, cb(function badCb(err) { assert(err); }));
var http = require('http'), assert = require('assert'), cb = require('assert-called'), resourceful = require('resourceful'); require('../'); var PORT = 8123, gotCallbacks = 0; function maybeEnd() { if (++gotCallbacks === 2) { server.close(); } } var server = http.createServer(function (req, res) { assert.equal(req.url, '/?event=create'); var data = ''; req.on('data', function (chunk) { data += chunk; }); req.on('end', function () { data = JSON.parse(data); if (data.hello === 'world') { res.writeHead(200); res.end(); } else if (data.hello === 'universe') { res.writeHead(400); res.end(); } else { assert(false); } maybeEnd(); }); }).listen(PORT); var Resource = resourceful.define('Resource', function () { this.webhooks({ url: 'http://127.0.0.1:' + PORT.toString(), events: ['create'] }); }); Resource.create({ id: 'resource/good', hello: 'world' }, cb(function goodCb(err) { assert(!err); })); Resource.create({ id: 'resource/bad', hello: 'universe' }, cb(function badCb(err) { assert(err); }));
Fix time tests by adding Date to sandbox. Since tests are now run in their own sandbox, assert.deepEqual was not properly testing the returned Date objects for equality, as they weren't instances of the same Date class used by the test itself, causing type inference to fail. It was always returning true, even for different dates.
process.env.TZ = "America/Los_Angeles"; var smash = require("smash"), jsdom = require("jsdom"); require("./XMLHttpRequest"); module.exports = function() { var files = [].slice.call(arguments).map(function(d) { return "src/" + d; }), expression = "d3", sandbox = {Date: Date}; // so we can use deepEqual in tests files.unshift("src/start"); files.push("src/end"); function topic() { smash.load(files, expression, sandbox, this.callback); } topic.expression = function(_) { expression = _; return topic; }; topic.document = function(_) { var document = jsdom.jsdom("<html><head></head><body></body></html>"); // Monkey-patch createRange support to JSDOM. document.createRange = function() { return { selectNode: function() {}, createContextualFragment: jsdom.jsdom }; }; sandbox = { console: console, XMLHttpRequest: XMLHttpRequest, document: document, window: document.createWindow(), setTimeout: setTimeout, clearTimeout: clearTimeout, Date: Date // so we can override Date.now in tests, and use deepEqual }; return topic; }; return topic; }; process.on("uncaughtException", function(e) { console.trace(e.stack); });
process.env.TZ = "America/Los_Angeles"; var smash = require("smash"), jsdom = require("jsdom"); require("./XMLHttpRequest"); module.exports = function() { var files = [].slice.call(arguments).map(function(d) { return "src/" + d; }), expression = "d3", sandbox = null; files.unshift("src/start"); files.push("src/end"); function topic() { smash.load(files, expression, sandbox, this.callback); } topic.expression = function(_) { expression = _; return topic; }; topic.document = function(_) { var document = jsdom.jsdom("<html><head></head><body></body></html>"); // Monkey-patch createRange support to JSDOM. document.createRange = function() { return { selectNode: function() {}, createContextualFragment: jsdom.jsdom }; }; sandbox = { console: console, XMLHttpRequest: XMLHttpRequest, document: document, window: document.createWindow(), setTimeout: setTimeout, clearTimeout: clearTimeout, Date: Date // so we can override Date.now in tests }; return topic; }; return topic; }; process.on("uncaughtException", function(e) { console.trace(e.stack); });
Fix to_host_port_tuple to resolve test case issues
# -*- coding: utf-8 -*- """ hyper/common/util ~~~~~~~~~~~~~~~~~ General utility functions for use with hyper. """ from hyper.compat import unicode, bytes, imap def to_bytestring(element): """ Converts a single string to a bytestring, encoding via UTF-8 if needed. """ if isinstance(element, unicode): return element.encode('utf-8') elif isinstance(element, bytes): return element else: raise ValueError("Non string type.") def to_bytestring_tuple(*x): """ Converts the given strings to a bytestring if necessary, returning a tuple. Uses ``to_bytestring``. """ return tuple(imap(to_bytestring, x)) def to_host_port_tuple(host_port_str, default_port=80): """ Converts the given string containing a host and possibly a port to a tuple. """ if ']' in host_port_str: delim = ']:' else: delim = ':' try: host, port = host_port_str.rsplit(delim, 1) except ValueError: host, port = host_port_str, default_port else: port = int(port) host = host.strip('[]') return ((host, port))
# -*- coding: utf-8 -*- """ hyper/common/util ~~~~~~~~~~~~~~~~~ General utility functions for use with hyper. """ from hyper.compat import unicode, bytes, imap def to_bytestring(element): """ Converts a single string to a bytestring, encoding via UTF-8 if needed. """ if isinstance(element, unicode): return element.encode('utf-8') elif isinstance(element, bytes): return element else: raise ValueError("Non string type.") def to_bytestring_tuple(*x): """ Converts the given strings to a bytestring if necessary, returning a tuple. Uses ``to_bytestring``. """ return tuple(imap(to_bytestring, x)) def to_host_port_tuple(host_port_str, default_port=80): """ Converts the given string containing a host and possibly a port to a tuple. """ try: host, port = host_port_str.rsplit(':', 1) except ValueError: host, port = host_port_str, default_port else: port = int(port) host = host.strip('[]') return ((host, port))
Set "{ecmaVersion: 6}" for falafel's acorn
var falafel = require('falafel'); module.exports = replace; function replace (src, deps) { return falafel(src, {ecmaVersion: 6}, function (node) { if (isRequire(node)) { var value = node.arguments[0].value; if (has(deps, value) && deps[value]) { node.update('require(' + JSON.stringify(deps[value]) + ')'); } } }).toString(); } function isRequire (node) { var c = node.callee; return c && node.type === 'CallExpression' && c.type === 'Identifier' && c.name === 'require' && node.arguments[0] && node.arguments[0].type === 'Literal' ; } function has (obj, key) { return Object.prototype.hasOwnProperty.call(obj, key); }
var falafel = require('falafel'); module.exports = replace; function replace (src, deps) { return falafel(src, function (node) { if (isRequire(node)) { var value = node.arguments[0].value; if (has(deps, value) && deps[value]) { node.update('require(' + JSON.stringify(deps[value]) + ')'); } } }).toString(); } function isRequire (node) { var c = node.callee; return c && node.type === 'CallExpression' && c.type === 'Identifier' && c.name === 'require' && node.arguments[0] && node.arguments[0].type === 'Literal' ; } function has (obj, key) { return Object.prototype.hasOwnProperty.call(obj, key); }
Remove unneeded import, fix python path and add coding
#!/usr/bin/env python # coding=utf-8 from Handler import Handler import urllib2 class HttpPostHandler(Handler): # Inititalize Handler with url and batch size def __init__(self, config=None): Handler.__init__(self, config) self.metrics = [] self.batch_size = int(self.config.get('batch', 100)) self.url = self.config.get('url') # Join batched metrics and push to url mentioned in config def process(self, metric): self.metrics.append(str(metric)) if len(self.metrics) >= self.batch_size: req = urllib2.Request(self.url, "\n".join(self.metrics)) urllib2.urlopen(req) self.metrics = []
#!/usr/bin/python2.7 from Handler import Handler import urllib import urllib2 class HttpPostHandler(Handler): # Inititalize Handler with url and batch size def __init__(self, config=None): Handler.__init__(self, config) self.metrics = [] self.batch_size = int(self.config.get('batch', 100)) self.url = self.config.get('url') # Join batched metrics and push to url mentioned in config def process(self, metric): self.metrics.append(str(metric)) if len(self.metrics) >= self.batch_size: req = urllib2.Request(self.url, "\n".join(self.metrics)) urllib2.urlopen(req) self.metrics = []
Change test to match new word format.
"use strict"; var adjAdjAnimal = require("../lib/index"); var expect = require("chai").expect; describe("the library", function () { describe("getting a default id", function () { var result; before(function () { return adjAdjAnimal() .then(function (id) { result = id; }); }); it("generates adj-adj-animal", function () { expect(result, "matches").to.match(/[A-Z][a-z]+[A-Z][a-z]+[A-Z][a-z]+/); }); }); describe("getting an id with specified number of adjectives", function () { var result; before(function () { return adjAdjAnimal(6) .then(function (id) { result = id; }); }); it("generates adj-{6}animal", function () { expect(result, "matches").to.match(/([A-Z][a-z]+){6}[A-Z][a-z]+/); }); }); });
"use strict"; var adjAdjAnimal = require("../lib/index"); var expect = require("chai").expect; describe("the library", function () { describe("getting a default id", function () { var result; before(function () { return adjAdjAnimal() .then(function (id) { result = id; }); }); it("generates adj-adj-animal", function () { expect(result, "matches").to.match(/[a-z]+-[a-z]+-[a-z]+/); }); }); describe("getting an id with specified number of adjectives", function () { var result; before(function () { return adjAdjAnimal(6) .then(function (id) { result = id; }); }); it("generates adj-{6}animal", function () { expect(result, "matches").to.match(/([a-z]+-){6}[a-z]+/); }); }); });
Update to return the correct mangled string
var esprima = require('esprima'); var esmangle = require('esmangle'); var escodegen = require('escodegen'); Blend.defineClass('Minify', { singleton: true, js: function (scripts) { var ast = esprima.parse(scripts.join(';')); var optimized = esmangle.optimize(ast, null); var result = esmangle.mangle(optimized); return escodegen.generate(result, { format: { renumber: true, hexadecimal: true, escapeless: true, compact: true, semicolons: false, parentheses: false } }); } });
var esprima = require('esprima'); var esmangle = require('esmangle'); var escodegen = require('escodegen'); Blend.defineClass('Minify', { singleton: true, js: function (scripts) { var ast = esprima.parse(scripts.join(';')); var optimized = esmangle.optimize(ast, null); var result = esmangle.mangle(optimized); result = escodegen.generate(result, { format: { renumber: true, hexadecimal: true, escapeless: true, compact: true, semicolons: false, parentheses: false } }); return result.toString(); } });
Delete all jobs on cleanup
var express = require('express'); var kue = require('kue'); var Bot = require('../models/bot'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index'); }); router.post('/destroy_jobs', function(req, res, next) { kue.Job.rangeByState('delayed', 0, 10000, 'asc', function( err, jobs ) { jobs.forEach(function(job) { job.remove(function() {}); }); res.send(); }); }); router.post('/destroy_all_the_things', function(req, res, next) { ['Queued', 'Active', 'Failed', 'Complete', 'Delayed'].forEach(function(state) { kue.Job.rangeByState(state, 0, 999999, 'asc', function( err, jobs ) { jobs.forEach(function(job) { job.remove(function(err) { if (err) console.log(err); }); }); }); }); Bot.remove({}) .then(function(result) { }) .catch(function(err) { res.status(500).send(err); }); res.send(); }); module.exports = router;
var express = require('express'); var kue = require('kue'); var Bot = require('../models/bot'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index'); }); router.post('/destroy_jobs', function(req, res, next) { kue.Job.rangeByState('delayed', 0, 10000, 'asc', function( err, jobs ) { jobs.forEach(function(job) { job.remove(function() {}); }); res.send(); }); }); router.post('/destroy_all_the_things', function(req, res, next) { var deleteJob = function(state) { kue.Job.rangeByState(state, 0, 999999, 'asc', function( err, jobs ) { jobs.forEach(function(job) { job.remove(function(err) { if (err) console.log(err); }); }); }); } deleteJob('complete'); deleteJob('delayed'); Bot.remove({}) .then(function(result) { }) .catch(function(err) { res.status(500).send(err); }); res.send(); }); module.exports = router;
Handle socket_create not being available
<?php function pole_display_price($label, $price) { if (!function_exists('socket_create')) return; $sock= socket_create(AF_INET, SOCK_STREAM, SOL_TCP); /* Set 1 sec timeout to avoid getting stuck, should be plenty long enough */ socket_set_option($sock, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 1, 'usec' => 0)); if (@socket_connect($sock, '127.0.0.1', 1888)) { socket_write($sock, sprintf("\x0a\x0d%-19.19s\x0a\x0d$%18.2f ", $label, $price)); } }
<?php function pole_display_price($label, $price) { $sock= socket_create(AF_INET, SOCK_STREAM, SOL_TCP); /* Set 1 sec timeout to avoid getting stuck, should be plenty long enough */ socket_set_option($sock, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 1, 'usec' => 0)); if (@socket_connect($sock, '127.0.0.1', 1888)) { socket_write($sock, sprintf("\x0a\x0d%-19.19s\x0a\x0d$%18.2f ", $label, $price)); } }
Use MultiCurl::setConcurrency() in load test example
<?php require __DIR__ . '/../vendor/autoload.php'; use \Curl\MultiCurl; $server_count = 10; $urls = array(); $port = 8000; for ($i = 0; $i < $server_count; $i++) { $port += 1; $urls[] = 'http://localhost:' . $port . '/'; } $multi_curl = new MultiCurl(); $multi_curl->setConcurrency(30); $success = 0; $error = 0; $complete = 0; $multi_curl->success(function ($instance) use (&$success) { $success += 1; }); $multi_curl->error(function ($instance) use (&$error) { $error += 1; }); $multi_curl->complete(function ($instance) use (&$complete) { $complete += 1; }); $limit = 1000; for ($i = 0; $i < $limit; $i++) { $url = $urls[mt_rand(0, count($urls) - 1)]; $multi_curl->addGet($url); } $multi_curl->start(); echo 'complete: ' . $complete . "\n"; echo 'success: ' . $success . "\n"; echo 'error: ' . $error . "\n"; echo 'done' . "\n";
<?php require __DIR__ . '/../vendor/autoload.php'; use \Curl\MultiCurl; $server_count = 10; $urls = array(); $port = 8000; for ($i = 0; $i < $server_count; $i++) { $port += 1; $urls[] = 'http://localhost:' . $port . '/'; } $multi_curl = new MultiCurl(); $success = 0; $error = 0; $complete = 0; $multi_curl->success(function ($instance) use (&$success) { $success += 1; }); $multi_curl->error(function ($instance) use (&$error) { $error += 1; }); $multi_curl->complete(function ($instance) use (&$complete) { $complete += 1; }); $limit = 1000; for ($i = 0; $i < $limit; $i++) { $url = $urls[mt_rand(0, count($urls) - 1)]; $multi_curl->addGet($url); } $multi_curl->start(); echo 'complete: ' . $complete . "\n"; echo 'success: ' . $success . "\n"; echo 'error: ' . $error . "\n"; echo 'done' . "\n";
Use equal matcher for remaining keys
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from testtools import matchers from spreadflow_core.test.matchers import MatchesInvocation class MatchesDeltaItem(matchers.MatchesDict): def __init__(self, item): spec = { 'data': matchers.Equals(item['data']), 'inserts': matchers.MatchesSetwise(*[matchers.Equals(oid) for oid in item['inserts']]), 'deletes': matchers.MatchesSetwise(*[matchers.Equals(oid) for oid in item['deletes']]) } if 'parent' in item: spec['parent'] = MatchesDeltaItem(item['parent']) # Use equal matcher for remaining keys. for key in set(item.keys()) - set(spec.keys()): spec[key] = matchers.Equals(item[key]) super(MatchesDeltaItem, self).__init__(spec) class MatchesSendDeltaItemInvocation(MatchesInvocation): def __init__(self, expected_item, expected_port): super(MatchesSendDeltaItemInvocation, self).__init__( MatchesDeltaItem(expected_item), matchers.Equals(expected_port) )
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from testtools import matchers from spreadflow_core.test.matchers import MatchesInvocation class MatchesDeltaItem(matchers.MatchesDict): def __init__(self, item): spec = { 'data': matchers.Equals(item['data']), 'inserts': matchers.MatchesSetwise(*[matchers.Equals(oid) for oid in item['inserts']]), 'deletes': matchers.MatchesSetwise(*[matchers.Equals(oid) for oid in item['deletes']]) } if 'parent' in item: spec['parent'] = MatchesDeltaItem(item['parent']) super(MatchesDeltaItem, self).__init__(spec) class MatchesSendDeltaItemInvocation(MatchesInvocation): def __init__(self, expected_item, expected_port): super(MatchesSendDeltaItemInvocation, self).__init__( MatchesDeltaItem(expected_item), matchers.Equals(expected_port) )
Fix monkey patching to pass kwargs required by Python 3.4
import xml.etree.ElementTree as E from authorize.configuration import Configuration from authorize.address import Address from authorize.bank_account import BankAccount from authorize.batch import Batch from authorize.credit_card import CreditCard from authorize.customer import Customer from authorize.environment import Environment from authorize.exceptions import AuthorizeError from authorize.exceptions import AuthorizeConnectionError from authorize.exceptions import AuthorizeResponseError from authorize.exceptions import AuthorizeInvalidError from authorize.recurring import Recurring from authorize.transaction import Transaction # Monkeypatch the ElementTree module so that we can use CDATA element types E._original_serialize_xml = E._serialize_xml def _serialize_xml(write, elem, *args, **kwargs): if elem.tag == '![CDATA[': write('<![CDATA[%s]]>' % elem.text) return return E._original_serialize_xml(write, elem, *args, **kwargs) E._serialize_xml = E._serialize['xml'] = _serialize_xml
import xml.etree.ElementTree as E from authorize.configuration import Configuration from authorize.address import Address from authorize.bank_account import BankAccount from authorize.batch import Batch from authorize.credit_card import CreditCard from authorize.customer import Customer from authorize.environment import Environment from authorize.exceptions import AuthorizeError from authorize.exceptions import AuthorizeConnectionError from authorize.exceptions import AuthorizeResponseError from authorize.exceptions import AuthorizeInvalidError from authorize.recurring import Recurring from authorize.transaction import Transaction # Monkeypatch the ElementTree module so that we can use CDATA element types E._original_serialize_xml = E._serialize_xml def _serialize_xml(write, elem, *args): if elem.tag == '![CDATA[': write('<![CDATA[%s]]>' % elem.text) return return E._original_serialize_xml(write, elem, *args) E._serialize_xml = E._serialize['xml'] = _serialize_xml
Change how StringIO is imported
import contextlib import re import sys import mock import six from random_object_id.random_object_id import \ gen_random_object_id, parse_args, main @contextlib.contextmanager def captured_output(): old_out = sys.stdout try: sys.stdout = six.StringIO() yield sys.stdout finally: sys.stdout = old_out def test_gen_random_object_id(): assert re.match('[0-9a-f]{24}', gen_random_object_id()) def test_gen_random_object_id_time(): with mock.patch('time.time') as mock_time: mock_time.return_value = 1429506585.786924 object_id = gen_random_object_id() assert re.match('55348a19', object_id) def test_parse_args(): assert parse_args(['-l']).long_form def test_main(): with mock.patch('sys.argv', ['random_object_id']): with captured_output() as output: main() assert re.match('[0-9a-f]{24}\n', output.getvalue()) def test_main_l(): with mock.patch('sys.argv', ['random_object_id', '-l']): with captured_output() as output: main() assert re.match('ObjectId\("[0-9a-f]{24}"\)\n', output.getvalue())
import contextlib import re import sys import mock from six.moves import cStringIO from random_object_id.random_object_id import \ gen_random_object_id, parse_args, main @contextlib.contextmanager def captured_output(): new_out = StringIO() old_out = sys.stdout try: sys.stdout = new_out yield sys.stdout finally: sys.stdout = old_out def test_gen_random_object_id(): assert re.match('[0-9a-f]{24}', gen_random_object_id()) def test_gen_random_object_id_time(): with mock.patch('time.time') as mock_time: mock_time.return_value = 1429506585.786924 object_id = gen_random_object_id() assert re.match('55348a19', object_id) def test_parse_args(): assert parse_args(['-l']).long_form def test_main(): with mock.patch('sys.argv', ['random_object_id']): with captured_output() as output: main() assert re.match('[0-9a-f]{24}\n', output.getvalue()) def test_main_l(): with mock.patch('sys.argv', ['random_object_id', '-l']): with captured_output() as output: main() assert re.match('ObjectId\("[0-9a-f]{24}"\)\n', output.getvalue())
Fix 1.7 wrapper instancing minecraft client class
package fr.ourten.brokkgui.wrapper; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import fr.ourten.brokkgui.BrokkGuiPlatform; /** * @author Ourten 5 oct. 2016 */ @Mod(modid = BrokkGuiWrapperMod.MODID, version = BrokkGuiWrapperMod.VERSION, name = BrokkGuiWrapperMod.MODNAME) public class BrokkGuiWrapperMod { public static final String MODID = "brokkguiwrapper"; public static final String MODNAME = "BrokkGui Wrapper"; public static final String VERSION = "0.1.0"; @EventHandler public void onPreInit(final FMLPreInitializationEvent event) { BrokkGuiPlatform.getInstance().setPlatformName("MC1.7.10"); BrokkGuiPlatform.getInstance().setKeyboardUtil(new KeyboardUtil()); BrokkGuiPlatform.getInstance().setMouseUtil(new MouseUtil()); if (event.getSide().isClient()) BrokkGuiPlatform.getInstance().setGuiHelper(new GuiHelper()); } }
package fr.ourten.brokkgui.wrapper; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import fr.ourten.brokkgui.BrokkGuiPlatform; /** * @author Ourten 5 oct. 2016 */ @Mod(modid = BrokkGuiWrapperMod.MODID, version = BrokkGuiWrapperMod.VERSION, name = BrokkGuiWrapperMod.MODNAME) public class BrokkGuiWrapperMod { public static final String MODID = "brokkguiwrapper"; public static final String MODNAME = "BrokkGui Wrapper"; public static final String VERSION = "0.1.0"; @EventHandler public void onPreInit(final FMLPreInitializationEvent event) { BrokkGuiPlatform.getInstance().setPlatformName("MC1.7.10"); BrokkGuiPlatform.getInstance().setKeyboardUtil(new KeyboardUtil()); BrokkGuiPlatform.getInstance().setMouseUtil(new MouseUtil()); BrokkGuiPlatform.getInstance().setGuiHelper(new GuiHelper()); } }
Update for new Moment.js API
/* * Clock plugin using Moment.js (http://momentjs.com/) to * format the time and date. * * The only exposed property, 'format', determines the * format (see Moment.js documentation) to display time and date. * * Requires 'jquery' and 'moment' to be available through RequireJS. */ define(['jquery', 'moment'], function ($, moment) { "use strict"; var config = { format: 'llll' }; function updateClock() { var dt = moment(); var clockText = dt.format(config.format); $('.widget-time').text(clockText); var interval = 59 - dt.second(); if (interval < 1) { interval = 1; } else if (interval > 5) { interval = 5; } setTimeout(updateClock, interval * 1000); } $(document).ready(function () { var lang = navigator.language; if (moment.localeData(lang)) { moment.locale(lang); } else { moment.locale(navigator.language.replace(/-.+/, '')); } updateClock(); }); return config; });
/* * Clock plugin using Moment.js (http://momentjs.com/) to * format the time and date. * * The only exposed property, 'format', determines the * format (see Moment.js documentation) to display time and date. * * Requires 'jquery' and 'moment' to be available through RequireJS. */ define(['jquery', 'moment'], function ($, moment) { "use strict"; var config = { format: 'llll' }; function updateClock() { var dt = moment(); var clockText = dt.format(config.format); $('.widget-time').text(clockText); var interval = 59 - dt.second(); if (interval < 1) { interval = 1; } else if (interval > 5) { interval = 5; } setTimeout(updateClock, interval * 1000); } $(document).ready(function () { var lang = navigator.language; if (moment.langData(lang)) { moment.lang(lang); } else { moment.lang(navigator.language.replace(/-.+/, '')); } updateClock(); }); return config; });
Fix casting for Pulses and added getUpdates()
<?php namespace allejo\DaPulse; use allejo\DaPulse\Objects\ApiPulse; class PulseProject extends ApiPulse { const API_PREFIX = "pulses"; private $urlSyntax = "%s/%s/%s.json"; public function getSubscribers($params = array()) { $url = sprintf($this->urlSyntax, parent::apiEndpoint(), $this->id, "subscribers"); return parent::fetchJsonArrayToObjectArray($url, "PulseUser", $params); } public function getNotes() { $url = sprintf($this->urlSyntax, parent::apiEndpoint(), $this->id, "notes"); return parent::fetchJsonArrayToObjectArray($url, "PulseNote"); } public function getUpdates() { $url = sprintf($this->urlSyntax, parent::apiEndpoint(), $this->id, "updates"); return parent::fetchJsonArrayToObjectArray($url, "PulseUpdate"); } public static function getPulses($params = array()) { $url = sprintf("%s.json", parent::apiEndpoint()); return parent::fetchJsonArrayToObjectArray($url, "PulseProject", $params); } }
<?php namespace allejo\DaPulse; use allejo\DaPulse\Objects\ApiPulse; class PulseProject extends ApiPulse { const API_PREFIX = "pulses"; private $urlSyntax = "%s/%s/%s.json"; public function getSubscribers($params = array()) { $url = sprintf($this->urlSyntax, parent::apiEndpoint(), $this->id, "subscribers"); return parent::fetchJsonArrayToObjectArray($url, "PulseUser", $params); } public function getNotes() { $url = sprintf($this->urlSyntax, parent::apiEndpoint(), $this->id, "notes"); return parent::fetchJsonArrayToObjectArray($url, "PulseNote"); } public static function getPulses($params = array()) { $url = sprintf("%s.json", parent::apiEndpoint()); return parent::fetchJsonArrayToObjectArray($url, "PulsePulse", $params); } }
Fix Replication compilation error (CE) We have changed an abstact method initC4Socket(int) to initSocketFactory(Object). The implmenation change has been made to the EE version. The CE version of the Replicator class needs to follow.
package com.couchbase.lite; import android.support.annotation.NonNull; import com.couchbase.lite.internal.replicator.CBLWebSocket; import com.couchbase.litecore.C4Socket; public final class Replicator extends AbstractReplicator { /** * Initializes a replicator with the given configuration. * * @param config */ public Replicator(@NonNull ReplicatorConfiguration config) { super(config); } @Override void initSocketFactory(Object socketFactoryContext) { C4Socket.socketFactory.put(socketFactoryContext, CBLWebSocket.class); } @Override int framing() { return C4Socket.kC4NoFraming; } @Override String schema() { return null; } }
package com.couchbase.lite; import android.support.annotation.NonNull; import com.couchbase.lite.internal.replicator.CBLWebSocket; import com.couchbase.litecore.C4Socket; public final class Replicator extends AbstractReplicator { /** * Initializes a replicator with the given configuration. * * @param config */ public Replicator(@NonNull ReplicatorConfiguration config) { super(config); } @Override void initC4Socket(int hash) { C4Socket.socketFactory.put(hash, CBLWebSocket.class); } @Override int framing() { return C4Socket.kC4NoFraming; } @Override String schema() { return null; } }
Use empty instead of empty + isset
<?php use_helper('Text') ?> <article class="search-result"> <div class="search-result-description"> <p class="title"><?php echo link_to(get_search_i18n($doc, 'authorizedFormOfName'), array('module' => 'actor', 'slug' => $doc['slug'])) ?></p> <ul class="result-details"> <?php if (!empty($doc['descriptionIdentifier'])): ?> <li class="reference-code"><?php echo $doc['descriptionIdentifier'] ?></li> <?php endif; ?> <?php if (!empty($types[$doc['entityTypeId']])): ?> <li><?php echo $types[$doc['entityTypeId']] ?></li> <?php endif; ?> <li><?php echo get_search_i18n($doc, 'datesOfExistence') ?></li> </ul> </div> </article>
<?php use_helper('Text') ?> <article class="search-result"> <div class="search-result-description"> <p class="title"><?php echo link_to(get_search_i18n($doc, 'authorizedFormOfName'), array('module' => 'actor', 'slug' => $doc['slug'])) ?></p> <ul class="result-details"> <?php if (isset($doc['descriptionIdentifier']) && !empty($doc['descriptionIdentifier'])): ?> <li class="reference-code"><?php echo $doc['descriptionIdentifier'] ?></li> <?php endif; ?> <?php if (isset($doc['entityTypeId']) && isset($types[$doc['entityTypeId']])): ?> <li><?php echo $types[$doc['entityTypeId']] ?></li> <?php endif; ?> <li><?php echo get_search_i18n($doc, 'datesOfExistence') ?></li> </ul> </div> </article>
Disable test until filesystem-graph issue works - seems that this error comes in test environment, have to figure out is this something phantomjs specific...
var env = require('../env'); var fs = require('fs'); env.init(); var name = "navigate-to-radiator"; var waitTimeout = 2000; casper.test.begin('navigate to host page', 1, function(test) { casper.start(env.root + "/#metric=cpu&timescale=10800", function() { test.assertExists(env.cpuLink, "common navigation is initialized"); }); //FIXME resolve issue with filesystem-graph.js // TypeError: 'undefined' is not a function (evaluating 'nv.utils.optionsFunc.bind(chart)') //http://localhost:5120/scripts/lib/nv.d3.js:11422 //http://localhost:5120/scripts/lib/nv.d3.js:5128 //http://localhost:5120/scripts/lib/nv.d3.js:5402 //http://localhost:5120/scripts/modules/graphs/heap-graph.js:28 //http://localhost:5120/scripts/lib/nv.d3.js:65 //casper.waitUntilVisible(env.hostLink, function() { // this.click(env.hostLink); //}, env.screencapFailure, waitTimeout); // //casper.waitForPopup(/radiator\.html/, function() { // //FIXME should assert something actual popup count..? //}, env.screencapFailure, waitTimeout); // //casper.withPopup(/radiator\.html/, function() { // this.capture('debugging-in-popup.png'); // //FIXME should assert something actual element presence here //}); // //casper.waitUntilVisible(env.heapDiv, function() { // env.writeCoverage(this, name); //}, env.screencapFailure, waitTimeout); casper.run(function() { test.done(); }); });
var env = require('../env'); var fs = require('fs'); env.init(); var name = "navigate-to-radiator"; var waitTimeout = 2000; casper.test.begin('navigate to host page', 2, function(test) { casper.start(env.root + "/#metric=cpu&timescale=10800", function() { test.assertExists(env.cpuLink); }); casper.waitUntilVisible(env.hostLink, function() { this.click(env.hostLink); }, env.screencapFailure, waitTimeout); casper.waitForPopup(/radiator\.html/, function() { //FIXME should assert something actual popup count..? }, env.screencapFailure, waitTimeout); casper.withPopup(/radiator\.html/, function() { //FIXME should assert something actual element presence here }); casper.waitUntilVisible(env.heapDiv, function() { env.writeCoverage(this, name); }, env.screencapFailure, waitTimeout); casper.run(function() { test.done(); }); });
Add the blacklist checking to the bulk
from datetime import timedelta CELERYBEAT_SCHEDULE = { "reddit-validations": { "task": "reddit.tasks.process_validations", "schedule": timedelta(minutes=10), }, "eveapi-update": { "task": "eve_api.tasks.account.queue_apikey_updates", "schedule": timedelta(minutes=10), }, "alliance-update": { "task": "eve_api.tasks.alliance.import_alliance_details", "schedule": timedelta(hours=6), }, "api-log-clear": { "task": "eve_proxy.tasks.clear_old_logs", "schedule": timedelta(days=1), }, "blacklist-check": { "task": "hr.tasks.blacklist_check", "schedule": timedelta(days=1), }, "reddit-update": { "task": "reddit.tasks.queue_account_updates", "schedule": timedelta(minutes=15), } } CELERY_ROUTES = { "sso.tasks.update_service_groups": {'queue': 'bulk'}, "hr.tasks.blacklist_check": {'queue': 'bulk'}, }
from datetime import timedelta CELERYBEAT_SCHEDULE = { "reddit-validations": { "task": "reddit.tasks.process_validations", "schedule": timedelta(minutes=10), }, "eveapi-update": { "task": "eve_api.tasks.account.queue_apikey_updates", "schedule": timedelta(minutes=10), }, "alliance-update": { "task": "eve_api.tasks.alliance.import_alliance_details", "schedule": timedelta(hours=6), }, "api-log-clear": { "task": "eve_proxy.tasks.clear_old_logs", "schedule": timedelta(days=1), }, "blacklist-check": { "task": "hr.tasks.blacklist_check", "schedule": timedelta(days=1), }, "reddit-update": { "task": "reddit.tasks.queue_account_updates", "schedule": timedelta(minutes=15), } } CELERY_ROUTES = { "sso.tasks.update_service_groups": {'queue': 'bulk'}, }
Fix stack node types mismatch
package org.spoofax.jsglr2.measure.parsing; import org.spoofax.jsglr2.parseforest.IDerivation; import org.spoofax.jsglr2.parseforest.IParseForest; import org.spoofax.jsglr2.parseforest.IParseNode; import org.spoofax.jsglr2.parser.AbstractParseState; import org.spoofax.jsglr2.stack.StackLink; import org.spoofax.jsglr2.stack.hybrid.HybridStackNode; class StandardParserMeasureObserver //@formatter:off <ParseForest extends IParseForest, Derivation extends IDerivation<ParseForest>, ParseNode extends IParseNode<ParseForest, Derivation>> //@formatter:on extends ParserMeasureObserver<ParseForest, Derivation, ParseNode, HybridStackNode<ParseForest>, AbstractParseState<?, HybridStackNode<ParseForest>>> { @Override int stackNodeLinkCount(HybridStackNode<ParseForest> stackNode) { int linksOutCount = 0; for(StackLink<?, ?> link : stackNode.getLinks()) linksOutCount++; return linksOutCount; } }
package org.spoofax.jsglr2.measure.parsing; import org.spoofax.jsglr2.parseforest.IDerivation; import org.spoofax.jsglr2.parseforest.IParseForest; import org.spoofax.jsglr2.parseforest.IParseNode; import org.spoofax.jsglr2.parser.AbstractParseState; import org.spoofax.jsglr2.stack.StackLink; import org.spoofax.jsglr2.stack.basic.BasicStackNode; class StandardParserMeasureObserver //@formatter:off <ParseForest extends IParseForest, Derivation extends IDerivation<ParseForest>, ParseNode extends IParseNode<ParseForest, Derivation>> //@formatter:on extends ParserMeasureObserver<ParseForest, Derivation, ParseNode, BasicStackNode<ParseForest>, AbstractParseState<?, BasicStackNode<ParseForest>>> { @Override int stackNodeLinkCount(BasicStackNode<ParseForest> stackNode) { int linksOutCount = 0; for(StackLink<?, ?> link : stackNode.getLinks()) linksOutCount++; return linksOutCount; } }
Fix realtime notification, the id had been removed.
<script src="js/updater.js"></script> <?php include_once 'core.php'; include_once 'db.php'; ?> <a href="../"><img class="logo" src="files/logo.png" alt="Hallo"/></a> <?php if (isset($_GET['p'])) { echo '<ul class="navbar-p">'; } else { echo '<ul class="navbar">'; } ?> <li><form method="get" action="search.php" id="search"> <input type="hidden" name="mode" value="q"> <input name="query" type="text" size="40" placeholder="Search..." /> </form> </li> <li><a href="./">Home</a></li> <li class="notify-btn"><a href="notifications">Notifications<span id="ncounter" class="notify notification_counter"><?php echo count_unseen_notf($pdo) ?></span></a></li> <?php if (isset($_GET['p'])): ?> <li><a href="settings">Settings</a></li> <li><a href="friends.php?r=1&l=1">Friends</a></li> <?php else: $nickname = get_user()['nickname']; echo "<li><a href='./profile'>{$nickname}</a></li>"; endif; ?> <li><a href='./auth?op=x'>Logout</a></li> </ul>
<script src="js/updater.js"></script> <?php include_once 'core.php'; include_once 'db.php'; ?> <a href="../"><img class="logo" src="files/logo.png" alt="Hallo"/></a> <?php if (isset($_GET['p'])) { echo '<ul class="navbar-p">'; } else { echo '<ul class="navbar">'; } ?> <li><form method="get" action="search.php" id="search"> <input type="hidden" name="mode" value="q"> <input name="query" type="text" size="40" placeholder="Search..." /> </form> </li> <li><a href="./">Home</a></li> <li class="notify-btn"><a href="notifications">Notifications<span class="notify notification_counter"><?php echo count_unseen_notf($pdo) ?></span></a></li> <?php if (isset($_GET['p'])): ?> <li><a href="settings">Settings</a></li> <li><a href="friends.php?r=1&l=1">Friends</a></li> <?php else: $nickname = get_user()['nickname']; echo "<li><a href='./profile'>{$nickname}</a></li>"; endif; ?> <li><a href='./auth?op=x'>Logout</a></li> </ul>
Set sqlite as standard install method
<?php /** * Welcome to the Mackstar.Spout Project * * This is where the main configuration is added. * You can override this per environment in * /conf/env/{env}.php * */ $appDir = dirname(__DIR__); return [ 'tmp_dir' => dirname(__DIR__) . '/var/tmp', 'upload_dir' => dirname(__DIR__) . '/var/www/uploads', 'resource_dir' => dirname(__DIR__), 'lib_dir' => $appDir . '/lib', 'log_dir' => $appDir . '/var/log', 'template_dir' => $appDir . '/lib/twig/template', 'master_db' => [ 'driver' => 'pdo_sqlite', 'path' => __DIR__ . '/test_db.sqlite3', 'charset' => 'UTF8' ], 'slave_db' => [ 'driver' => 'pdo_sqlite', 'path' => __DIR__ . '/test_db.sqlite3', 'charset' => 'UTF8' ], ];
<?php /** * Welcome to the Mackstar.Spout Project * * This is where the main configuration is added. * You can override this per environment in * /conf/env/{env}.php * */ $appDir = dirname(__DIR__); return [ 'tmp_dir' => dirname(__DIR__) . '/var/tmp', 'upload_dir' => dirname(__DIR__) . '/var/www/uploads', 'resource_dir' => dirname(__DIR__), 'lib_dir' => $appDir . '/lib', 'log_dir' => $appDir . '/var/log', 'template_dir' => $appDir . '/lib/twig/template', 'master_db' => [ 'driver' => 'pdo_mysql', 'host' => 'localhost', 'dbname' => 'spout', 'user' => 'root', 'password' => '', 'port' => '3306', 'charset' => 'UTF8' ], 'slave_db' => [ 'driver' => 'pdo_mysql', 'host' => 'localhost', 'dbname' => 'spout', 'user' => 'root', 'password' => '', 'port' => '3306', 'charset' => 'UTF8' ], ];
Move the onClick from the wrapper to the status bullet
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import theme from './theme.css'; import Box from '../box'; import { TextSmall } from '../typography'; class ProgressStep extends PureComponent { render() { const { label, active, completed, onClick } = this.props; const classNames = cx(theme['step'], { [theme['is-active']]: active, [theme['is-completed']]: completed, [theme['is-clickable']]: onClick, }); return ( <Box className={classNames}> <TextSmall className={theme['step-label']}>{label}</TextSmall> <span className={theme['status-bullet']} onClick={onClick} /> </Box> ); } } ProgressStep.propTypes = { /** The label for the progress step */ label: PropTypes.string.isRequired, /** Whether or not the step is active */ active: PropTypes.bool.isRequired, /** Whether or not the step has been completed */ completed: PropTypes.bool.isRequired, /** Callback function that is fired when the progress step is clicked */ onClick: PropTypes.func, }; ProgressStep.defaultProps = { active: false, completed: false, }; export default ProgressStep;
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import theme from './theme.css'; import Box from '../box'; import { TextSmall } from '../typography'; class ProgressStep extends PureComponent { render() { const { label, active, completed, onClick } = this.props; const classNames = cx(theme['step'], { [theme['is-active']]: active, [theme['is-completed']]: completed, [theme['is-clickable']]: onClick, }); return ( <Box className={classNames} onClick={onClick}> <TextSmall className={theme['step-label']}>{label}</TextSmall> <span className={theme['status-bullet']} /> </Box> ); } } ProgressStep.propTypes = { /** The label for the progress step */ label: PropTypes.string.isRequired, /** Whether or not the step is active */ active: PropTypes.bool.isRequired, /** Whether or not the step has been completed */ completed: PropTypes.bool.isRequired, /** Callback function that is fired when the progress step is clicked */ onClick: PropTypes.func, }; ProgressStep.defaultProps = { active: false, completed: false, }; export default ProgressStep;
Move pg_query_init call to init(). Thank you PostgreSQL assertions :)
package pg_query // Note(LukasFittl): This needs Go 1.5 for $SRCDIR support, see // https://github.com/golang/go/commit/131758183f7dc2610af489da3a7fcc4d30c6bc48 /* #cgo CFLAGS: -I${SRCDIR}/tmp/libpg_query-master #cgo LDFLAGS: -L${SRCDIR}/tmp/libpg_query-master -lpg_query -fstack-protector #include <pg_query.h> #include <stdlib.h> */ import "C" import "unsafe" func init() { C.pg_query_init() } func Parse(input string) string { input_c := C.CString(input) defer C.free(unsafe.Pointer(input_c)) result_c := C.pg_query_parse(input_c) defer C.free(unsafe.Pointer(result_c.parse_tree)) defer C.free(unsafe.Pointer(result_c.stderr_buffer)) result := C.GoString(result_c.parse_tree) return result }
package pg_query // Note(LukasFittl): This needs Go 1.5 for $SRCDIR support, see // https://github.com/golang/go/commit/131758183f7dc2610af489da3a7fcc4d30c6bc48 /* #cgo CFLAGS: -I${SRCDIR}/tmp/libpg_query-master #cgo LDFLAGS: -L${SRCDIR}/tmp/libpg_query-master -lpg_query -fstack-protector #include <pg_query.h> #include <stdlib.h> */ import "C" import "unsafe" func Parse(input string) string { C.pg_query_init() input_c := C.CString(input) defer C.free(unsafe.Pointer(input_c)) result_c := C.pg_query_parse(input_c) defer C.free(unsafe.Pointer(result_c.parse_tree)) defer C.free(unsafe.Pointer(result_c.stderr_buffer)) result := C.GoString(result_c.parse_tree) return result }
Fix large stylesheet browser test
test('stylesheet_large.php', function (assert, document) { var h1 = document.getElementsByTagName('h1')[0]; var cs = document.defaultView.getComputedStyle(h1, null); var done = assert.async(); wait(); function wait() { if (document.querySelectorAll('style[data-phast-params]').length > 0) { return setTimeout(wait); } done(); assert.equal(cs.backgroundColor, 'rgb(242, 222, 222)', 'The <h1> should have a reddish background'); var styles = document.querySelectorAll('style'); assert.equal(styles.length, 1, 'There should be one style element on the page'); assert.ok(styles[0].textContent.length >= 120 * 1000, 'The stylesheet in <style> should be at least 120K') } });
test('stylesheet_large.php', function (assert, document) { var h1 = document.getElementsByTagName('h1')[0]; var cs = document.defaultView.getComputedStyle(h1, null); var done = assert.async(); wait(); function wait() { if (document.querySelectorAll('style[data-phast-href]').length > 0) { return setTimeout(wait); } done(); assert.equal(cs.backgroundColor, 'rgb(242, 222, 222)', 'The <h1> should have a reddish background'); var styles = document.querySelectorAll('style'); assert.equal(styles.length, 1, 'There should be one style element on the page'); assert.ok(styles[0].textContent.length >= 120 * 1000, 'The stylesheet in <style> should be at least 120K') } });
Allow render to take a template different from the default one.
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import, unicode_literals import itertools from .util import trim def render(item, **fields): """ Render the given item """ if item is None: return '' elif isinstance(item, Renderer): return item.render(**fields) elif isinstance(item, list): return ''.join(render(e) for e in item) else: return str(item) class Renderer(object): template = '' _counter = itertools.count() def __init__(self, template=None): if template is not None: self.template = template def counter(self): return next(self._counter) def render_fields(self, fields): pass def render(self, template=None, **fields): if template is None: template = self.template fields.update({k:v for k, v in vars(self).items() if not k.startswith('_')}) self.render_fields(fields) fields = {k:render(v) for k, v in fields.items()} try: return trim(template).format(**fields) except KeyError as e: raise KeyError(str(e), type(self))
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import, unicode_literals import itertools from .util import trim def render(item, **fields): """ Render the given item """ if item is None: return '' elif isinstance(item, Renderer): return item.render(**fields) elif isinstance(item, list): return ''.join(render(e) for e in item) else: return str(item) class Renderer(object): template = '' _counter = itertools.count() def __init__(self, template=None): if template is not None: self.template = template def counter(self): return next(self._counter) def render_fields(self, fields): pass def render(self, **fields): fields.update({k:v for k, v in vars(self).items() if not k.startswith('_')}) self.render_fields(fields) fields = {k:render(v) for k, v in fields.items()} try: return trim(self.template).format(**fields) except KeyError as e: raise KeyError(str(e), type(self))
Add authentication to the serverside
#!/usr/bin/env python from configReader import ConfigReader import sys import os, os.path import os.path from time import time from math import floor import hashlib import random import requests f = open('adjectives.txt','r') adjectives = [line.rstrip() for line in f] f.close() configReader = ConfigReader(name="clientConfig.txt") path = sys.argv[1] timeHash = hashlib.md5(str(time())).hexdigest()[0:6] adjective = random.choice(adjectives) keys=configReader.getKeys() endpoint=keys['endpoint'] username=keys['username'] password=keys['password'] finalLocation=keys['finalLocation'] urlPath = adjective+timeHash+".png" print "Uploading",path,"as",urlPath,"to",endpoint r = requests.post(endpoint,auth=(username,password),params={'name':urlPath},files={'file':open(path,'rb')}) print r.status_code if r.status_code==200: print os.path.join(finalLocation,urlPath) os.system("echo '"+os.path.join(finalLocation,urlPath)+"'|pbcopy")
#!/usr/bin/env python from configReader import ConfigReader import sys import os, os.path import os.path from time import time from math import floor import hashlib import random import requests f = open('adjectives.txt','r') adjectives = [line.rstrip() for line in f] f.close() configReader = ConfigReader(name="clientConfig.txt") path = sys.argv[1] timeHash = hashlib.md5(str(time())).hexdigest()[0:6] adjective = random.choice(adjectives) keys=configReader.getKeys() endpoint=keys['endpoint'] username=keys['username'] password=keys['password'] finalLocation=keys['finalLocation'] urlPath = adjective+timeHash+".png" print "Uploading",path,"as",urlPath,"to",endpoint r = requests.post(endpoint,params={'name':urlPath},files={'file':open(path,'rb')}) print r.status_code if r.status_code==200: print os.path.join(finalLocation,urlPath) os.system("echo '"+os.path.join(finalLocation,urlPath)+"'|pbcopy")
Allow mutiple hooks for packets
packetFunctions = {} commands = {} onStart = [] onConnection = [] onConnectionLoss = [] class packetHook(object): def __init__(self, pktType, pktSubtype): self.pktType = pktType self.pktSubtype = pktSubtype def __call__(self, f): global packetFunctions if (self.pktType, self.pktSubtype) not in packetFunctions: packetFunctions[(self.pktType, self.pktSubtype)] = [] packetFunctions[(self.pktType, self.pktSubtype)].append(f) class commandHook(object): """docstring for commandHook""" def __init__(self, command): self.command = command def __call__(self, f): global commands commands[self.command] = f def onStartHook(f): global onStart onStart.append(f) return f def onConnectionHook(f): global onConnection onConnection.append(f) return f def onConnectionLossHook(f): global onConnectionLoss onConnectionLoss.append(f) return f
packetFunctions = {} commands = {} onStart = [] onConnection = [] onConnectionLoss = [] class packetHook(object): def __init__(self, pktType, pktSubtype): self.pktType = pktType self.pktSubtype = pktSubtype def __call__(self, f): global packetFunctions packetFunctions[(self.pktType, self.pktSubtype)] = f class commandHook(object): """docstring for commandHook""" def __init__(self, command): self.command = command def __call__(self, f): global commands commands[self.command] = f def onStartHook(f): global onStart onStart.append(f) return f def onConnectionHook(f): global onConnection onConnection.append(f) return f def onConnectionLossHook(f): global onConnectionLoss onConnectionLoss.append(f) return f
Fix up indentation and other config fo cppp mode
define(function (require) { 'use strict'; var jquery = require('jquery'); var monaco = require('monaco'); var cpp = require('vs/basic-languages/src/cpp'); // We need to create a new definition for cpp so we can remove invalid keywords function definition() { var cppp = jquery.extend(true, {}, cpp.language); // deep copy function removeKeyword(keyword) { var index = cppp.keywords.indexOf(keyword); if (index > -1) { cppp.keywords.splice(index, 1); } } removeKeyword("array"); removeKeyword("in"); removeKeyword("interface"); return cppp; } monaco.languages.register({id: 'cppp'}); monaco.languages.setLanguageConfiguration('cppp', cpp.conf); monaco.languages.setMonarchTokensProvider('cppp', definition()); });
define(function (require) { 'use strict'; var jquery = require('jquery'); var monaco = require('monaco'); var cpp = require('vs/basic-languages/src/cpp'); // We need to create a new definition for cpp so we can remove invalid keywords function definition() { var cppp = jquery.extend(true, {}, cpp.language); // deep copy function removeKeyword(keyword) { var index = cppp.keywords.indexOf(keyword); if (index > -1) { cppp.keywords.splice(index, 1); } } removeKeyword("array"); removeKeyword("in"); removeKeyword("interface"); return cppp; } monaco.languages.register({id: 'cppp'}); monaco.languages.setMonarchTokensProvider('cppp', definition()); });
Add pos for max_lemma_count also
#!/usr/bin/env python -*- coding: utf-8 -*- # # Python Word Sense Disambiguation (pyWSD): Baseline WSD # # Copyright (C) 2014-2020 alvations # URL: # For license information, see LICENSE.md import random custom_random = random.Random(0) def random_sense(ambiguous_word, pos=None): """ Returns a random sense. """ if pos is None: return custom_random.choice(wn.synsets(ambiguous_word)) else: return custom_random.choice(wn.synsets(ambiguous_word, pos)) def first_sense(ambiguous_word, pos=None): """ Returns the first sense. """ if pos is None: return wn.synsets(ambiguous_word)[0] else: return wn.synsets(ambiguous_word, pos)[0] def max_lemma_count(ambiguous_word, pos=None): """ Returns the sense with the highest lemma_name count. The max_lemma_count() can be treated as a rough gauge for the Most Frequent Sense (MFS), if no other sense annotated corpus is available. NOTE: The lemma counts are from the Brown Corpus """ sense2lemmacounts = {} for i in wn.synsets(ambiguous_word, pos=None): sense2lemmacounts[i] = sum(j.count() for j in i.lemmas()) return max(sense2lemmacounts, key=sense2lemmacounts.get)
#!/usr/bin/env python -*- coding: utf-8 -*- # # Python Word Sense Disambiguation (pyWSD): Baseline WSD # # Copyright (C) 2014-2020 alvations # URL: # For license information, see LICENSE.md import random custom_random = random.Random(0) def random_sense(ambiguous_word, pos=None): """ Returns a random sense. """ if pos is None: return custom_random.choice(wn.synsets(ambiguous_word)) else: return custom_random.choice(wn.synsets(ambiguous_word, pos)) def first_sense(ambiguous_word, pos=None): """ Returns the first sense. """ if pos is None: return wn.synsets(ambiguous_word)[0] else: return wn.synsets(ambiguous_word, pos)[0] def max_lemma_count(ambiguous_word): """ Returns the sense with the highest lemma_name count. The max_lemma_count() can be treated as a rough gauge for the Most Frequent Sense (MFS), if no other sense annotated corpus is available. NOTE: The lemma counts are from the Brown Corpus """ sense2lemmacounts = {} for i in wn.synsets(ambiguous_word): sense2lemmacounts[i] = sum(j.count() for j in i.lemmas()) return max(sense2lemmacounts, key=sense2lemmacounts.get)
Add dependency on six to help support legacy python2
from setuptools import setup, find_packages setup( name='validation', url='https://github.com/JOIVY/validation', version='0.0.1', author='Ben Mather', author_email='bwhmather@bwhmather.com', maintainer='', license='BSD', description=( "A library for runtime type checking and validation of python values" ), long_description=__doc__, classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], install_requires=[ 'six >= 1.10, < 2', ], packages=find_packages(), package_data={ '': ['*.*'], }, entry_points={ 'console_scripts': [ ], }, test_suite='validation.tests.suite', )
from setuptools import setup, find_packages setup( name='validation', url='https://github.com/JOIVY/validation', version='0.0.1', author='Ben Mather', author_email='bwhmather@bwhmather.com', maintainer='', license='BSD', description=( "A library for runtime type checking and validation of python values" ), long_description=__doc__, classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], install_requires=[ ], packages=find_packages(), package_data={ '': ['*.*'], }, entry_points={ 'console_scripts': [ ], }, test_suite='validation.tests.suite', )
Use resolve helper instead of app
<?php /* * This file is part of Flarum. * * For detailed copyright and license information, please view the * LICENSE file that was distributed with this source code. */ use Flarum\Extend; use Flarum\Frontend\Document; use Psr\Http\Message\ServerRequestInterface as Request; return [ (new Extend\Frontend('forum')) ->route( '/embed/{id:\d+(?:-[^/]*)?}[/{near:[^/]*}]', 'embed.discussion', function (Document $document, Request $request) { // Add the discussion content to the document so that the // payload will be included on the page and the JS app will be // able to render the discussion immediately. resolve(Flarum\Forum\Content\Discussion::class)($document, $request); resolve(Flarum\Frontend\Content\Assets::class)->forFrontend('embed')($document, $request); } ), (new Extend\Frontend('embed')) ->js(__DIR__.'/js/dist/forum.js') ->css(__DIR__.'/less/forum.less') ];
<?php /* * This file is part of Flarum. * * For detailed copyright and license information, please view the * LICENSE file that was distributed with this source code. */ use Flarum\Extend; use Flarum\Frontend\Document; use Psr\Http\Message\ServerRequestInterface as Request; return [ (new Extend\Frontend('forum')) ->route( '/embed/{id:\d+(?:-[^/]*)?}[/{near:[^/]*}]', 'embed.discussion', function (Document $document, Request $request) { // Add the discussion content to the document so that the // payload will be included on the page and the JS app will be // able to render the discussion immediately. app(Flarum\Forum\Content\Discussion::class)($document, $request); app(Flarum\Frontend\Content\Assets::class)->forFrontend('embed')($document, $request); } ), (new Extend\Frontend('embed')) ->js(__DIR__.'/js/dist/forum.js') ->css(__DIR__.'/less/forum.less') ];
Simplify location chooser target route logic
import locations from '../core/locations'; import View from '../base/view'; import {trigger} from '../utils/browser'; import template from '../../templates/location-chooser.ejs'; export default class LocationChooser extends View { constructor({app, location, route}) { super({app}); this.location = location; this.route = route; } getHTML() { const currentLocation = this.location; const targetRoute = this.getTargetRoute(); return this.app.renderTemplate(template, { locations, targetRoute, currentLocation}); } mount() { this.events.bind('change', 'onChange'); } getTargetRoute() { if (['place-list', 'event-list'].includes(this.route.name)) { return this.route; } else { return {name: 'event-list', args: {}}; } } onChange(event) { trigger(window, 'navigate', this.element.value); } }
import locations from '../core/locations'; import View from '../base/view'; import {trigger} from '../utils/browser'; import template from '../../templates/location-chooser.ejs'; export default class LocationChooser extends View { constructor({app, location, route}) { super({app}); this.location = location; this.route = route; } getHTML() { const currentLocation = this.location; const targetRoute = this.getTargetRoute(); return this.app.renderTemplate(template, { locations, targetRoute, currentLocation}); } mount() { this.events.bind('change', 'onChange'); } getTargetRoute() { if (this.route.name == 'place-list') { return {name: 'place-list', args: this.route.args}; } else if (this.route.name == 'event-list') { return {name: 'event-list', args: this.route.args}; } else { return {name: 'event-list', args: {}}; } } onChange(event) { trigger(window, 'navigate', this.element.value); } }
Modify prop generation to encompass the whole chunk instead of each of the 16x16 blocks.
/* * Trident - A Multithreaded Server Alternative * Copyright 2016 The TridentSDK Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.tridentsdk.world.gen; /** * This class generates props in the world such as trees, * flowers, tall grass, etc... * * @author TridentSDK * @since 0.5-alpha */ public interface PropGenerator { /** * A prop generator is implemented by overriding this * method and writing the generated blocks to the * context. * * @param chunkX the chunk x * @param chunkZ the chunk z * @param height the highest block at the X/Z * @param context the context */ void generate(int chunkX, int chunkZ, int height, GeneratorContext context); }
/* * Trident - A Multithreaded Server Alternative * Copyright 2016 The TridentSDK Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.tridentsdk.world.gen; /** * This class generates props in the world such as trees, * flowers, tall grass, etc... * * @author TridentSDK * @since 0.5-alpha */ public interface PropGenerator { /** * A prop generator is implemented by overriding this * method and writing the generated blocks to the * context. * * <p>This method is called for each of the horizontal * 16 blocks in a chunk, with the height representing * the highest block at the relative X/Z coordinates. * </p> * * @param relX the relative x * @param relZ the relative z * @param height the highest block at the X/Z * @param context the context */ void generate(int relX, int relZ, int height, GeneratorContext context); }
Print command usage on errors
package forager.newui; import java.util.HashMap; import java.util.Map; public class Launcher { public static void main(String[] args) throws Exception { if (args.length < 1) { printHelp(); } Client clientCommand = new Client(); Map<String, Command> commands = new HashMap<>(); commands.put(clientCommand.name(), clientCommand); String commandName = args[0].toLowerCase(); Command cmd = commands.get(commandName); if (cmd != null) { String[] argList = new String[args.length - 1]; for (int i = 0; i < argList.length; ++i) { argList[i] = args[i + 1]; } try { cmd.execute(argList); } catch (Exception e) { System.out.println(e.getMessage()); cmd.printUsage(); } } } private static void printHelp() { System.out.println("usage: ..."); } }
package forager.newui; import java.util.HashMap; import java.util.Map; public class Launcher { public static void main(String[] args) throws Exception { if (args.length < 1) { printHelp(); } Client clientCommand = new Client(); Map<String, Command> commands = new HashMap<>(); commands.put(clientCommand.name(), clientCommand); String commandName = args[0].toLowerCase(); Command cmd = commands.get(commandName); if (cmd != null) { String[] argList = new String[args.length - 1]; for (int i = 0; i < argList.length; ++i) { argList[i] = args[i + 1]; } cmd.execute(argList); } } private static void printHelp() { System.out.println("usage: ..."); } }
Add Growth Push tracking code to sample
package com.growthbeat.growthbeatsample; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import com.growthbeat.Growthbeat; import com.growthpush.GrowthPush; import com.growthpush.model.Environment; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Growthbeat.getInstance().initialize(this.getApplicationContext(), "dy6VlRMnN3juhW9L", "NuvkVhQtRDG2nrNeDzHXzZO5c6j0Xu5t"); Growthbeat.getInstance().initializeGrowthPush(BuildConfig.DEBUG ? Environment.development : Environment.production, "955057365401"); Growthbeat.getInstance().initializeGrowthReplay(); GrowthPush.getInstance().setDeviceTags(); GrowthPush.getInstance().trackEvent("Launch"); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } }
package com.growthbeat.growthbeatsample; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import com.growthbeat.Growthbeat; import com.growthpush.model.Environment; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Growthbeat.getInstance().initialize(this.getApplicationContext(), "dy6VlRMnN3juhW9L", "NuvkVhQtRDG2nrNeDzHXzZO5c6j0Xu5t"); Growthbeat.getInstance().initializeGrowthPush(BuildConfig.DEBUG ? Environment.development : Environment.production, "955057365401"); Growthbeat.getInstance().initializeGrowthReplay(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } }
Fix order total shipping rules
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Sylius\Component\Core\Shipping\Checker\Rule; use Sylius\Component\Core\Model\ShipmentInterface; use Sylius\Component\Shipping\Checker\Rule\RuleCheckerInterface; use Sylius\Component\Shipping\Model\ShippingSubjectInterface; abstract class OrderTotalRuleChecker implements RuleCheckerInterface { public function isEligible(ShippingSubjectInterface $subject, array $configuration): bool { if (!$subject instanceof ShipmentInterface) { return false; } $order = $subject->getOrder(); if (null === $order) { return false; } $channel = $order->getChannel(); if (null === $channel) { return false; } $amount = $configuration[$channel->getCode()]['amount'] ?? null; if (null === $amount) { return false; } return $this->compare($order->getTotal(), $amount); } abstract protected function compare(int $total, int $threshold): bool; }
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Sylius\Component\Core\Shipping\Checker\Rule; use Sylius\Component\Core\Model\ShipmentInterface; use Sylius\Component\Shipping\Checker\Rule\RuleCheckerInterface; use Sylius\Component\Shipping\Model\ShippingSubjectInterface; abstract class OrderTotalRuleChecker implements RuleCheckerInterface { public function isEligible(ShippingSubjectInterface $subject, array $configuration): bool { if (!$subject instanceof ShipmentInterface) { return false; } $order = $subject->getOrder(); if (null === $order) { return false; } $channel = $order->getChannel(); if (null === $channel) { return false; } $amount = $configuration['total'][$channel->getCode()]['amount'] ?? null; if (null === $amount) { return false; } return $this->compare($order->getTotal(), $amount); } abstract protected function compare(int $total, int $threshold): bool; }
Update to the v3 api
#!/usr/bin/python3 import requests import pprint import argparse parser = argparse.ArgumentParser(description='A tool to check if your email account has been in a breach By Jay Townsend') parser.add_argument('-e', '--email-account', help='Email account to lookup', required=True) parser.add_argument('-k', '--api-key', help='Your HIBP API key', required=True) args = parser.parse_args() headers = {'User-agent': 'Have I been pwn module', f'hibp-api-key': {args.api_key}} API = f'https://haveibeenpwned.com/api/v3/breachedaccount/{args.email_account}' request = requests.get(API, headers=headers) if request.status_code == 404: print('Cannot find your account') else: entries = request.json() for entry in entries: print('Domain:', entry['Domain']) print('DateAdded:', entry['AddedDate']) print('BreachDate:', entry['BreachDate']) pprint.pprint(entry['Description']) print('IsSensitive:', entry['IsSensitive']) print('IsVerified:', entry['IsVerified']) print('PwnCount:', entry['PwnCount'])
#!/usr/bin/python3 import requests import pprint import argparse parser = argparse.ArgumentParser(description='A tool to check if your email account has been in a breach By Jay Townsend') parser.add_argument('-e', '--email-account', help='Email account to lookup', required=True) args = parser.parse_args() headers = {'User-agent': 'Have I been pwn module'} API = 'https://haveibeenpwned.com/api/v2/breachedaccount/{0}'.format(args.email_account) request = requests.get(API, headers=headers) if request.status_code == 404: print('Cannot find your account') else: entries = request.json() for entry in entries: print('Domain:', entry['Domain']) print('DateAdded:', entry['AddedDate']) print('BreachDate:', entry['BreachDate']) pprint.pprint(entry['Description']) print('IsSensitive:', entry['IsSensitive']) print('IsVerified:', entry['IsVerified']) print('PwnCount:', entry['PwnCount'])
Print parsed args, useful for demo.
#!/usr/bin/env python """ Usage: tig init tig commit <msg> tig checkout <start-point> [-b <branch-name>] tig diff tig log tig branch tig merge <branch> Options: -b <branch-name> Branch name to checkout. """ import docopt def init(): pass def branch(): pass def commit(msg): pass def checkout(start_point, new_branch): pass def diff(): pass def log(): pass def merge(branch): pass def main(): args = docopt.docopt(__doc__) print args if args["commit"]: commit(args["<msg>"]) elif args["checkout"]: checkout(args["<start-point>"], args["-b"]) elif args["init"]: init() elif args["diff"]: diff() elif args["log"]: log() elif args["branch"]: branch() elif args["merge"]: merge(args["<branch>"]) else: # Not reached pass if __name__ == "__main__": main()
#!/usr/bin/env python """ Usage: tig init tig commit <msg> tig checkout <start-point> [-b <branch-name>] tig diff tig log tig branch tig merge <branch> Options: -b <branch-name> Branch name to checkout. """ import docopt def init(): pass def branch(): pass def commit(msg): pass def checkout(start_point, new_branch): pass def diff(): pass def log(): pass def merge(branch): pass def main(): args = docopt.docopt(__doc__) if args["commit"]: commit(args["<msg>"]) elif args["checkout"]: checkout(args["<start-point>"], args["-b"]) elif args["init"]: init() elif args["diff"]: diff() elif args["log"]: log() elif args["branch"]: branch() elif args["merge"]: merge(args["<branch>"]) else: # Not reached pass if __name__ == "__main__": main()
Add djangorestframework DefaultRouter instance and registered BondViewSet.
"""bond_analytics_project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import patterns, include, url from django.contrib import admin from rest_framework import routers from views import BondViewSet admin.autodiscover() router = routers.DefaultRouter() router.register(r'bond', BondViewSet) urlpatterns = patterns( '', url(regex='^', view=include(router.urls)), url(regex='^admin/', view=admin.site.urls), )
"""bond_analytics_project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url from django.contrib import admin admin.autodiscover() urlpatterns = [ url(regex='^admin/', view=admin.site.urls), ]
Clarify the code a bit
module.exports = function stringReplaceAsync( string, searchValue, replaceValue ) { try { if (typeof replaceValue === "function") { // 1. Run fake pass of `replace`, collect values from `replaceValue` calls // 2. Resolve them with `Promise.all` // 3. Run `replace` with resolved values var values = []; String.prototype.replace.call(string, searchValue, function () { values.push(replaceValue.apply(undefined, arguments)); return ""; }); return Promise.all(values).then(function (resolvedValues) { return String.prototype.replace.call(string, searchValue, function () { return resolvedValues.shift(); }); }); } else { return Promise.resolve( String.prototype.replace.call(string, searchValue, replaceValue) ); } } catch (error) { return Promise.reject(error); } };
module.exports = function stringReplaceAsync( string, searchValue, replaceValue ) { try { if (typeof replaceValue === "function") { // Step 1: Call native `replace` one time to acquire arguments for // `replaceValue` function // Step 2: Collect all return values in an array // Step 3: Run `Promise.all` on collected values to resolve them // Step 4: Call native `replace` the second time, replacing substrings // with resolved values in order of occurance! var promises = []; String.prototype.replace.call(string, searchValue, function () { promises.push(replaceValue.apply(undefined, arguments)); return ""; }); return Promise.all(promises).then(function (values) { return String.prototype.replace.call(string, searchValue, function () { return values.shift(); }); }); } else { return Promise.resolve( String.prototype.replace.call(string, searchValue, replaceValue) ); } } catch (error) { return Promise.reject(error); } };