text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix case of file path It is impossible to build/install this on Linux with this path broken because all file systems are case sensitive. I'll assume this only slipped by because it was only ever tested on Windows or another case insensitive filesystem.
import re from setuptools import setup _versionRE = re.compile(r'__version__\s*=\s*\"([^\"]+)\"') # read the version number for the settings file with open('Lib/glyphConstruction.py', "r") as settings: code = settings.read() found = _versionRE.search(code) assert found is not None, "glyphConstruction __version__ not found" __version__ = found.group(1) setup( name='glyphConstruction', version=__version__, author='Frederik Berlaen', author_email='frederik@typemytpye.com', url='https://github.com/typemytype/GlyphConstruction', license='LICENSE.txt', description='Letter shape description language', long_description='Letter shape description language', install_requires=[], py_modules=["glyphConstruction"], package_dir={'': 'Lib'} )
import re from setuptools import setup _versionRE = re.compile(r'__version__\s*=\s*\"([^\"]+)\"') # read the version number for the settings file with open('lib/glyphConstruction.py', "r") as settings: code = settings.read() found = _versionRE.search(code) assert found is not None, "glyphConstruction __version__ not found" __version__ = found.group(1) setup( name='glyphConstruction', version=__version__, author='Frederik Berlaen', author_email='frederik@typemytpye.com', url='https://github.com/typemytype/GlyphConstruction', license='LICENSE.txt', description='Letter shape description language', long_description='Letter shape description language', install_requires=[], py_modules=["glyphConstruction"], package_dir={'': 'Lib'} )
Fix links assignment on some AJAX requests
import axios from 'axios' let links export default async function AJAX({ url, resource, id, method = 'GET', data = {}, params = {}, headers = {}, }) { try { const basepath = window.basepath || '' let response url = `${basepath}${url}` if (!links) { const linksRes = (response = await axios({ url: `${basepath}/chronograf/v1`, method: 'GET', })) links = linksRes.data } if (resource) { url = id ? `${basepath}${links[resource]}/${id}` : `${basepath}${links[resource]}` } response = await axios({ url, method, data, params, headers, }) const {auth} = links return { ...response, auth: {links: auth}, } } catch (error) { const {response} = error const {auth} = links throw {...response, auth: {links: auth}} // eslint-disable-line no-throw-literal } }
import axios from 'axios' let links export default async function AJAX({ url, resource, id, method = 'GET', data = {}, params = {}, headers = {}, }) { try { const basepath = window.basepath || '' let response url = `${basepath}${url}` if (!links) { const linksRes = (response = await axios({ url: `${basepath}/chronograf/v1`, method: 'GET', })) links = linksRes.data } const {auth} = links if (resource) { url = id ? `${basepath}${links[resource]}/${id}` : `${basepath}${links[resource]}` } response = await axios({ url, method, data, params, headers, }) return { auth, ...response, } } catch (error) { const {response} = error const {auth} = links throw {...response, auth: {links: auth}} // eslint-disable-line no-throw-literal } }
Add the attributes that must be excluded from the JSON
<?php namespace Begin; use Illuminate\Auth\Authenticatable; use Illuminate\Database\Eloquent\Model; use Illuminate\Auth\Passwords\CanResetPassword; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract; class User extends Model implements AuthenticatableContract, CanResetPasswordContract { use Authenticatable, CanResetPassword; /** * The database table used by the model. * * @var string */ protected $table = 'users'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = ['name', 'email', 'password']; /** * The attributes excluded from the model's JSON form. * * @var array */ protected $hidden = ['password', 'remember_token']; }
<?php namespace Begin; use Illuminate\Auth\Authenticatable; use Illuminate\Database\Eloquent\Model; use Illuminate\Auth\Passwords\CanResetPassword; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract; class User extends Model implements AuthenticatableContract, CanResetPasswordContract { use Authenticatable, CanResetPassword; /** * The database table used by the model. * * @var string */ protected $table = 'users'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = ['name', 'email', 'password']; }
Fix return messages to be limited
/* globals module Promise */ 'use strict'; module.exports = function ({ models }) { const { Message } = models; return { createMessage(message) { let messageModel = Message.getMessage(message); return new Promise((resolve, reject) => { messageModel.save(err => { if (err) { return reject(err); } return resolve(messageModel); }); }); }, getLast100Messages() { return new Promise((resolve, reject) => { Message.find((err, messages) => { if (err) { return reject(err); } return resolve(messages); }).limit(100); }); } }; };
/* globals module Promise */ 'use strict'; module.exports = function ({ models }) { const { Message } = models; return { createMessage(message) { let messageModel = Message.getMessage(message); return new Promise((resolve, reject) => { messageModel.save(err => { if (err) { return reject(err); } return resolve(messageModel); }); }); }, getLast100Messages() { return new Promise((resolve, reject) => { Message.find((err, messages) => { if (err) { return reject(err); } return resolve(messages); }); }); } }; };
Change password hasher for tests for faster tests
from seed_stage_based_messaging.settings import * # flake8: noqa # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'TESTSEKRET' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True CELERY_EAGER_PROPAGATES_EXCEPTIONS = True CELERY_ALWAYS_EAGER = True BROKER_BACKEND = 'memory' CELERY_RESULT_BACKEND = 'djcelery.backends.database:DatabaseBackend' SCHEDULER_URL = "http://seed-scheduler/api/v1" SCHEDULER_API_TOKEN = "REPLACEME" IDENTITY_STORE_URL = "http://seed-identity-store/api/v1" IDENTITY_STORE_TOKEN = "REPLACEME" MESSAGE_SENDER_URL = "http://seed-message-sender/api/v1" MESSAGE_SENDER_TOKEN = "REPLACEME" METRICS_URL = "http://metrics-url" METRICS_AUTH_TOKEN = "REPLACEME" PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',)
from seed_stage_based_messaging.settings import * # flake8: noqa # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'TESTSEKRET' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True CELERY_EAGER_PROPAGATES_EXCEPTIONS = True CELERY_ALWAYS_EAGER = True BROKER_BACKEND = 'memory' CELERY_RESULT_BACKEND = 'djcelery.backends.database:DatabaseBackend' SCHEDULER_URL = "http://seed-scheduler/api/v1" SCHEDULER_API_TOKEN = "REPLACEME" IDENTITY_STORE_URL = "http://seed-identity-store/api/v1" IDENTITY_STORE_TOKEN = "REPLACEME" MESSAGE_SENDER_URL = "http://seed-message-sender/api/v1" MESSAGE_SENDER_TOKEN = "REPLACEME" METRICS_URL = "http://metrics-url" METRICS_AUTH_TOKEN = "REPLACEME"
Add .clear() method to Keyv
'use strict'; class Keyv { constructor(opts) { this.opts = opts || {}; this.opts.store = this.opts.store || new Map(); } get(key) { const store = this.opts.store; return Promise.resolve(store.get(key)).then(data => { if (data === undefined) { return undefined; } if (!store.ttlSupport && Date.now() > data.expires) { this.delete(key); return undefined; } return store.ttlSupport ? data : data.value; }); } set(key, value, ttl) { ttl = ttl || this.opts.ttl; const store = this.opts.store; let set; if (store.ttlSupport) { set = store.set(key, value, ttl); } else { const expires = (typeof ttl === 'number') ? (Date.now() + ttl) : undefined; const data = { value, expires }; set = store.set(key, data); } return Promise.resolve(set).then(() => value); } delete(key) { const store = this.opts.store; return Promise.resolve(store.delete(key)); } clear() { const store = this.opts.store; return Promise.resolve(store.clear()); } } module.exports = Keyv;
'use strict'; class Keyv { constructor(opts) { this.opts = opts || {}; this.opts.store = this.opts.store || new Map(); } get(key) { const store = this.opts.store; return Promise.resolve(store.get(key)).then(data => { if (data === undefined) { return undefined; } if (!store.ttlSupport && Date.now() > data.expires) { this.delete(key); return undefined; } return store.ttlSupport ? data : data.value; }); } set(key, value, ttl) { ttl = ttl || this.opts.ttl; const store = this.opts.store; let set; if (store.ttlSupport) { set = store.set(key, value, ttl); } else { const expires = (typeof ttl === 'number') ? (Date.now() + ttl) : undefined; const data = { value, expires }; set = store.set(key, data); } return Promise.resolve(set).then(() => value); } delete(key) { const store = this.opts.store; return Promise.resolve(store.delete(key)); } } module.exports = Keyv;
Fix an issue where reported threads had incomplete urls
'use strict'; const r = require('../services/reddit'); let reportedItemNames = new Set(); let hasFinishedFirstRun = false; const SUBREDDITS = ['pokemontrades', 'SVExchange']; module.exports = { period: 60, onStart: true, task () { return r.get_subreddit(SUBREDDITS.join('+')).get_reports({limit: 25}).then(items => { // Don't output the new reports on the first fetch, as that would cause old reports to be listed. // Unfortunately, there is no way to tell whether reports on an item have been ignored using the OAuth API. const newItemsToReport = hasFinishedFirstRun ? items.filter(item => !reportedItemNames.has(item.name)) : []; items.forEach(item => reportedItemNames.add(item.name)); hasFinishedFirstRun = true; return newItemsToReport.map(formatItem); }); } }; function formatItem (item) { const permalink = item.constructor.name === 'Comment' ? item.link_url + item.id : item.url; return `[NEW REPORTED ITEM] ${item.constructor.name} by /u/${item.author.name}: ${permalink}`; }
'use strict'; const r = require('../services/reddit'); let reportedItemNames = new Set(); let hasFinishedFirstRun = false; const SUBREDDITS = ['pokemontrades', 'SVExchange']; module.exports = { period: 60, onStart: true, task () { return r.get_subreddit(SUBREDDITS.join('+')).get_reports({limit: 25}).then(items => { // Don't output the new reports on the first fetch, as that would cause old reports to be listed. // Unfortunately, there is no way to tell whether reports on an item have been ignored using the OAuth API. const newItemsToReport = hasFinishedFirstRun ? items.filter(item => !reportedItemNames.has(item.name)) : []; items.forEach(item => reportedItemNames.add(item.name)); hasFinishedFirstRun = true; return newItemsToReport.map(formatItem); }); } }; function formatItem (item) { const permalink = item.constructor.name === 'Comment' ? item.link_url + item.id : item.permalink; return `[NEW REPORTED ITEM] ${item.constructor.name} by /u/${item.author.name}: ${permalink}`; }
Make use of the common stack
package main import ( "fmt" "github.com/ant0ine/go-json-rest/rest" "log" "net/http" "time" ) func main() { router, err := rest.MakeRouter( &rest.Route{"GET", "/stream", StreamThings}, ) if err != nil { log.Fatal(err) } api := rest.NewApi(router) api.Use(&rest.AccessLogApacheMiddleware{}) api.Use(rest.DefaultCommonStack...) log.Fatal(http.ListenAndServe(":8080", api.MakeHandler())) } type Thing struct { Name string } func StreamThings(w rest.ResponseWriter, r *rest.Request) { cpt := 0 for { cpt++ w.WriteJson( &Thing{ Name: fmt.Sprintf("thing #%d", cpt), }, ) w.(http.ResponseWriter).Write([]byte("\n")) // Flush the buffer to client w.(http.Flusher).Flush() // wait 3 seconds time.Sleep(time.Duration(3) * time.Second) } }
package main import ( "fmt" "github.com/ant0ine/go-json-rest/rest" "log" "net/http" "time" ) func main() { router, err := rest.MakeRouter( &rest.Route{"GET", "/stream", StreamThings}, ) if err != nil { log.Fatal(err) } api := rest.NewApi(router) api.Use(&rest.AccessLogApacheMiddleware{}) api.Use(&rest.TimerMiddleware{}) api.Use(&rest.RecorderMiddleware{}) api.Use(&rest.RecoverMiddleware{}) log.Fatal(http.ListenAndServe(":8080", api.MakeHandler())) } type Thing struct { Name string } func StreamThings(w rest.ResponseWriter, r *rest.Request) { cpt := 0 for { cpt++ w.WriteJson( &Thing{ Name: fmt.Sprintf("thing #%d", cpt), }, ) w.(http.ResponseWriter).Write([]byte("\n")) // Flush the buffer to client w.(http.Flusher).Flush() // wait 3 seconds time.Sleep(time.Duration(3) * time.Second) } }
Remove compatibility detection, and refactor listeners to avoid unnecessary calls
var through = require('through2') function ChromeRuntimeStream(port) { var connected = true var stream = through.obj(function (msg, enc, next) { if (connected) { port.postMessage(msg) } next() }, function flush(done) { if (connected) { removeListeners() connected = false port.disconnect() } done() }) addListeners() function onMessage(msg) { stream.push(msg) } function onDisconnect() { removeListeners() connected = false stream.end() } function addListeners() { port.onMessage.addListener(onMessage) port.onDisconnect.addListener(onDisconnect) } function removeListeners() { port.onMessage.removeListener(onMessage) port.onDisconnect.removeListener(onDisconnect) } return stream } module.exports = ChromeRuntimeStream
var through = require('through2') function ChromeRuntimeStream(port) { var stream = through.obj(function (msg, enc, next) { port.postMessage(msg) next() }, function (done) { port.disconnect() done() }) port.onMessage.addListener(function (msg) { stream.push(msg) }) port.onDisconnect.addListener(function () { stream.end() }) return stream } module.exports = ChromeRuntimeStream module.exports.detectCompatibility = function (callback) { if (!chrome) { callback && callback(new Error('Chrome browser not detected.')) return false } else if (!chrome.runtime) { callback && callback(new Error('Chrome runtime not detected.')) return false } else if (!typeof chrome.runtime.connect === 'function') { callback && callback(new Error('Chrome version 26 or higher not detected.')) return false } else { callback && callback(null) return true } }
Fix potential ReferenceError in non-browser env Testing for `window` would throw if undeclared. Also, avoid repeating feature check.
define(['globals'], function(globals) { 'use strict'; // Wrap logging so it can be pushed to log in prod, and used safely on old browsers var opts = ['log', 'info', 'warn', 'error'], l = opts.length, logs = {}, logged = [], useConsole = typeof window !== 'undefined' && window.console && globals.bootstrap.env && typeof Function.prototype.bind === 'function' && globals.bootstrap.env === 'development'; function logIt(name, options) { logged.push([name, options, type]); } while (l--) { var type = l; logs[opts[l]] = useConsole ? console[opts[l]].bind(console) : logIt; } if (typeof window !== 'undefined') window.logged = logged; return logs; });
define(['globals'], function(globals) { 'use strict'; // Wrap logging so it can be pushed to log in prod, and used safely on old browsers var opts = ['log', 'info', 'warn', 'error'], l = opts.length, logs = {}, logged = []; function logIt(name, options) { logged.push([name, options, type]); } while (l--) { var type = l; logs[opts[l]] = (window && window.console && globals.bootstrap.env && globals.bootstrap.env === 'development') ? console[opts[l]].bind && console[opts[l]].bind(console) : logIt; } if (window) window.logged = logged; return logs; });
FIX Handle edge case where controller does not have a url_segment defined
<?php namespace SilverStripe\ShareDraftContent\Extensions; use SilverStripe\Core\Extension; use SilverStripe\Security\Security; class ShareDraftContentControllerExtension extends Extension { /** * @var array */ private static $allowed_actions = array( 'MakeShareDraftLink', ); /** * @return mixed */ public function MakeShareDraftLink() { if ($member = Security::getCurrentUser()) { if ($this->owner->hasMethod('CurrentPage') && $this->owner->CurrentPage()->canEdit($member)) { return $this->owner->CurrentPage()->ShareTokenLink(); } elseif ($this->owner->hasMethod('canEdit') && $this->owner->canEdit($member)) { return $this->owner->ShareTokenLink(); } } return Security::permissionFailure(); } /** * @return string */ public function getShareDraftLinkAction() { if ($this->owner->config()->get('url_segment')) { return $this->owner->Link('MakeShareDraftLink'); } return ''; } }
<?php namespace SilverStripe\ShareDraftContent\Extensions; use SilverStripe\Core\Extension; use SilverStripe\Security\Member; use SilverStripe\Security\Security; class ShareDraftContentControllerExtension extends Extension { /** * @var array */ private static $allowed_actions = array( 'MakeShareDraftLink', ); /** * @return mixed */ public function MakeShareDraftLink() { if ($member = Member::currentUser()) { if ($this->owner->hasMethod('CurrentPage') && $this->owner->CurrentPage()->canEdit($member)) { return $this->owner->CurrentPage()->ShareTokenLink(); } elseif ($this->owner->hasMethod('canEdit') && $this->owner->canEdit($member)) { return $this->owner->ShareTokenLink(); } } return Security::permissionFailure(); } /** * @return string */ public function getShareDraftLinkAction() { return $this->owner->Link('MakeShareDraftLink'); } }
Add test for Spotify show type (podcast)
<?php /** * SpotifyTest.php * * @package Embera * @author Michael Pratt <yo@michael-pratt.com> * @link http://www.michael-pratt.com/ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Embera\Provider; use Embera\ProviderTester; /** * Test the Spotify Provider */ final class SpotifyTest extends ProviderTester { protected $tasks = [ 'valid_urls' => [ 'https://open.spotify.com/album/4FCuyUjOkT28PnFo6A6vkf/4K4sc36DCTp9YJNVu5zV09', 'https://open.spotify.com/track/0Wm3w3YiMe7YiS8erpKbOl', 'https://open.spotify.com/show/3wBfqov60qDZbEVjPHo0a8?si=2ee16a763fd44148', ], 'invalid_urls' => [ 'https://open.spotify.com/stuff/3zIzQMHvOlw3ukDhRKR2jO', ], ]; public function testProvider() { $this->validateProvider('Spotify', [ 'width' => 480, 'height' => 270]); } }
<?php /** * SpotifyTest.php * * @package Embera * @author Michael Pratt <yo@michael-pratt.com> * @link http://www.michael-pratt.com/ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Embera\Provider; use Embera\ProviderTester; /** * Test the Spotify Provider */ final class SpotifyTest extends ProviderTester { protected $tasks = [ 'valid_urls' => [ 'https://open.spotify.com/album/4FCuyUjOkT28PnFo6A6vkf/4K4sc36DCTp9YJNVu5zV09', 'https://open.spotify.com/track/0Wm3w3YiMe7YiS8erpKbOl', ], 'invalid_urls' => [ 'https://open.spotify.com/stuff/3zIzQMHvOlw3ukDhRKR2jO', ], ]; public function testProvider() { $this->validateProvider('Spotify', [ 'width' => 480, 'height' => 270]); } }
Set a custom JSON Encoder to serialize date class.
import datetime import flask import json from apscheduler.job import Job from .utils import job_to_dict loads = json.loads def dumps(obj, indent=None): return json.dumps(obj, indent=indent, cls=JSONEncoder) def jsonify(data, status=None): indent = None if flask.current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] and not flask.request.is_xhr: indent = 2 return flask.current_app.response_class(dumps(data, indent=indent), status=status, mimetype='application/json') class JSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime.datetime): return obj.isoformat() if isinstance(obj, datetime.date): return obj.isoformat() if isinstance(obj, Job): return job_to_dict(obj) return super(JSONEncoder, self).default(obj)
import flask import json from datetime import datetime from apscheduler.job import Job from .utils import job_to_dict class JSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime): return obj.isoformat() if isinstance(obj, Job): return job_to_dict(obj) return super(JSONEncoder, self).default(obj) def dumps(obj, indent=None): return json.dumps(obj, indent=indent, cls=JSONEncoder) def jsonify(data, status=None): indent = None if flask.current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] and not flask.request.is_xhr: indent = 2 return flask.current_app.response_class(dumps(data, indent=indent), status=status, mimetype='application/json')
OAK-15: Clean up oak-jcr - formatting git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1301494 13f79535-47bb-0310-9956-ffa450edef68
package org.apache.jackrabbit.oak.jcr.state; import org.apache.jackrabbit.oak.jcr.json.JsonValue; import org.apache.jackrabbit.oak.model.AbstractPropertyState; public class PropertyStateImpl extends AbstractPropertyState { private final String name; private final JsonValue value; public PropertyStateImpl(String name, JsonValue value) { this.name = name; this.value = value; } public JsonValue getValue() { return value; } @Override public String getName() { return name; } @Override public String getEncodedValue() { return value.toJson(); } @Override public String toString() { return name + ':' + getEncodedValue(); } }
package org.apache.jackrabbit.oak.jcr.state; import org.apache.jackrabbit.oak.jcr.json.JsonValue; import org.apache.jackrabbit.oak.model.AbstractPropertyState; public class PropertyStateImpl extends AbstractPropertyState { private final String name; private final JsonValue value; public PropertyStateImpl(String name, JsonValue value) { this.name = name; this.value = value; } public JsonValue getValue() { return value; } @Override public String getName() { return name; } @Override public String getEncodedValue() { return value.toJson(); } @Override public String toString() { return name + ':' + getEncodedValue(); } }
Fix link to Slowvote user guide Summary: This URI is incorrect. Test Plan: Clicked "Help" tab. Reviewers: cpiro Reviewed By: cpiro CC: aran, cpiro Differential Revision: 1026
<?php /* * Copyright 2011 Facebook, 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. */ /** * @group slowvote */ abstract class PhabricatorSlowvoteController extends PhabricatorController { public function buildStandardPageResponse($view, array $data) { $page = $this->buildStandardPageView(); $page->setApplicationName('Slowvote'); $page->setBaseURI('/vote/'); $page->setTitle(idx($data, 'title')); $page->setGlyph("\xE2\x9C\x94"); $doc_href = PhabricatorEnv::getDoclink('article/Slowvote_User_Guide.html'); $page->setTabs( array( 'help' => array( 'name' => 'Help', 'href' => $doc_href, ), ), null); $page->appendChild($view); $response = new AphrontWebpageResponse(); return $response->setContent($page->render()); } }
<?php /* * Copyright 2011 Facebook, 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. */ /** * @group slowvote */ abstract class PhabricatorSlowvoteController extends PhabricatorController { public function buildStandardPageResponse($view, array $data) { $page = $this->buildStandardPageView(); $page->setApplicationName('Slowvote'); $page->setBaseURI('/vote/'); $page->setTitle(idx($data, 'title')); $page->setGlyph("\xE2\x9C\x94"); $doc_href = PhabricatorEnv::getDoclink('articles/Slowvote_User_Guide.html'); $page->setTabs( array( 'help' => array( 'name' => 'Help', 'href' => $doc_href, ), ), null); $page->appendChild($view); $response = new AphrontWebpageResponse(); return $response->setContent($page->render()); } }
Hide user deletion for non-admins.
// Midas Server. Copyright Kitware SAS. Licensed under the Apache License 2.0. $(document).ready(function () { 'use strict'; var hideDownloadsForAnon = function () { if (json.global.logged !== "1") { $('.downloadObject').hide(); } }; // Go to the landing page. $('div.HeaderLogo').unbind('click').click(function () { window.location = json.global.webroot; }); // Remove download links if the user is not logged into the system. hideDownloadsForAnon(); midas.registerCallback('CALLBACK_CORE_RESOURCE_HIGHLIGHTED', 'rsnabranding', hideDownloadsForAnon); // Change upload button to "Request Upload" $('.uploadFile-top') .empty() .unbind() .html("<div style=\"color: white; font-size: 14pt; padding-top: 2px;\">Request Upload</div>") .click(function (evt) { if (evt.originalEvent) { window.location = "https://www.rsna.org/QIDW-Contributor-Request/"; } }); // Hide the users and feed links $('#menuUsers').hide(); $('#menuFeed').hide(); // Hide user deletion for non admins $('#userDeleteActionNonAdmin').hide(); });
// Midas Server. Copyright Kitware SAS. Licensed under the Apache License 2.0. $(document).ready(function () { 'use strict'; var hideDownloadsForAnon = function () { if (json.global.logged !== "1") { $('.downloadObject').hide(); } }; // Go to the landing page. $('div.HeaderLogo').unbind('click').click(function () { window.location = json.global.webroot; }); // Remove download links if the user is not logged into the system. hideDownloadsForAnon(); midas.registerCallback('CALLBACK_CORE_RESOURCE_HIGHLIGHTED', 'rsnabranding', hideDownloadsForAnon); // Change upload button to "Request Upload" $('.uploadFile-top') .empty() .unbind() .html("<div style=\"color: white; font-size: 14pt; padding-top: 2px;\">Request Upload</div>") .click(function (evt) { if (evt.originalEvent) { window.location = "https://www.rsna.org/QIDW-Contributor-Request/"; } }); // Hide the users and feed links $('#menuUsers').hide(); $('#menuFeed').hide(); });
Update datatime control, setting default time
<?php /** * Class wpAPIDateTime * * @package wpAPI\Core\Elements\wpAPIDateTime */ class wpAPIDateTime extends BaseElement { function __construct($id, $label, $permissions=[], $elementPath='') { parent::__construct($id, $label, $permissions, $elementPath); } function ReadView($post) { echo $this->twigTemplate->render('/read_view.mustache', ["value" => $this->GetDatabaseValue($post)]); } function EditView( $post) { parent::EditView($post); $db_dateTime = $this->GetDatabaseValue($post) == null ? date("Y-m-d\TH:i:s", time()) : $this->GetDatabaseValue($post); echo $this->twigTemplate->render('/edit_view.mustache', [ "id" => $this->id, "value" => $db_dateTime ]); } function ProcessPostData($post_id) { parent::ProcessPostData($post_id); $data = sanitize_text_field($_POST[$this->id]); $this->SaveElementData($post_id, $data); } }
<?php /** * Class wpAPIDateTime * * @package wpAPI\Core\Elements\wpAPIDateTime */ class wpAPIDateTime extends BaseElement { function __construct($id, $label, $permissions=[], $elementPath='') { parent::__construct($id, $label, $permissions, $elementPath); } function ReadView($post) { echo $this->twigTemplate->render('/read_view.mustache', ["value" => $this->GetDatabaseValue($post)]); } function EditView( $post) { parent::EditView($post); echo $this->twigTemplate->render('/edit_view.mustache', [ "id" => $this->id, "value" => $this->GetDatabaseValue($post) ]); } function ProcessPostData($post_id) { parent::ProcessPostData($post_id); $data = sanitize_text_field($_POST[$this->id]); $this->SaveElementData($post_id, $data); } }
Refactoring: Replace single quotes -> double quotes
module.exports = [ { test: /\.ts(x?)$/, loader: "ts-loader" }, { test: /\.css$/, loader: "style-loader!css-loader" }, { test: /\.scss$/, loader: "style-loader!css-loader!sass-loader" }, { test: /\.html$/, exclude: /node_modules/, loader: "raw-loader" }, { test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url-loader?limit=10000&mimetype=application/font-woff" }, { test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader" }, { test: /\.jpg$/, exclude: /node_modules/, loader: "file-loader" }, { test: /\.png$/, exclude: /node_modules/, loader: "url-loader" } ];
module.exports = [ { test: /\.ts(x?)$/, loader: 'ts-loader' }, { test: /\.css$/, loader: 'style-loader!css-loader' }, { test: /\.scss$/, loader: 'style-loader!css-loader!sass-loader' }, { test: /\.html$/, exclude: /node_modules/, loader: 'raw-loader' }, { test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'url-loader?limit=10000&mimetype=application/font-woff' }, { test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'file-loader' }, { test: /\.jpg$/, exclude: /node_modules/, loader: 'file-loader' }, { test: /\.png$/, exclude: /node_modules/, loader: 'url-loader' } ];
Put my stuff with Eddies stuff
var express = require('express'), app = express(), http = require('http'), socketIo = require('socket.io'); // start webserver on port 8080 var server = http.createServer(app); var io = socketIo.listen(server); server.listen(8080); // add directory with our static files app.use(express.static(__dirname + '/public')); console.log("Server running on 127.0.0.1:8080"); // array of all lines drawn // 2000 x 2000 // characters are 5 x 5 var characterHistory = []; // event-handler for new incoming connections io.on('connection', function (socket) { characterHistory.push({x:((Math.random()*1990)+5),y:((Math.random()*1990)+5)}); socket.emit('init_character', {id:characterHistory.length-1,position:characterHistory[characterHistory.length-1]}); // first send the history to the new client socket.emit('update_characters', characterHistory); // add handler for message type "draw_line". socket.on('move_character', function (data) { // add received line to history characterHistory[data.id]=data.position // send line to all clients io.emit('update_characters', characterHistory); }); });
var express = require('express'), app = express(), http = require('http'), socketIo = require('socket.io'); // start webserver on port 8080 var server = http.createServer(app); var io = socketIo.listen(server); server.listen(8080); // add directory with our static files app.use(express.static(__dirname + '/public')); console.log("Server running on 127.0.0.1:8080"); // array of all lines drawn var line_history = []; // event-handler for new incoming connections io.on('connection', function (socket) { // first send the history to the new client for (var i in line_history) { socket.emit('draw_line', { line: line_history[i] } ); } // add handler for message type "draw_line". socket.on('draw_line', function (data) { // add received line to history line_history.push(data.line); // send line to all clients io.emit('draw_line', { line: data.line }); }); });
Update comment on authToken field
/* * Copyright 2012 GitHub Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.mobile.accounts; /** * GitHub account model */ public class GitHubAccount { /** * Account username */ public final String username; /** * Account password */ public final String password; /** * Account OAuth token */ public final String authToken; /** * Create account with username and password * * @param username * @param password * @param authToken */ public GitHubAccount(String username, String password, String authToken) { this.username = username; this.password = password; this.authToken = authToken; } @Override public String toString() { return getClass().getSimpleName() + '[' + username + ']'; } }
/* * Copyright 2012 GitHub Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.mobile.accounts; /** * GitHub account model */ public class GitHubAccount { /** * Account username */ public final String username; /** * Account password */ public final String password; /** * Account password */ public final String authToken; /** * Create account with username and password * * @param username * @param password * @param authToken */ public GitHubAccount(String username, String password, String authToken) { this.username = username; this.password = password; this.authToken = authToken; } @Override public String toString() { return getClass().getSimpleName() + '[' + username + ']'; } }
Use saveEventually() instead of saveInBackground()
package com.permutassep.presentation.utils; import com.parse.ParseInstallation; /** * By Jorge E. Hernandez (@lalongooo) 2015 */ public class ParseUtils { private static final String PARSE_INSTALLATION_COLUMN_PS_USER = "PSUser"; public static void setUpParseInstallationUser(int userId) { ParseInstallation installation = ParseInstallation.getCurrentInstallation(); installation.put(PARSE_INSTALLATION_COLUMN_PS_USER, userId); installation.saveEventually(); // if (installation.get(PARSE_INSTALLATION_COLUMN_PS_USER) == null // || // Integer.valueOf(installation.get(PARSE_INSTALLATION_COLUMN_PS_USER).toString()) != userId) { // installation.put(PARSE_INSTALLATION_COLUMN_PS_USER, userId); // installation.saveInBackground(); // } } public static void clearParseInstallationUser() { ParseInstallation installation = ParseInstallation.getCurrentInstallation(); installation.put(PARSE_INSTALLATION_COLUMN_PS_USER, -1); installation.saveEventually(); } }
package com.permutassep.presentation.utils; import com.parse.ParseInstallation; /** * By Jorge E. Hernandez (@lalongooo) 2015 */ public class ParseUtils { private static final String PARSE_INSTALLATION_COLUMN_PS_USER = "PSUser"; public static void setUpParseInstallationUser(int userId) { ParseInstallation installation = ParseInstallation.getCurrentInstallation(); if (installation.get(PARSE_INSTALLATION_COLUMN_PS_USER) == null || Integer.valueOf(installation.get(PARSE_INSTALLATION_COLUMN_PS_USER).toString()) != userId) { installation.put(PARSE_INSTALLATION_COLUMN_PS_USER, userId); installation.saveInBackground(); } } public static void clearParseInstallationUser() { ParseInstallation installation = ParseInstallation.getCurrentInstallation(); installation.put(PARSE_INSTALLATION_COLUMN_PS_USER, -1); installation.saveInBackground(); } }
Add username to feedback entries
window.admin = {}; $(document).ready(function() { $("#admin-feedback").on("tabOpened", function() { window.api.get("admin/feedback/getList", function(resp) { $("#admin-feedback-list").text(""); for (var feedbackIndex in resp.feedback) { var feedbackItem = resp.feedback[feedbackIndex]; var $feedbackLi = $('<li></li>'); var $feedbackDesc = $('<div></div>'); $feedbackDesc.text(" #" + feedbackItem.feedbackId + " " + feedbackItem.msg); var $icon = $('<i class="fa"></i>'); if (feedbackItem.type == "smile") { $icon.addClass("fa-smile-o"); } else if (feedbackItem.type == "frown") { $icon.addClass("fa-frown-o"); } else if (feedbackItem.type == "idea") { $icon.addClass("fa-lightbulb-o"); } $feedbackDesc.prepend($icon); $feedbackLi.append($feedbackDesc); var $feedbackName = $('<div></div>'); $feedbackName.text(feedbackItem.name + " (" + feedbackItem.username + ")"); $feedbackLi.append($feedbackName); $("#admin-feedback-list").append($feedbackLi); }; }); }); });
window.admin = {}; $(document).ready(function() { $("#admin-feedback").on("tabOpened", function() { window.api.get("admin/feedback/getList", function(resp) { $("#admin-feedback-list").text(""); for (var feedbackIndex in resp.feedback) { var feedbackItem = resp.feedback[feedbackIndex]; var $feedbackLi = $('<li></li>'); var $feedbackDesc = $('<div></div>'); $feedbackDesc.text(" #" + feedbackItem.feedbackId + " " + feedbackItem.msg); var $icon = $('<i class="fa"></i>'); if (feedbackItem.type == "smile") { $icon.addClass("fa-smile-o"); } else if (feedbackItem.type == "frown") { $icon.addClass("fa-frown-o"); } else if (feedbackItem.type == "idea") { $icon.addClass("fa-lightbulb-o"); } $feedbackDesc.prepend($icon); $feedbackLi.append($feedbackDesc); var $feedbackName = $('<div></div>'); $feedbackName.text(feedbackItem.name); $feedbackLi.append($feedbackName); $("#admin-feedback-list").append($feedbackLi); }; }); }); });
Fix pre-commit issue for the cli_eigenvals test.
#!/usr/bin/env python # -*- coding: utf-8 -*- # (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik # Author: Dominik Gresch <greschd@gmx.ch> """ Tests for the 'eigenvals' command. """ import os import tempfile import numpy as np import bands_inspect as bi from click.testing import CliRunner from tbmodels._cli import cli def test_cli_eigenvals(sample): """ Test the 'eigenvals' command. """ samples_dir = sample('cli_eigenvals') runner = CliRunner() with tempfile.NamedTemporaryFile() as out_file: run = runner.invoke( cli, [ 'eigenvals', '-o', out_file.name, '-k', os.path.join(samples_dir, 'kpoints.hdf5'), '-i', os.path.join(samples_dir, 'silicon_model.hdf5') ], catch_exceptions=False ) print(run.output) res = bi.io.load(out_file.name) reference = bi.io.load(os.path.join(samples_dir, 'silicon_eigenvals.hdf5')) np.testing.assert_allclose(bi.compare.difference.calculate(res, reference), 0, atol=1e-10)
#!/usr/bin/env python # -*- coding: utf-8 -*- # (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik # Author: Dominik Gresch <greschd@gmx.ch> import os import pytest import tempfile import numpy as np import bands_inspect as bi from click.testing import CliRunner import tbmodels from tbmodels._cli import cli def test_cli_eigenvals(sample): samples_dir = sample('cli_eigenvals') runner = CliRunner() with tempfile.NamedTemporaryFile() as out_file: run = runner.invoke( cli, [ 'eigenvals', '-o', out_file.name, '-k', os.path.join(samples_dir, 'kpoints.hdf5'), '-i', os.path.join(samples_dir, 'silicon_model.hdf5') ], catch_exceptions=False ) print(run.output) res = bi.io.load(out_file.name) reference = bi.io.load(os.path.join(samples_dir, 'silicon_eigenvals.hdf5')) np.testing.assert_allclose(bi.compare.difference.calculate(res, reference), 0, atol=1e-10)
Remove unused imports for lint
# -*- coding: utf-8 -*- ''' unittests for yaml outputter ''' # Import Python Libs from __future__ import absolute_import # Import Salt Testing Libs from salttesting import TestCase from salttesting.helpers import ensure_in_syspath ensure_in_syspath('../../') # Import Salt Libs from salt.output import yaml_out as yaml class YamlTestCase(TestCase): ''' Test cases for salt.output.json_out ''' def setUp(self): # reset to default behavior yaml.__opts__ = {} self.data = {'test': 'two', 'example': 'one'} def test_default_output(self): ret = yaml.output(self.data) expect = 'example: one\ntest: two\n' self.assertEqual(expect, ret) def test_negative_int_output(self): yaml.__opts__['output_indent'] = -1 ret = yaml.output(self.data) expect = '{example: one, test: two}\n' self.assertEqual(expect, ret) if __name__ == '__main__': from integration import run_tests run_tests(YamlTestCase, needs_daemon=False)
# -*- coding: utf-8 -*- ''' unittests for yaml outputter ''' # Import Python Libs from __future__ import absolute_import from StringIO import StringIO import sys # Import Salt Testing Libs from salttesting import TestCase from salttesting.helpers import ensure_in_syspath ensure_in_syspath('../../') # Import Salt Libs from salt.output import yaml_out as yaml class YamlTestCase(TestCase): ''' Test cases for salt.output.json_out ''' def setUp(self): # reset to default behavior yaml.__opts__ = {} self.data = {'test': 'two', 'example': 'one'} def test_default_output(self): ret = yaml.output(self.data) expect = 'example: one\ntest: two\n' self.assertEqual(expect, ret) def test_negative_int_output(self): yaml.__opts__['output_indent'] = -1 ret = yaml.output(self.data) expect = '{example: one, test: two}\n' self.assertEqual(expect, ret) if __name__ == '__main__': from integration import run_tests run_tests(YamlTestCase, needs_daemon=False)
Throw error and exit on failure
#!/usr/bin/env node --harmony var program = require('commander'); var fetch = require('node-fetch'); var base64 = require('base-64'); async function fetchArtifactList(uri, username, password) { const response = await fetch(uri, { method: 'get', headers: { 'Authorization': 'Basic ' + base64.encode(username + ':' + password) }, }); const body = await response.json(); if (response.status !== 200) { throw body.errors; } return body; } async function showArtifactList(uri, username, password) { try { const json = await fetchArtifactList(uri, username, password); console.log(json.repo); console.log(json.path); console.log(json.children); process.exit(0); } catch (err) { for (let i = 0; i < err.length; i++) { const error = err[i]; console.error('Error: ' + error.message + ' (' + error.status + ')'); } process.exit(1); } } program .arguments('<uri>') .version('0.0.2') .description('A command line tool to retrieve that URI to the latest artifact from an Artifactory repo') .option('-u, --username <username>', 'The user to authenticate as') .option('-p, --password <password>', 'The user\'s password') .action(uri => { const { username, password } = program; showArtifactList(uri, username, password); }) .parse(process.argv);
#!/usr/bin/env node --harmony var program = require('commander'); var fetch = require('node-fetch'); var base64 = require('base-64'); program .arguments('<uri>') .version('0.0.2') .description('A command line tool to retrieve that URI to the latest artifact from an Artifactory repo') .option('-u, --username <username>', 'The user to authenticate as') .option('-p, --password <password>', 'The user\'s password') .action(function (uri) { const { username, password } = program; console.log('user: %s \npass: %s \nuri: %s', program.username, program.password, uri); fetchArtifactList(uri, username, password) .then(json => { console.log(JSON.stringify(json, null, 2)); }); }) .parse(process.argv); async function fetchArtifactList(uri, username, password) { const response = await fetch(uri, { method: 'get', headers: { 'Authorization': 'Basic ' + base64.encode(username + ':' + password) }, }); return await response.json(); }
Fix accidental removal of WeakReference +review REVIEW-5606
/* * Copyright 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.api.internal.project.antbuilder; import org.gradle.internal.classpath.ClassPath; import java.lang.ref.WeakReference; class CacheEntry extends WeakReference<CachedClassLoader> { private final ClassPath key; CacheEntry(ClassPath key, CachedClassLoader cached) { super(cached); this.key = key; } public ClassPath getKey() { return key; } }
/* * Copyright 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.api.internal.project.antbuilder; import org.gradle.internal.classpath.ClassPath; import java.lang.ref.SoftReference; class CacheEntry extends SoftReference<CachedClassLoader> { private final ClassPath key; CacheEntry(ClassPath key, CachedClassLoader cached) { super(cached); this.key = key; } public ClassPath getKey() { return key; } }
Fix tests for python 3
import re import sh from .base import DjangoCookieTestCase class TestCookiecutterSubstitution(DjangoCookieTestCase): """Test that all cookiecutter instances are substituted""" def test_all_cookiecutter_instances_are_substituted(self): # Build a list containing absolute paths to the generated files paths = self.generate_project() # Construct the cookiecutter search pattern pattern = "{{(\s?cookiecutter)[.](.*?)}}" re_obj = re.compile(pattern) # Assert that no match is found in any of the files for path in paths: for line in open(path, 'r', encoding='utf-8', errors='ignore'): match = re_obj.search(line) self.assertIsNone( match, "cookiecutter variable not replaced in {}".format(path)) def test_flake8_complaince(self): """generated project should pass flake8""" self.generate_project() try: sh.flake8(self.destpath) except sh.ErrorReturnCode as e: raise AssertionError(e)
import re import sh from .base import DjangoCookieTestCase class TestCookiecutterSubstitution(DjangoCookieTestCase): """Test that all cookiecutter instances are substituted""" def test_all_cookiecutter_instances_are_substituted(self): # Build a list containing absolute paths to the generated files paths = self.generate_project() # Construct the cookiecutter search pattern pattern = "{{(\s?cookiecutter)[.](.*?)}}" re_obj = re.compile(pattern) # Assert that no match is found in any of the files for path in paths: for line in open(path, 'r'): match = re_obj.search(line) self.assertIsNone( match, "cookiecutter variable not replaced in {}".format(path)) def test_flake8_complaince(self): """generated project should pass flake8""" self.generate_project() try: sh.flake8(self.destpath) except sh.ErrorReturnCode as e: raise AssertionError(e)
Remove test for number of config properties This is a really stupid way to test. Instead test the actual properties.
define([ 'page_config' ], function (PageConfig) { describe('PageConfig', function () { var req; beforeEach(function () { var get = jasmine.createSpy(); get.plan = function (prop) { return { assetPath: '/path/to/assets/', govukHost: 'www.gov.uk' }[prop]; }; req = { app: { get: get }, protocol: 'http', originalUrl: '/performance/foo' }; }); describe('getGovUkUrl', function () { it('returns the equivalent page location on GOV.UK', function () { expect(PageConfig.getGovUkUrl(req)).toEqual('https://www.gov.uk/performance/foo'); }); }); describe('commonConfig', function () { it('contains assetPath property', function () { var commonConfig = PageConfig.commonConfig(req); expect(commonConfig.assetPath).toEqual('/path/to/assets/'); }); it('contains assetPath property', function () { var commonConfig = PageConfig.commonConfig(req); expect(commonConfig.url).toEqual('/performance/foo'); }); }); }); });
define([ 'page_config' ], function (PageConfig) { describe('PageConfig', function () { var req; beforeEach(function () { var get = jasmine.createSpy(); get.plan = function (prop) { return { assetPath: '/path/to/assets/', govukHost: 'www.gov.uk' }[prop]; }; req = { app: { get: get }, protocol: 'http', originalUrl: '/performance/foo' }; }); describe('getGovUkUrl', function () { it('returns the equivalent page location on GOV.UK', function () { expect(PageConfig.getGovUkUrl(req)).toEqual('https://www.gov.uk/performance/foo'); }); }); describe('commonConfig', function () { it('returns configuration required by all Spotlight pages', function () { var commonConfig = PageConfig.commonConfig(req); expect(Object.keys(commonConfig).length).toEqual(7); expect(commonConfig.assetPath).toEqual('/path/to/assets/'); }); }); }); });
Revise docstring by adding advantage
from __future__ import absolute_import from __future__ import print_function from __future__ import division def insertion_sort(a_list): """Insertion Sort algortihm. Time complexity: O(n^2). Although its complexity is bigger than the ones with O(n*logn), one advantage is the sorting happens in place. """ gen = ((i, v) for i, v in enumerate(a_list) if i > 0) for (i, v) in gen: key = i while key > 0 and a_list[key - 1] > v: a_list[key] = a_list[key - 1] key -= 1 a_list[key] = v def main(): a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20] insertion_sort(a_list) print(a_list) if __name__ == '__main__': main()
from __future__ import absolute_import from __future__ import print_function from __future__ import division def insertion_sort(a_list): """Insertion Sort algortihm. Time complexity: O(n^2). """ gen = ((i, v) for i, v in enumerate(a_list) if i > 0) for (i, v) in gen: key = i while key > 0 and a_list[key - 1] > v: a_list[key] = a_list[key - 1] key -= 1 a_list[key] = v def main(): a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20] insertion_sort(a_list) print(a_list) if __name__ == '__main__': main()
Add authorize to createReceiver() convenience method
"use strict"; module.exports.Receiver = require( './lib/receiver' ); module.exports.transports = { receivers: { Express: require( './lib/transport.receiver.express' ), Local: require( './lib/transport.receiver.local' ) }, senders: { Http: require( './lib/transport.sender.http' ) } }; // convenience method for creating a receiver. module.exports.createReceiver = function( params ) { params = params || {}; var transConfig = params.transports; var receiver = new this.Receiver( { authorize: params.authorize, baseDir: params.baseDir } ); for ( var name in transConfig ) { if ( transConfig.hasOwnProperty( name ) && this.transports.receivers.hasOwnProperty( name ) ) { receiver.addTransport( new this.transports.receivers[ name ]( transConfig[ name ] ) ); } } return receiver; };
"use strict"; module.exports.Receiver = require( './lib/receiver' ); module.exports.transports = { receivers: { Express: require( './lib/transport.receiver.express' ), Local: require( './lib/transport.receiver.local' ) }, senders: { Http: require( './lib/transport.sender.http' ) } }; // convenience method for creating a receiver. module.exports.createReceiver = function( params ) { params = params || {}; var transConfig = params.transports; var receiver = new this.Receiver( { baseDir: params.baseDir } ); for ( var name in transConfig ) { if ( transConfig.hasOwnProperty( name ) && this.transports.receivers.hasOwnProperty( name ) ) { receiver.addTransport( new this.transports.receivers[ name ]( transConfig[ name ] ) ); } } return receiver; };
Remove extra space in help string Extra spaces make the openstack-manuals tests fail with a niceness error. This patch removes an extra space at the end of a help string. Change-Id: I29bab90ea5a6f648c4539c7cd20cd9b2b63055c2
# Copyright (c) 2014 OpenStack Foundation # 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. from oslo.config import cfg from neutron.extensions import portbindings eswitch_opts = [ cfg.StrOpt('vnic_type', default=portbindings.VIF_TYPE_MLNX_DIRECT, help=_("Type of VM network interface: mlnx_direct or " "hostdev")), cfg.BoolOpt('apply_profile_patch', default=False, help=_("Enable server compatibility with old nova")), ] cfg.CONF.register_opts(eswitch_opts, "ESWITCH")
# Copyright (c) 2014 OpenStack Foundation # 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. from oslo.config import cfg from neutron.extensions import portbindings eswitch_opts = [ cfg.StrOpt('vnic_type', default=portbindings.VIF_TYPE_MLNX_DIRECT, help=_("Type of VM network interface: mlnx_direct or " "hostdev")), cfg.BoolOpt('apply_profile_patch', default=False, help=_("Enable server compatibility with old nova ")), ] cfg.CONF.register_opts(eswitch_opts, "ESWITCH")
Add region names to platform id constants
package constant; /* * Copyright 2015 Taylor Caldwell * * 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. */ public enum PlatformId { NA("NA1", "na"), BR("BR1", "br"), LAN("LA1", "lan"), LAS("LA2", "las"), OCE("OC1", "oce"), EUNE("EUN1", "eune"), EUW("EUW1", "euw"), KR("KR", "kr"), RU("RU", "ru"), TR("TR1", "tr"); private String id; private String name; PlatformId(String id, String name) { this.id = id; this.name = name; } public String getId() { return id; } public String getName() { return name; } }
package constant; /* * Copyright 2015 Taylor Caldwell * * 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. */ public enum PlatformId { NA("NA1"), BR("BR1"), LAN("LA1"), LAS("LA2"), OCE("OC1"), EUNE("EUN1"), EUW("EUW1"), KR("KR"), RU("RU"), TR("TR1"); private String id; PlatformId(String id) { this.id = id; } public String getId() { return id; } }
Disable first run after configuration process
const Configstore = require('configstore'); const Promise = require('promise'); const inquirer = require('inquirer'); const pkg = require('../../../../package.json'); const prompts = require('./setup-prompts'); class ServerConfig { static DEFAULTS = { 'isFirstRun': true, 'serverPort': '3000' } constructor(defaults = this.constructor.DEFAULTS) { this.db = new Configstore(pkg.name, defaults); } prompt() { return new Promise((resolve, reject) => { console.log('> Preparing initial setup\n'); inquirer.prompt(prompts, answers => { Object.keys(answers).map(key => { return this.db.set(key, answers[key]); }); this.db.set('isFirstRun', false); resolve('\n> Setup finished!\n'); }); }); } } module.exports = new ServerConfig();
const Configstore = require('configstore'); const Promise = require('promise'); const inquirer = require('inquirer'); const pkg = require('../../../../package.json'); const prompts = require('./setup-prompts'); class ServerConfig { static DEFAULTS = { 'isFirstRun': true, 'serverPort': '3000' } constructor(defaults = this.constructor.DEFAULTS) { this.db = new Configstore(pkg.name, defaults); } prompt() { return new Promise((resolve, reject) => { console.log('> Preparing initial setup\n'); this.db.set('isFirstRun', false); inquirer.prompt(prompts, answers => { Object.keys(answers).map(key => { return this.db.set(key, answers[key]); }); resolve('\n> Setup finished!\n'); }); }); } } module.exports = new ServerConfig();
fix(addon): Remove the frame-src definition as it is now obsolete.
#! /usr/bin/env node "use strict"; const defaults = { baseUrl: "", title: "Loading...", csp: "on" }; function template(rawOptions) { const options = Object.assign({}, defaults, rawOptions || {}); const csp = options.csp === "on" ? "<meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'none'; script-src 'self'; img-src http: https: data:; style-src 'self' 'unsafe-inline'; child-src 'self' https://*.youtube.com https://*.vimeo.com\">" : ""; return `<!doctype html> <html lang="en-us"> <head> <meta charset="utf-8"> ${csp} <title>${options.title}</title> <link rel="stylesheet" href="${options.baseUrl}main.css" /> <link rel="icon" type="image/svg+xml" href="${options.baseUrl}img/newtab-icon.svg"> </head> <body> <div id="root"></div> <script src="${options.baseUrl}vendor.bundle.js"></script> <script src="${options.baseUrl}bundle.js"></script> </body> </html> `; } module.exports = template; if (require.main === module) { // called from command line const args = require("minimist")(process.argv.slice(2), {alias: {baseUrl: "b", title: "t"}}); process.stdout.write(template(args)); }
#! /usr/bin/env node "use strict"; const defaults = { baseUrl: "", title: "Loading...", csp: "on" }; function template(rawOptions) { const options = Object.assign({}, defaults, rawOptions || {}); const csp = options.csp === "on" ? "<meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'none'; script-src 'self'; img-src http: https: data:; style-src 'self' 'unsafe-inline'; child-src 'self' https://*.youtube.com https://*.vimeo.com; frame-src 'self' https://*.youtube.com https://*.vimeo.com\">" : ""; return `<!doctype html> <html lang="en-us"> <head> <meta charset="utf-8"> ${csp} <title>${options.title}</title> <link rel="stylesheet" href="${options.baseUrl}main.css" /> <link rel="icon" type="image/svg+xml" href="${options.baseUrl}img/newtab-icon.svg"> </head> <body> <div id="root"></div> <script src="${options.baseUrl}vendor.bundle.js"></script> <script src="${options.baseUrl}bundle.js"></script> </body> </html> `; } module.exports = template; if (require.main === module) { // called from command line const args = require("minimist")(process.argv.slice(2), {alias: {baseUrl: "b", title: "t"}}); process.stdout.write(template(args)); }
Make removal of host a bit safer
const Connection = require('./connection'); class ConnectionPool { constructor() { this.hosts = []; this.nextHostID = 1; // not an index for array this.addHost = this.addHost.bind(this); this.getDisplayList = this.getDisplayList.bind(this); this.onConnectRequest = this.onConnectRequest.bind(this); } newConnection(ws) { const con = new Connection(ws, { addHost: this.addHost, getDisplayList: this.getDisplayList, onConnectRequest: this.onConnectRequest, onClose: () => this.removeHost(con), }); } removeHost(con) { const index = this.hosts.indexOf(con); if(index >= 0) { this.hosts.splice(index, 1); } } // ========================== Callbacks ========================== addHost(con) { this.hosts.push(con); return this.nextHostID++; } getDisplayList() { return this.hosts.map(h => ({ hostID: h.hostID, hostName: h.hostName, })); } onConnectRequest(req) { return this.hosts.find(h => ( req.hostID === h.hostID || req.hostName === h.hostName )) || null; } } module.exports = ConnectionPool;
const Connection = require('./connection'); class ConnectionPool { constructor() { this.hosts = []; this.nextHostID = 1; // not an index for array this.addHost = this.addHost.bind(this); this.getDisplayList = this.getDisplayList.bind(this); this.onConnectRequest = this.onConnectRequest.bind(this); } newConnection(ws) { return new Connection(ws, { addHost: this.addHost, getDisplayList: this.getDisplayList, onConnectRequest: this.onConnectRequest, }) } removeHost(con) { this.hosts.splice(this.hosts.indexOf(con), 1); } // ========================== Callbacks ========================== addHost(con) { this.hosts.push(con); return this.nextHostID++; } getDisplayList() { return this.hosts.map(h => ({ hostID: h.hostID, hostName: h.hostName, })); } onConnectRequest(req) { return this.hosts.find(h => ( req.hostID === h.hostID || req.hostName === h.hostName )) || null; } } module.exports = ConnectionPool;
Improve performance of the URLFallbackClassLoader. Non-scientific stopwatch tests showed a >10% speed increase, translating to a whopping seven seconds off when analysing rt.jar. git-svn-id: ed609ce04ec9e3c0bc25e071e87814dd6d976548@103 c7a0535c-eda6-11de-83d8-6d5adf01d787
/* * Mutability Detector * * Copyright 2009 Graham Allan * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.mutabilitydetector.asmoverride; import org.mutabilitydetector.cli.URLFallbackClassLoader; import org.objectweb.asm.Type; import org.objectweb.asm.tree.analysis.SimpleVerifier; public class CustomClassLoadingSimpleVerifier extends SimpleVerifier { private URLFallbackClassLoader classLoader; public CustomClassLoadingSimpleVerifier() { classLoader = new URLFallbackClassLoader(); } @Override protected Class<?> getClass(Type t) { String className; try { if (t.getSort() == Type.ARRAY) { className = t.getDescriptor().replace('/', '.'); } else { className = t.getClassName(); } return classLoader.getClass(className); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } }
/* * Mutability Detector * * Copyright 2009 Graham Allan * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.mutabilitydetector.asmoverride; import org.mutabilitydetector.cli.URLFallbackClassLoader; import org.objectweb.asm.Type; import org.objectweb.asm.tree.analysis.SimpleVerifier; public class CustomClassLoadingSimpleVerifier extends SimpleVerifier { @Override protected Class<?> getClass(Type t) { URLFallbackClassLoader classLoader = new URLFallbackClassLoader(); String className; try { if (t.getSort() == Type.ARRAY) { className = t.getDescriptor().replace('/', '.'); } else { className = t.getClassName(); } return classLoader.getClass(className); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } }
Add download and login functions
import os from synapseclient import Synapse, File expression = 'syn11311347' metadata = 'syn11311931' def upload_file(file_path, login, parent, description=None): """ Uploads file to Synapse. Password must be stored in environment variable SYNAPSE_PASS :param str file_path: Path to file :param str login: Login (usually an email address) :param str parent: Parent Synapse ID (example: syn12312415) where file will be placed :param str description: Optional description to add """ description = '' if None else description f = File(file_path, description=description, parent=parent) syn = _syn_login(login) syn.store(f) def download_file(synid, login, download_location='.'): """ Synapse ID of file to download :param str synid: Synapse ID :param str login: Synapse ID :param str download_location: Download location for file """ syn = _syn_login(login) syn.get(synid, downloadLocation=download_location) def _syn_login(login): """ Login to synapse. Set environment variable SYNAPSE_PASS to the password for `login` :param str login: :return: Synapse instance :rtype: instance """ assert 'SYNAPSE_PASS' in os.environ, 'SYNAPSE_PASS must be set as an environment variable' syn = Synapse() syn.login(login, os.environ['SYNAPSE_PASS']) return syn
import os from synapseclient import Synapse, File expression = 'syn11311347' metadata = 'syn11311931' def upload_file(file_path, login, parent, description=None): """ Uploads file to Synapse. Password must be stored in environment variable SYNAPSE_PASS :param str file_path: Path to file :param str login: Login (usually an email address) :param str parent: Parent Synapse ID (example: syn12312415) where file will be placed :param str description: Optional description to add """ description = '' if None else description f = File(file_path, description=description, parent=parent) assert 'SYNAPSE_PASS' in os.environ, 'SYNAPSE_PASS must be set as an environment variable' syn = Synapse() syn.login(login, os.environ['SYNAPSE_PASS']) syn.store(f)
Disable Sentry due to sync behavior
import changes import urlparse from flask import render_template, current_app, redirect, url_for, session from flask.views import MethodView class IndexView(MethodView): def get(self, path=''): # require auth if not session.get('email'): return redirect(url_for('login')) if current_app.config['SENTRY_DSN'] and False: parsed = urlparse.urlparse(current_app.config['SENTRY_DSN']) dsn = '%s://%s@%s/%s' % ( parsed.scheme, parsed.username, parsed.hostname + (':%s' % (parsed.port,) if parsed.port else ''), parsed.path, ) else: dsn = None return render_template('index.html', **{ 'SENTRY_PUBLIC_DSN': dsn, 'VERSION': changes.get_version(), })
import changes import urlparse from flask import render_template, current_app, redirect, url_for, session from flask.views import MethodView class IndexView(MethodView): def get(self, path=''): # require auth if not session.get('email'): return redirect(url_for('login')) if current_app.config['SENTRY_DSN']: parsed = urlparse.urlparse(current_app.config['SENTRY_DSN']) dsn = '%s://%s@%s/%s' % ( parsed.scheme, parsed.username, parsed.hostname + (':%s' % (parsed.port,) if parsed.port else ''), parsed.path, ) else: dsn = None return render_template('index.html', **{ 'SENTRY_PUBLIC_DSN': dsn, 'VERSION': changes.get_version(), })
Adjust gulp-eslint to fail on error
const gulp = require('gulp'); const eslint = require('gulp-eslint'); const mocha = require('gulp-mocha'); const nodemon = require('gulp-nodemon'); var lintFiles = ['lib/**/*.js', 'models/**/*.js', 'routes/**/*.js', 'test/**/*.js', '_server.js', 'gulpfile.js', 'index.js', 'server.js']; var testFiles = ['lib/**/*.js', 'models/**/*.js', 'routes/**/*.js', 'test/**/*.js', '_server.js', 'server.js']; gulp.task('lint', () => { return gulp.src(lintFiles) .pipe(eslint({ useEslintrc: true })) .pipe(eslint.format()) .pipe(eslint.failOnError()); }); gulp.task('test', () => { return gulp.src('test/**/*.js') .pipe(mocha({ reporter: 'spec' })); }); gulp.task('develop', () => { nodemon({ script: 'server.js', ext: 'js', tasks: ['lint', 'test'] }) .on('restart', () => { process.stdout.write('Server restarted!\n'); }); }); gulp.task('watch', () => { gulp.watch(lintFiles, ['lint']); gulp.watch(testFiles, ['test']); }); gulp.task('default', ['lint', 'test']);
const gulp = require('gulp'); const eslint = require('gulp-eslint'); const mocha = require('gulp-mocha'); const nodemon = require('gulp-nodemon'); var lintFiles = ['lib/**/*.js', 'models/**/*.js', 'routes/**/*.js', 'test/**/*.js', '_server.js', 'gulpfile.js', 'index.js', 'server.js']; var testFiles = ['lib/**/*.js', 'models/**/*.js', 'routes/**/*.js', 'test/**/*.js', '_server.js', 'server.js']; gulp.task('lint', () => { return gulp.src(lintFiles) .pipe(eslint({ useEslintrc: true })) .pipe(eslint.format()); }); gulp.task('test', () => { return gulp.src('test/**/*.js') .pipe(mocha({ reporter: 'spec' })); }); gulp.task('develop', () => { nodemon({ script: 'server.js', ext: 'js', tasks: ['lint', 'test'] }) .on('restart', () => { process.stdout.write('Server restarted!\n'); }); }); gulp.task('watch', () => { gulp.watch(lintFiles, ['lint']); gulp.watch(testFiles, ['test']); }); gulp.task('default', ['lint', 'test']);
Throw error if using getToken() outside cordova
import axios from '@/services/axios' import authUser from '@/services/api/authUser' let KEY, updateToken, clearToken if (CORDOVA) { const { localStorage } = window KEY = 'token' clearToken = () => { localStorage.removeItem(KEY) clearHeader() } updateToken = token => { localStorage.setItem(KEY, token) setHeader(token) } const initialize = () => { const token = localStorage.getItem(KEY) if (token) setHeader(token) } const setHeader = token => { axios.defaults.headers.common.Authorization = `TOKEN ${token}` } const clearHeader = () => { delete axios.defaults.headers.common.Authorization } initialize() } export default { async login ({ email, password }) { if (CORDOVA) { const { token } = (await axios.post('/api/auth/token/', { username: email, password })).data updateToken(token) return authUser.get() // return the user info to match what the /api/auth/ endpoints returns } else { return (await axios.post('/api/auth/', { email, password })).data } }, async logout () { if (CORDOVA) clearToken() return (await axios.post('/api/auth/logout/', {})).data }, getToken () { if (CORDOVA) { return localStorage.getItem(KEY) } else { throw new Error('getToken() is only available inside cordova environment') } }, }
import axios from '@/services/axios' import authUser from '@/services/api/authUser' let KEY, updateToken, clearToken if (CORDOVA) { const { localStorage } = window KEY = 'token' clearToken = () => { localStorage.removeItem(KEY) clearHeader() } updateToken = token => { localStorage.setItem(KEY, token) setHeader(token) } const initialize = () => { const token = localStorage.getItem(KEY) if (token) setHeader(token) } const setHeader = token => { axios.defaults.headers.common.Authorization = `TOKEN ${token}` } const clearHeader = () => { delete axios.defaults.headers.common.Authorization } initialize() } export default { async login ({ email, password }) { if (CORDOVA) { const { token } = (await axios.post('/api/auth/token/', { username: email, password })).data updateToken(token) return authUser.get() // return the user info to match what the /api/auth/ endpoints returns } else { return (await axios.post('/api/auth/', { email, password })).data } }, async logout () { if (CORDOVA) clearToken() return (await axios.post('/api/auth/logout/', {})).data }, getToken () { if (CORDOVA) { return localStorage.getItem(KEY) } }, }
Update eve_proxy taks for Django 1.4
import logging from datetime import datetime, timedelta from django.conf import settings from django.utils.timezone import now from celery.task import task from eve_proxy.models import CachedDocument, ApiAccessLog @task(ignore_result=True) def clear_stale_cache(cache_extension=0): log = clear_stale_cache.get_logger() time = now() - timedelta(seconds=cache_extension) objs = CachedDocument.objects.filter(cached_until__lt=time) log.info('Removing %s stale cache documents' % objs.count()) objs.delete() @task(ignore_result=True) def clear_old_logs(): log = clear_old_logs.get_logger() time = now() - timedelta(days=getattr(settings, 'EVE_PROXY_KEEP_LOGS', 30)) objs = ApiAccessLog.objects.filter(time_access__lt=time) log.info('Removing %s old access logs' % objs.count()) objs.delete()
from django.conf import settings import logging from datetime import datetime, timedelta from celery.task import task from eve_proxy.models import CachedDocument, ApiAccessLog @task(ignore_result=True) def clear_stale_cache(cache_extension=0): log = clear_stale_cache.get_logger() time = datetime.utcnow() - timedelta(seconds=cache_extension) objs = CachedDocument.objects.filter(cached_until__lt=time) log.info('Removing %s stale cache documents' % objs.count()) objs.delete() @task(ignore_result=True) def clear_old_logs(): log = clear_old_logs.get_logger() time = datetime.utcnow() - timedelta(days=settings.EVE_PROXY_KEEP_LOGS) objs = ApiAccessLog.objects.filter(time_access__lt=time) log.info('Removing %s old access logs' % objs.count()) objs.delete()
Add function for flashing all form errors
import re from flask import url_for, flash def register_template_utils(app): """Register Jinja 2 helpers (called from __init__.py).""" @app.template_test() def equalto(value, other): return value == other @app.template_global() def is_hidden_field(field): from wtforms.fields import HiddenField return isinstance(field, HiddenField) app.add_template_global(index_for_role) def index_for_role(role): return url_for(role.index) def parse_phone_number(phone_number): """Make phone number conform to E.164 (https://en.wikipedia.org/wiki/E.164) """ stripped = re.sub(r'\D', '', phone_number) if len(stripped) == 10: stripped = '1' + stripped stripped = '+' + stripped return stripped def flash_errors(form): for field, errors in form.errors.items(): for error in errors: flash(u"Error in the %s field - %s" % ( getattr(form, field).label.text, error ))
import re from flask import url_for def register_template_utils(app): """Register Jinja 2 helpers (called from __init__.py).""" @app.template_test() def equalto(value, other): return value == other @app.template_global() def is_hidden_field(field): from wtforms.fields import HiddenField return isinstance(field, HiddenField) app.add_template_global(index_for_role) def index_for_role(role): return url_for(role.index) def parse_phone_number(phone_number): """Make phone number conform to E.164 (https://en.wikipedia.org/wiki/E.164) """ stripped = re.sub(r'\D', '', phone_number) if len(stripped) == 10: stripped = '1' + stripped stripped = '+' + stripped return stripped
Set __name__, __doc__ and __package__ in Module
// Module objects package py import ( "fmt" ) var ( // Registry of installed modules modules = make(map[string]*Module) // Builtin module Builtins *Module ) // A python Module object type Module struct { Name string Doc string Globals StringDict // dict Dict } var ModuleType = NewType("module", "module object") // Type of this object func (o *Module) Type() *Type { return ModuleType } // Define a new module func NewModule(name, doc string, methods []*Method, globals StringDict) *Module { m := &Module{ Name: name, Doc: doc, Globals: globals.Copy(), } // Insert the methods into the module dictionary for _, method := range methods { m.Globals[method.Name] = method } // Set some module globals m.Globals["__name__"] = String(name) m.Globals["__doc__"] = String(doc) m.Globals["__package__"] = None // Register the module modules[name] = m // Make a note of the builtin module if name == "builtins" { Builtins = m } fmt.Printf("Registering module %q\n", name) return m }
// Module objects package py import ( "fmt" ) var ( // Registry of installed modules modules = make(map[string]*Module) // Builtin module Builtins *Module ) // A python Module object type Module struct { Name string Doc string Globals StringDict // dict Dict } var ModuleType = NewType("module", "module object") // Type of this object func (o *Module) Type() *Type { return ModuleType } // Define a new module func NewModule(name, doc string, methods []*Method, globals StringDict) *Module { m := &Module{ Name: name, Doc: doc, Globals: globals.Copy(), } // Insert the methods into the module dictionary for _, method := range methods { m.Globals[method.Name] = method } // Register the module modules[name] = m // Make a note of the builtin module if name == "builtins" { Builtins = m } fmt.Printf("Registering module %q\n", name) return m }
Fix crashing bug: Compare Libya
import { createSelector } from 'reselect'; import isEmpty from 'lodash/isEmpty'; import { parseSelectedLocations, getSelectedLocationsFilter, addSelectedNameToLocations } from 'selectors/compare'; // values from search const getSelectedLocations = state => state.selectedLocations || null; const getContentOverviewData = state => state.ndcContentOverviewData || null; const getCountriesData = state => state.countriesData || null; const parseLocations = parseSelectedLocations(getSelectedLocations); export const getLocationsFilter = getSelectedLocationsFilter( getSelectedLocations ); export const addNameToLocations = addSelectedNameToLocations( getCountriesData, parseLocations ); export const getSummaryText = createSelector( [addNameToLocations, getContentOverviewData], (selectedLocations, data) => { if (!selectedLocations || !data || isEmpty(data)) return null; return selectedLocations.map(l => { const d = data[l.iso_code3]; const text = d && d.values && d.values.find(v => v.slug === 'indc_summary'); return { ...l, text: text && text.value }; }); } ); export default { getSummaryText, getLocationsFilter };
import { createSelector } from 'reselect'; import isEmpty from 'lodash/isEmpty'; import { parseSelectedLocations, getSelectedLocationsFilter, addSelectedNameToLocations } from 'selectors/compare'; // values from search const getSelectedLocations = state => state.selectedLocations || null; const getContentOverviewData = state => state.ndcContentOverviewData || null; const getCountriesData = state => state.countriesData || null; const parseLocations = parseSelectedLocations(getSelectedLocations); export const getLocationsFilter = getSelectedLocationsFilter( getSelectedLocations ); export const addNameToLocations = addSelectedNameToLocations( getCountriesData, parseLocations ); export const getSummaryText = createSelector( [addNameToLocations, getContentOverviewData], (selectedLocations, data) => { if (!selectedLocations || !data || isEmpty(data)) return null; return selectedLocations.map(l => { const d = data[l.iso_code3]; const text = d && d.values && d.values.find(v => v.slug === 'indc_summary').value; return { ...l, text }; }); } ); export default { getSummaryText, getLocationsFilter };
Update to support Synchronous Parsing
const AnnotationParser = require(__dirname+"/../").AnnotationParser; const Request = require(__dirname+"/myannotations/Request"); try { let annotatedElements = AnnotationParser.parse(__dirname+"/annotatedFile.js", __dirname+"/myannotations/"); for (let i in annotatedElements) { if (typeof annotatedElements[i] != "function") { // TODO : Improve this feature let annotatedElement = annotatedElements[i]; console.log(annotatedElement.getName()+" : "+annotatedElement.getType()); let elementAnnotations = annotatedElement.getAnnotations(); for (let i in elementAnnotations) { console.log("\t"+JSON.stringify(elementAnnotations[i])); } console.log(); } } } catch (err) { console.log(err); }
const AnnotationParser = require(__dirname+"/../").AnnotationParser; const Request = require(__dirname+"/myannotations/Request"); AnnotationParser.parse( __dirname+"/annotatedFile.js", __dirname+"/myannotations/", (err, annotatedElements) => { if (err) { console.log(err); } else { for (let i in annotatedElements) { if (typeof annotatedElements[i] != "function") { // TODO : Improve this feature let annotatedElement = annotatedElements[i]; console.log(annotatedElement.getName()+" : "+annotatedElement.getType()); let elementAnnotations = annotatedElement.getAnnotations(); for (let i in elementAnnotations) { console.log("\t"+JSON.stringify(elementAnnotations[i])); } console.log(); } } } });
Make sure we'll be able to obtain a new token before reset
'use strict'; var async = require('async'); var rarity = require('rarity'); var AnyFetch = require('../../lib/index.js'); /** * Reset the company and obtain the new Bearer token. * Automatically switch to Bearer auth. */ AnyFetch.prototype.resetToBearer = function(done) { var self = this; if(!self.basicAuthHeader) { return done(new Error('Reset canceled: `this` does not contain basic auth infos, we would not be able to obtain a new token after reset.')); } async.waterfall([ function resetCompany(cb) { self.deleteCompanyReset(rarity.slice(1, cb)); }, function obtainNewToken(cb) { // Switch back to basic auth to obtain a new token self.authHeader = self.basicAuthHeader; self.getToken(cb); } ], function(err, res) { if(res && res.body && res.body.token) { // Switch to Bearer auth self.authHeader = 'Bearer ' + res.body.token; } done(err, res); }); };
'use strict'; var async = require('async'); var rarity = require('rarity'); var AnyFetch = require('../../lib/index.js'); /** * Reset the company and obtain the new Bearer token. * Automatically switch to Bearer auth. */ AnyFetch.prototype.resetToBearer = function(done) { var self = this; async.waterfall([ function resetCompany(cb) { self.deleteCompanyReset(rarity.slice(1, cb)); }, function obtainNewToken(cb) { // Switch back to basic auth to obtain a new token self.authHeader = self.basicAuthHeader; self.getToken(cb); } ], function(err, res) { if(res && res.body && res.body.token) { // Switch to Bearer auth self.authHeader = 'Bearer ' + res.body.token; } done(err, res); }); };
Add error for non-wrapped LinearRing
/** * Generates a new GeoJSON Polygon feature, given an array of coordinates * and list of properties. * * @module turf/polygon * @param {number[][]} rings - an array of LinearRings * @param {Object} properties - an optional properties object * @return {GeoJSONPolygon} output * @example * var poly1 = turf.polygon([[[20.0,0.0],[101.0,0.0],[101.0,1.0],[100.0,1.0],[100.0,0.0]]]) * var poly2 = turf.polygon([[[20.0,0.0],[101.0,0.0],[101.0,1.0],[100.0,1.0],[100.0,0.0]]], * {name: 'line 1', distance: 145}) * console.log(poly1) * console.log(poly2) */ module.exports = function(coordinates, properties){ if(coordinates === null) return new Error('No coordinates passed'); if(coordinates[0] !== coordinates[coordinates.length - 1]) return new Error('First and last coordinate pair are not equivalent'); var polygon = { "type": "Feature", "geometry": { "type": "Polygon", "coordinates": coordinates }, "properties": properties }; if(!polygon.properties){ polygon.properties = {}; } return polygon; }
/** * Generates a new GeoJSON Polygon feature, given an array of coordinates * and list of properties. * * @module turf/polygon * @param {number[][]} rings - an array of LinearRings * @param {Object} properties - an optional properties object * @return {GeoJSONPolygon} output * @example * var poly1 = turf.polygon([[[20.0,0.0],[101.0,0.0],[101.0,1.0],[100.0,1.0],[100.0,0.0]]]) * var poly2 = turf.polygon([[[20.0,0.0],[101.0,0.0],[101.0,1.0],[100.0,1.0],[100.0,0.0]]], * {name: 'line 1', distance: 145}) * console.log(poly1) * console.log(poly2) */ module.exports = function(coordinates, properties){ if(coordinates === null) return new Error('No coordinates passed'); var polygon = { "type": "Feature", "geometry": { "type": "Polygon", "coordinates": coordinates }, "properties": properties }; if(!polygon.properties){ polygon.properties = {}; } return polygon; }
Allow limiting selection by role
<? include '../scat.php'; $criteria= array(); $term= $_REQUEST['term']; $terms= preg_split('/\s+/', $term); foreach ($terms as $term) { $term= $db->real_escape_string($term); $criteria[]= "(person.name LIKE '%$term%' OR person.company LIKE '%$term%')"; } if (!$_REQUEST['all']) $criteria[]= 'active'; if (($type= $_REQUEST['role'])) { $criteria[]= "person.role = '" . $db->escape($type) . "'"; } if (empty($criteria)) { $criteria= '1=1'; } else { $criteria= join(' AND ', $criteria); } $q= "SELECT id, CONCAT(IFNULL(name, ''), IF(name != '' AND company != '', ' / ', ''), IFNULL(company, '')) AS value FROM person WHERE $criteria ORDER BY value"; $r= $db->query($q) or die_query($db, $q); $list= array(); while ($row= $r->fetch_assoc()) { /* force numeric values to numeric type */ $list[]= $row; } echo jsonp($list);
<? include '../scat.php'; $criteria= array(); $term= $_REQUEST['term']; $terms= preg_split('/\s+/', $term); foreach ($terms as $term) { $term= $db->real_escape_string($term); $criteria[]= "(person.name LIKE '%$term%' OR person.company LIKE '%$term%')"; } if (!$_REQUEST['all']) $criteria[]= 'active'; if (empty($criteria)) { $criteria= '1=1'; } else { $criteria= join(' AND ', $criteria); } $q= "SELECT id, CONCAT(IFNULL(name, ''), IF(name != '' AND company != '', ' / ', ''), IFNULL(company, '')) AS value FROM person WHERE $criteria ORDER BY value"; $r= $db->query($q) or die_query($db, $q); $list= array(); while ($row= $r->fetch_assoc()) { /* force numeric values to numeric type */ $list[]= $row; } echo jsonp($list);
Fix error handling on aggregate status report Previously the catch block was a little too aggressive. It was swallowing a real error (since aggregate reports pass a float, not a decimal). Now we prevent the original possible errors by converting no matter what the type is and checking for zero/null values first.
from decimal import Decimal UNDERSTOCK_THRESHOLD = 0.5 # months OVERSTOCK_THRESHOLD = 2. # months def months_of_stock_remaining(stock, daily_consumption): if daily_consumption: return stock / Decimal((daily_consumption * 30)) else: return None def stock_category(stock, daily_consumption): if stock is None: return 'nodata' elif stock == 0: return 'stockout' elif daily_consumption is None: return 'nodata' elif daily_consumption == 0: return 'overstock' months_left = months_of_stock_remaining(stock, daily_consumption) if months_left is None: return 'nodata' elif months_left < UNDERSTOCK_THRESHOLD: return 'understock' elif months_left > OVERSTOCK_THRESHOLD: return 'overstock' else: return 'adequate'
UNDERSTOCK_THRESHOLD = 0.5 # months OVERSTOCK_THRESHOLD = 2. # months def months_of_stock_remaining(stock, daily_consumption): try: return stock / (daily_consumption * 30) except (TypeError, ZeroDivisionError): return None def stock_category(stock, daily_consumption): if stock is None: return 'nodata' elif stock == 0: return 'stockout' elif daily_consumption is None: return 'nodata' elif daily_consumption == 0: return 'overstock' months_left = months_of_stock_remaining(stock, daily_consumption) if months_left is None: return 'nodata' elif months_left < UNDERSTOCK_THRESHOLD: return 'understock' elif months_left > OVERSTOCK_THRESHOLD: return 'overstock' else: return 'adequate'
Add HTMLInputElement to satisfy ag-grid dependecy
// satisfy ag-grid HTMLElement dependency HTMLElement = typeof HTMLElement === 'undefined' ? function () {} : HTMLElement; HTMLSelectElement = typeof HTMLSelectElement === 'undefined' ? function () {} : HTMLSelectElement; HTMLInputElement = typeof HTMLInputElement === 'undefined' ? function () {} : HTMLInputElement; var {AgGridNg2} = require('./dist/agGridNg2'); var {ComponentUtil} = require("ag-grid/main"); var missingProperties = []; ComponentUtil.ALL_PROPERTIES.forEach((property) => { if (!AgGridNg2.propDecorators.hasOwnProperty(property)) { missingProperties.push(`Grid property ${property} does not exist on AgGridNg2`) } }); var missingEvents = []; ComponentUtil.EVENTS.forEach((event) => { if (!AgGridNg2.propDecorators.hasOwnProperty(event)) { missingEvents.push(`Grid event ${event} does not exist on AgGridNg2`) } }); if(missingProperties.length || missingEvents.length) { console.error("*************************** BUILD FAILED ***************************"); missingProperties.concat(missingEvents).forEach((message) => console.error(message)); console.error("*************************** BUILD FAILED ***************************"); throw("Build Properties Check Failed"); } else { console.info("*************************** BUILD OK ***************************"); }
// satisfy ag-grid HTMLElement dependency HTMLElement = typeof HTMLElement === 'undefined' ? function () {} : HTMLElement; HTMLSelectElement = typeof HTMLSelectElement === 'undefined' ? function () {} : HTMLSelectElement; var {AgGridNg2} = require('./dist/agGridNg2'); var {ComponentUtil} = require("ag-grid/main"); var missingProperties = []; ComponentUtil.ALL_PROPERTIES.forEach((property) => { if (!AgGridNg2.propDecorators.hasOwnProperty(property)) { missingProperties.push(`Grid property ${property} does not exist on AgGridNg2`) } }); var missingEvents = []; ComponentUtil.EVENTS.forEach((event) => { if (!AgGridNg2.propDecorators.hasOwnProperty(event)) { missingEvents.push(`Grid event ${event} does not exist on AgGridNg2`) } }); if(missingProperties.length || missingEvents.length) { console.error("*************************** BUILD FAILED ***************************"); missingProperties.concat(missingEvents).forEach((message) => console.error(message)); console.error("*************************** BUILD FAILED ***************************"); throw("Build Properties Check Failed"); } else { console.info("*************************** BUILD OK ***************************"); }
Update unit test for ad8bcd8
# -*- coding: utf-8 -*- import unittest from gtts.tokenizer.pre_processors import tone_marks, end_of_line, abbreviations, word_sub class TestPreProcessors(unittest.TestCase): def test_tone_marks(self): _in = "lorem!ipsum?" _out = "lorem! ipsum? " self.assertEqual(tone_marks(_in), _out) def test_end_of_line(self): _in = """test- ing""" _out = "testing" self.assertEqual(end_of_line(_in), _out) def test_abbreviations(self): _in = "jr. sr. dr." _out = "jr sr dr" self.assertEqual(abbreviations(_in), _out) def test_word_sub(self): _in = "Esq. Bacon" _out = "Esquire Bacon" self.assertEqual(word_sub(_in), _out) if __name__ == '__main__': unittest.main()
# -*- coding: utf-8 -*- import unittest from gtts.tokenizer.pre_processors import tone_marks, end_of_line, abbreviations, word_sub class TestPreProcessors(unittest.TestCase): def test_tone_marks(self): _in = "lorem!ipsum?" _out = "lorem! ipsum? " self.assertEqual(tone_marks(_in), _out) def test_end_of_line(self): _in = """test- ing""" _out = "testing" self.assertEqual(end_of_line(_in), _out) def test_abbreviations(self): _in = "jr. sr. dr." _out = "jr sr dr" self.assertEqual(abbreviations(_in), _out) def test_word_sub(self): _in = "M. Bacon" _out = "Monsieur Bacon" self.assertEqual(word_sub(_in), _out) if __name__ == '__main__': unittest.main()
Add json exporter module to modules coveraged
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', } } MODELTREES = { 'default': { 'model': 'tests.Employee' } } INSTALLED_APPS = ( 'avocado', 'avocado.meta', 'avocado.tests', ) COVERAGE_MODULES = ( 'avocado.meta.formatters', 'avocado.meta.exporters._base', 'avocado.meta.exporters._csv', 'avocado.meta.exporters._excel', 'avocado.meta.exporters._sas', 'avocado.meta.exporters._r', 'avocado.meta.exporters._json', # 'avocado.meta.logictree', 'avocado.meta.managers', 'avocado.meta.mixins', 'avocado.meta.models', 'avocado.meta.operators', 'avocado.meta.translators', 'avocado.meta.utils', ) TEST_RUNNER = 'avocado.tests.coverage_test.CoverageTestRunner'
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', } } MODELTREES = { 'default': { 'model': 'tests.Employee' } } INSTALLED_APPS = ( 'avocado', 'avocado.meta', 'avocado.tests', ) COVERAGE_MODULES = ( 'avocado.meta.formatters', 'avocado.meta.exporters._base', 'avocado.meta.exporters._csv', 'avocado.meta.exporters._excel', 'avocado.meta.exporters._sas', 'avocado.meta.exporters._r', # 'avocado.meta.logictree', 'avocado.meta.managers', 'avocado.meta.mixins', 'avocado.meta.models', 'avocado.meta.operators', 'avocado.meta.translators', 'avocado.meta.utils', ) TEST_RUNNER = 'avocado.tests.coverage_test.CoverageTestRunner'
test: Update Twitter auth test to run directly
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Twitter API test module. Local test to check that Twitter credentials are valid connect to Twitter API and that the auth functions can be used to do this. """ from __future__ import absolute_import import os import sys import unittest from unittest import TestCase # Allow imports to be done when executing this file directly. sys.path.insert(0, os.path.abspath(os.path.join( os.path.dirname(__file__), os.path.pardir, os.path.pardir) )) from lib.twitter_api import authentication class TestAuth(TestCase): def test_generateAppAccessToken(self): auth = authentication._generateAppAccessToken() def test_getTweepyConnection(self): auth = authentication._generateAppAccessToken() api = authentication._getTweepyConnection(auth) def test_getAPIConnection(self): """ Test that App Access token can be used to connect to Twitter API. """ api = authentication.getAPIConnection(userFlow=False) def test_getAppOnlyConnection(self): """ Test App-only token. """ api = authentication.getAppOnlyConnection() if __name__ == '__main__': unittest.main()
# -*- coding: utf-8 -*- """ Twitter API test module. Local test to check that Twitter credentials are valid connect to Twitter API and that the auth functions can be used to do this. s""" from __future__ import absolute_import from unittest import TestCase from lib.twitter_api import authentication class TestAuth(TestCase): def test_generateAppAccessToken(self): auth = authentication._generateAppAccessToken() def test_getTweepyConnection(self): auth = authentication._generateAppAccessToken() api = authentication._getTweepyConnection(auth) def test_getAPIConnection(self): """ Test that App Access token can be used to connect to Twitter API. """ api = authentication.getAPIConnection(userFlow=False) def test_getAppOnlyConnection(self): """ Test App-only token. """ api = authentication.getAppOnlyConnection()
Scale back threading, beacause Rasp Pi doesn't have enough threads
from igc.util import cache, util util.setupLog() from flask import Flask from flask import send_from_directory from flask_cors import CORS from igc.controller.controller_register import register_controllers app = Flask(__name__) CORS(app) app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///./sqllite.db" app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False register_controllers(app) cache.initalizeCache() for x in range(3): print "Starting Cache Thread: " + str(x) thread = cache.CacheThread() thread.start() thread = cache.CacheSchedulerThread() thread.start() @app.route("/") def index(): return app.send_static_file('index.html') @app.route("/<path:path>") def send_static(path): return send_from_directory('static', path) app.run(debug=False, port=5000)
from igc.util import cache, util util.setupLog() from flask import Flask from flask import send_from_directory from flask_cors import CORS from igc.controller.controller_register import register_controllers app = Flask(__name__) CORS(app) app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///./sqllite.db" app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False register_controllers(app) cache.initalizeCache() for x in range(5): print "Starting Cache Thread: " + str(x) thread = cache.CacheThread() thread.start() thread = cache.CacheSchedulerThread() thread.start() @app.route("/") def index(): return app.send_static_file('index.html') @app.route("/<path:path>") def send_static(path): return send_from_directory('static', path) app.run(debug=False, port=5000)
Remove version number from Python shebang. On special request from someone trying to purge python2.2 from code indexed internally at Google. git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@7071 0039d316-1c4b-4281-b951-d872f2087c98
#!/usr/bin/python # Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import md5 """64-bit fingerprint support for strings. Usage: from extern import FP print 'Fingerprint is %ld' % FP.FingerPrint('Hello world!') """ def UnsignedFingerPrint(str, encoding='utf-8'): """Generate a 64-bit fingerprint by taking the first half of the md5 of the string.""" hex128 = md5.new(str).hexdigest() int64 = long(hex128[:16], 16) return int64 def FingerPrint(str, encoding='utf-8'): fp = UnsignedFingerPrint(str, encoding=encoding) # interpret fingerprint as signed longs if fp & 0x8000000000000000L: fp = - ((~fp & 0xFFFFFFFFFFFFFFFFL) + 1) return fp
#!/usr/bin/python2.2 # Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import md5 """64-bit fingerprint support for strings. Usage: from extern import FP print 'Fingerprint is %ld' % FP.FingerPrint('Hello world!') """ def UnsignedFingerPrint(str, encoding='utf-8'): """Generate a 64-bit fingerprint by taking the first half of the md5 of the string.""" hex128 = md5.new(str).hexdigest() int64 = long(hex128[:16], 16) return int64 def FingerPrint(str, encoding='utf-8'): fp = UnsignedFingerPrint(str, encoding=encoding) # interpret fingerprint as signed longs if fp & 0x8000000000000000L: fp = - ((~fp & 0xFFFFFFFFFFFFFFFFL) + 1) return fp
Update example to check for query and body parameters.
'use strict' const sitemap = require('./../index') const express = require('express') const app = express() const core = new express.Router() const other = new express.Router() app.use(express.urlencoded({extended: false})) app.use(express.json()) app.use('/core', core) app.use(other) // express routing core.get('/', function(req, res) { res.send('hello /') }).get('/admin', function(req, res) { res.send('hello /admin') }).post('/admin', function(req, res) { res.send('hello /admin') }).get('/duplicate', function(req, res) { const master = req.query.master res.send(`hello /duplicate with: master = ${master} and ${req.query.boss}`) }).get('/duplicate/:id', function(req, res) { res.send(`hello /duplicate with id = ${req.params.id}`) }) other.post('/foo', function(req, res) { res.send(`hello /foo with: master = ${req.body.master} and ${req.body.boss}`) }).put('/nooo', function(req, res) { res.send('hello /nooo') }).get('/zas', function(req, res) { res.end('hello /zas') }) /* * sitemap */ app.get('/sitemap', sitemap(app)) /** * Auto generated Swagger UI */ sitemap.swagger('Demo', app) // server starting app.listen(3000) console.log('starting "sitemap example" on port 3000')
'use strict' const sitemap = require('./../index') const express = require('express') const app = express() const core = new express.Router() const other = new express.Router() app.use('/core', core) app.use(other) // express routing core.get('/', function(req, res) { res.send('hello /') }).get('/admin', function(req, res) { res.send('hello /admin') }).post('/admin', function(req, res) { res.send('hello /admin') }).get('/duplicate', function(req, res) { res.send('hello /duplicate') }).get('/duplicate/:id', function(req, res) { res.send('hello /duplicate') }) other.post('/foo', function(req, res) { res.send('hello /foo') }).put('/nooo', function(req, res) { res.send('hello /nooo') }).get('/zas', function(req, res) { res.end('hello /zas') }) /* * sitemap */ app.get('/sitemap', sitemap(app)) /** * Auto generated Swagger UI */ sitemap.swagger('Demo', app) // server starting app.listen(3000) console.log('starting "sitemap example" on port 3000')
Test that con.execute() propagate Postgres exceptions
import asyncpg from asyncpg import _testbase as tb class TestExecuteScript(tb.ConnectedTestCase): async def test_execute_script_1(self): r = await self.con.execute(''' SELECT 1; SELECT true FROM pg_type WHERE false = true; SELECT 2; ''') self.assertIsNone(r) async def test_execute_script_check_transactionality(self): with self.assertRaises(asyncpg.Error): await self.con.execute(''' CREATE TABLE mytab (a int); SELECT * FROM mytab WHERE 1 / 0 = 1; ''') with self.assertRaisesRegex(asyncpg.Error, '"mytab" does not exist'): await self.con.prepare(''' SELECT * FROM mytab ''') async def test_execute_exceptions_1(self): with self.assertRaisesRegex(asyncpg.Error, 'relation "__dne__" does not exist'): await self.con.execute('select * from __dne__')
import asyncpg from asyncpg import _testbase as tb class TestExecuteScript(tb.ConnectedTestCase): async def test_execute_script_1(self): r = await self.con.execute(''' SELECT 1; SELECT true FROM pg_type WHERE false = true; SELECT 2; ''') self.assertIsNone(r) async def test_execute_script_check_transactionality(self): with self.assertRaises(asyncpg.Error): await self.con.execute(''' CREATE TABLE mytab (a int); SELECT * FROM mytab WHERE 1 / 0 = 1; ''') with self.assertRaisesRegex(asyncpg.Error, '"mytab" does not exist'): await self.con.prepare(''' SELECT * FROM mytab ''')
Add escape to stop export
import './style.css!'; import 'bootstrap/css/bootstrap.css!'; import angular from 'angular'; import ShadertoyService from './shadertoy/service'; import ExportDirective from './export/directive'; import ExportingDirective from './exporting/directive'; import ExportErrorsDirective from './export-errors/directive'; import GoToURLDirective from './go-to-url/directive'; import PanelDirective from './panel/directive'; import ShadertoyDirective from './shadertoy/directive'; angular .module('app', []) .factory('shadertoy', ShadertoyService) .directive('export', ExportDirective) .directive('exporting', ExportingDirective) .directive('exportErrors', ExportErrorsDirective) .directive('goToUrl', GoToURLDirective) .directive('panel', PanelDirective) .directive('shadertoy', ShadertoyDirective) .run(['$document', 'shadertoy', ($document, shadertoy) => { $document.bind('keydown', (event) => { if (event.which === 27) { // escape shadertoy.stop(); event.preventDefault(); } }); }]) ;
import './style.css!'; import 'bootstrap/css/bootstrap.css!'; import angular from 'angular'; import ShadertoyService from './shadertoy/service'; import ExportDirective from './export/directive'; import ExportingDirective from './exporting/directive'; import ExportErrorsDirective from './export-errors/directive'; import GoToURLDirective from './go-to-url/directive'; import PanelDirective from './panel/directive'; import ShadertoyDirective from './shadertoy/directive'; angular .module('app', []) .factory('shadertoy', ShadertoyService) .directive('export', ExportDirective) .directive('exporting', ExportingDirective) .directive('exportErrors', ExportErrorsDirective) .directive('goToUrl', GoToURLDirective) .directive('panel', PanelDirective) .directive('shadertoy', ShadertoyDirective) ;
Add check for empty todo text
import ContentAdd from 'material-ui/lib/svg-icons/content/add'; import IconButton from 'material-ui/lib/icon-button'; import TextField from 'material-ui/lib/text-field'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { addTodo } from '../actions'; const styles = { container: { marginLeft: 20 } } let AddTodo = ({ dispatch }) => { let nodeRef; return ( <div style={ styles.container }> <form onSubmit={ (e) => { e.preventDefault(); if (!nodeRef.getValue().trim()) { return; } dispatch(addTodo(nodeRef.getValue())); nodeRef.clearValue(); }}> <TextField hintText="Add task" floatingLabelText="Add task" ref = { node => { nodeRef = node; }} /> </form> </div> ); } AddTodo = connect()(AddTodo); export default AddTodo;
import ContentAdd from 'material-ui/lib/svg-icons/content/add'; import IconButton from 'material-ui/lib/icon-button'; import TextField from 'material-ui/lib/text-field'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { addTodo } from '../actions'; const styles = { container: { marginLeft: 20 } } let AddTodo = ({ dispatch }) => { let nodeRef; return ( <div style={ styles.container }> <form onSubmit={ (e) => { e.preventDefault(); dispatch(addTodo(nodeRef.getValue())); nodeRef.clearValue(); }}> <TextField hintText="Add task" floatingLabelText="Add task" ref = { node => { nodeRef = node; }} /> </form> </div> ); } AddTodo = connect()(AddTodo); export default AddTodo;
Send 500 every now and then
var config = { clientId: '', clientSecret: '', hashTag: 'ruisrock2014' } var getIg = function(){ var ig = require('instagram-node').instagram(); ig.use({ client_id: config.clientId, client_secret: config.clientSecret}); return ig; } var parseIgMediaObject = function(media){ return { link: media.link, title: (media.caption==null)?"":media.caption.text, thumbnail: media.images.thumbnail.url, small_image: media.images.low_resolution.url, image: media.images.standard_resolution.url, likes: media.likes.count, tags: media.tags } } var parseIgMedia = function(medias){ var data = []; medias.forEach(function(media){ data.push(parseIgMediaObject(media)); }); return data; } module.exports = { tagMedia: function(req, res) { try{ getIg().tag_media_recent(config.hashTag, function(err, medias, pagination, limit) { if(err)res.send(500); else res.send(JSON.stringify({media: parseIgMedia(medias)})); }); }catch(err){ res.send(500); } } }
var config = { clientId: '', clientSecret: '', hashTag: 'ruisrock2014' } var getIg = function(){ var ig = require('instagram-node').instagram(); ig.use({ client_id: config.clientId, client_secret: config.clientSecret}); return ig; } var parseIgMediaObject = function(media){ return { link: media.link, title: (media.caption==null)?"":media.caption.text, thumbnail: media.images.thumbnail.url, small_image: media.images.low_resolution.url, image: media.images.standard_resolution.url, likes: media.likes.count, tags: media.tags } } var parseIgMedia = function(medias){ var data = []; medias.forEach(function(media){ data.push(parseIgMediaObject(media)); }); return data; } module.exports = { tagMedia: function(req, res) { try{ getIg().tag_media_recent(config.hashTag, function(err, medias, pagination, limit) { if(err) throw new Error("Virhe"); res.send(JSON.stringify({status: 200, media: parseIgMedia(medias)})); }); }catch(err){ res.send(500, JSON.stringify({status: 500, error: err.message})); } } }
Add example of Value to Python list conversion
#! /usr/bin/env python # # values.py # """ An example of using values via Python API """ from opencog.atomspace import AtomSpace, TruthValue from opencog.type_constructors import * a = AtomSpace() set_type_ctor_atomspace(a) a = FloatValue([1.0, 2.0, 3.0]) b = FloatValue([1.0, 2.0, 3.0]) c = FloatValue(1.0) print('{} == {}: {}'.format(a, b, a == b)) print('{} == {}: {}'.format(a, c, a == c)) featureValue = FloatValue([1.0, 2]) print('new value created: {}'.format(featureValue)) boundingBox = ConceptNode('boundingBox') featureKey = PredicateNode('features') boundingBox.set_value(featureKey, featureValue) print('set value to atom: {}'.format(boundingBox)) value = boundingBox.get_value(featureKey) print('get value from atom: {}'.format(value)) list = value.to_list() print('get python list from value: {}'.format(list))
#! /usr/bin/env python # # values.py # """ An example of using values via Python API """ from opencog.atomspace import AtomSpace, TruthValue from opencog.type_constructors import * a = AtomSpace() set_type_ctor_atomspace(a) a = FloatValue([1.0, 2.0, 3.0]) b = FloatValue([1.0, 2.0, 3.0]) c = FloatValue(1.0) print('{} == {}: {}'.format(a, b, a == b)) print('{} == {}: {}'.format(a, c, a == c)) featureValue = FloatValue([1.0, 2]) print('new value created: {}'.format(featureValue)) boundingBox = ConceptNode('boundingBox') featureKey = PredicateNode('features') boundingBox.set_value(featureKey, featureValue) print('set value to atom: {}'.format(boundingBox)) print('get value from atom: {}'.format(boundingBox.get_value(featureKey)))
Add functions to generate python numpy datastructure and write it into generated python file.
import os import json import sys from pprint import pprint def loadJSON(fInput): with open(fInput) as f: return json.load(f) return None if __name__ == '__main__': filePath = 'data/example.json' data = loadJSON(filePath) # check if the data is loaded correctly if data is None: sys.exit('wrong json file'); name = data.get('name') lstTypes = data.get('types') lstFuncs = data.get('functions') from dsFileBuilder import DSFileBuilder dsb = DSFileBuilder(name, lstTypes) dsb.buildDS() dicNumpyDS = dsb.getGeneratedNumpyDS() from kernelFuncBuilder import KernelFuncBuilder kfb = KernelFuncBuilder(name, lstFuncs) kfb.buildKF() dicKFuncDS = kfb.getGeneratedKFuncDS() from oclPyObjGenerator import OCLPyObjGenerator opg = OCLPyObjGenerator(name, dicNumpyDS, dicKFuncDS) opg.generateOCLPyObj() pass
import os import json import sys from pprint import pprint def loadJSON(fInput): with open(fInput) as f: return json.load(f) return None if __name__ == '__main__': filePath = 'data/example.json' data = loadJSON(filePath) # check if the data is loaded correctly if data is None: sys.exit('wrong json file'); name = data.get('name') lstTypes = data.get('types') lstFuncs = data.get('functions') ''' from dsFileBuilder import DSFileBuilder dsb = DSFileBuilder(name, lstTypes) dsb.buildDS() dicNumpyDS = dsb.getGeneratedNumpyDS() from kernelFuncBuilder import KernelFuncBuilder kfb = KernelFuncBuilder(name, lstFuncs) kfb.buildKF() dicKFuncDS = kfb.getGeneratedKFuncDS() from oclPyObjGenerator import OCLPyObjGenerator opg = OCLPyObjGenerator(name, dicNumpyDS, dicKFuncDS) opg.generateOCLPyObj() pass '''
Hide the top level progress node.
/** * */ package org.jmist.framework.services; import java.rmi.RMISecurityManager; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import javax.swing.JDialog; import org.jmist.framework.Job; import org.jmist.framework.reporting.ProgressPanel; /** * @author brad * */ public final class WorkerClient { /** * @param args */ public static void main(String[] args) { if (System.getSecurityManager() == null) { System.setSecurityManager(new RMISecurityManager()); } String host = args.length > 0 ? args[0] : "localhost"; JDialog dialog = new JDialog(); ProgressPanel monitor = new ProgressPanel(); int numberOfCpus = Runtime.getRuntime().availableProcessors(); Executor threadPool = Executors.newFixedThreadPool(numberOfCpus, new BackgroundThreadFactory()); Job workerJob = new ThreadServiceWorkerJob(host, 10000, numberOfCpus, threadPool); monitor.setRootVisible(false); dialog.add(monitor); dialog.setBounds(0, 0, 400, 300); dialog.setVisible(true); workerJob.go(monitor); } }
/** * */ package org.jmist.framework.services; import java.rmi.RMISecurityManager; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import javax.swing.JDialog; import org.jmist.framework.Job; import org.jmist.framework.reporting.ProgressPanel; /** * @author brad * */ public final class WorkerClient { /** * @param args */ public static void main(String[] args) { if (System.getSecurityManager() == null) { System.setSecurityManager(new RMISecurityManager()); } String host = args.length > 0 ? args[0] : "localhost"; JDialog dialog = new JDialog(); ProgressPanel monitor = new ProgressPanel(); int numberOfCpus = Runtime.getRuntime().availableProcessors(); Executor threadPool = Executors.newFixedThreadPool(numberOfCpus, new BackgroundThreadFactory()); Job workerJob = new ThreadServiceWorkerJob(host, 10000, numberOfCpus, threadPool); dialog.add(monitor); dialog.setBounds(0, 0, 400, 300); dialog.setVisible(true); workerJob.go(monitor); } }
Make products\' `active` flag nullable so unit tests pass
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddActiveFieldToProducts extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('products', function (Blueprint $table) { $table->boolean('active')->after('back_order_due_date')->nullable(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('products', function (Blueprint $table) { $table->dropColumn('active'); }); } }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddActiveFieldToProducts extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('products', function (Blueprint $table) { $table->boolean('active')->after('back_order_due_date'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('products', function (Blueprint $table) { $table->dropColumn('active'); }); } }
Rewrite to use http.* for errors, fix function style
/* MEL app backend. Author: Alastair Hughes Contact: <hobbitalastair at yandex dot com> */ package main import ( "net/http" "fmt" "html" ) // Handle a single HTTP request. func Handle(writer http.ResponseWriter, request *http.Request) { fmt.Printf("Handling request for %q\n", html.EscapeString(request.URL.Path)) // Authenticate. name, password, ok := request.BasicAuth() if !ok { http.Error(writer, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return } if name != "" || password != "" { // TODO: Implement checking against the db. http.Error(writer, http.StatusText(http.StatusForbidden), http.StatusForbidden) return } fmt.Fprintf(writer, "%q: authenticated as %s\n", html.EscapeString(request.URL.Path), name) // Parse the URL and return the corresponding value. } func main() { http.ListenAndServe(":8080", http.HandlerFunc(Handle)) } // vim: sw=4 ts=4 noexpandtab
/* MEL app backend Author: Alastair Hughes Contact: <hobbitalastair at yandex dot com> */ package main import ( "net/http" "fmt" "html" ) // Handle a single HTTP request. func MELHandler(writer http.ResponseWriter, request *http.Request) { fmt.Printf("Handling request for %q\n", html.EscapeString(request.URL.Path)) name, password, ok := request.BasicAuth() if !ok { writer.WriteHeader(401) // Auth required return } if name != "" || password != "" { // TODO: Implement checking against the db. writer.WriteHeader(403) // Invalid auth return } fmt.Fprintf(writer, "%q: authenticated as %s\n", html.EscapeString(request.URL.Path), name) } func main() { http.ListenAndServe(":8080", http.HandlerFunc(MELHandler)) } // vim: sw=4 ts=4 noexpandtab
Remove reference to Closure, expose State instead Closure was removed in 32e3b21.
/** * The MIT License (MIT) * Copyright (c) 2015-present Dmitry Soshnikov <dmitry.soshnikov@gmail.com> */ // To require local modules from root. global.ROOT = __dirname + '/'; // Tokenizer. export {default as Tokenizer} from './tokenizer'; // Grammar classes. export {default as Grammar} from './grammar/grammar'; export {default as GrammarSymbol} from './grammar/grammar-symbol'; export {default as LexRule} from './grammar/lex-rule'; export {default as Production} from './grammar/production'; // Sets generator. export {default as SetsGenerator} from './sets-generator'; // LR parsing. export {default as CanonicalCollection} from './lr/canonical-collection'; export {default as State} from './lr/state'; export {default as LRItem} from './lr/lr-item'; export {default as LRParser} from './lr/lr-parser'; export {default as LRParsingTable} from './lr/lr-parsing-table'; // LL parsing. export {default as LLParsingTable} from './ll/ll-parsing-table';
/** * The MIT License (MIT) * Copyright (c) 2015-present Dmitry Soshnikov <dmitry.soshnikov@gmail.com> */ // To require local modules from root. global.ROOT = __dirname + '/'; // Tokenizer. export {default as Tokenizer} from './tokenizer'; // Grammar classes. export {default as Grammar} from './grammar/grammar'; export {default as GrammarSymbol} from './grammar/grammar-symbol'; export {default as LexRule} from './grammar/lex-rule'; export {default as Production} from './grammar/production'; // Sets generator. export {default as SetsGenerator} from './sets-generator'; // LR parsing. export {default as CanonicalCollection} from './lr/canonical-collection'; export {default as Closure} from './lr/closure'; export {default as LRItem} from './lr/lr-item'; export {default as LRParser} from './lr/lr-parser'; export {default as LRParsingTable} from './lr/lr-parsing-table'; // LL parsing. export {default as LLParsingTable} from './ll/ll-parsing-table';
Update MathJax URL to 2.7.1
# This file is part of python-markups module # License: BSD # Copyright: (C) Dmitry Shachnev, 2012-2017 import os.path # Some common constants and functions (LANGUAGE_HOME_PAGE, MODULE_HOME_PAGE, SYNTAX_DOCUMENTATION) = range(3) CONFIGURATION_DIR = (os.getenv('XDG_CONFIG_HOME') or os.getenv('APPDATA') or os.path.expanduser('~/.config')) MATHJAX_LOCAL_URL = 'file:///usr/share/javascript/mathjax/MathJax.js' MATHJAX_WEB_URL = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js' PYGMENTS_STYLE = 'default' def get_pygments_stylesheet(selector, style=None): if style is None: style = PYGMENTS_STYLE if style == '': return '' try: from pygments.formatters import HtmlFormatter except ImportError: return '' else: return HtmlFormatter(style=style).get_style_defs(selector) + '\n' def get_mathjax_url(webenv): if os.path.exists(MATHJAX_LOCAL_URL[7:]) and not webenv: return MATHJAX_LOCAL_URL else: return MATHJAX_WEB_URL
# This file is part of python-markups module # License: BSD # Copyright: (C) Dmitry Shachnev, 2012-2017 import os.path # Some common constants and functions (LANGUAGE_HOME_PAGE, MODULE_HOME_PAGE, SYNTAX_DOCUMENTATION) = range(3) CONFIGURATION_DIR = (os.getenv('XDG_CONFIG_HOME') or os.getenv('APPDATA') or os.path.expanduser('~/.config')) MATHJAX_LOCAL_URL = 'file:///usr/share/javascript/mathjax/MathJax.js' MATHJAX_WEB_URL = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js' PYGMENTS_STYLE = 'default' def get_pygments_stylesheet(selector, style=None): if style is None: style = PYGMENTS_STYLE if style == '': return '' try: from pygments.formatters import HtmlFormatter except ImportError: return '' else: return HtmlFormatter(style=style).get_style_defs(selector) + '\n' def get_mathjax_url(webenv): if os.path.exists(MATHJAX_LOCAL_URL[7:]) and not webenv: return MATHJAX_LOCAL_URL else: return MATHJAX_WEB_URL
Fix formatting tests: cfloat and cdouble as well as np.float and np.double are the same; make sure we test 4 bytes float.
import numpy as np from numpy.testing import * def check_float_type(tp): for x in [0, 1,-1, 1e10, 1e20] : assert_equal(str(tp(x)), str(float(x))) def test_float_types(): """ Check formatting. This is only for the str function, and only for simple types. The precision of np.float and np.longdouble aren't the same as the python float precision. """ for t in [np.float32, np.double, np.longdouble] : yield check_float_type, t def check_complex_type(tp): for x in [0, 1,-1, 1e10, 1e20] : assert_equal(str(tp(x)), str(complex(x))) assert_equal(str(tp(x*1j)), str(complex(x*1j))) assert_equal(str(tp(x + x*1j)), str(complex(x + x*1j))) def test_complex_types(): """Check formatting. This is only for the str function, and only for simple types. The precision of np.float and np.longdouble aren't the same as the python float precision. """ for t in [np.complex64, np.cdouble, np.clongdouble] : yield check_complex_type, t if __name__ == "__main__": run_module_suite()
import numpy as np from numpy.testing import * def check_float_type(tp): for x in [0, 1,-1, 1e10, 1e20] : assert_equal(str(tp(x)), str(float(x))) def test_float_types(): """ Check formatting. This is only for the str function, and only for simple types. The precision of np.float and np.longdouble aren't the same as the python float precision. """ for t in [np.float, np.double, np.longdouble] : yield check_float_type, t def check_complex_type(tp): for x in [0, 1,-1, 1e10, 1e20] : assert_equal(str(tp(x)), str(complex(x))) assert_equal(str(tp(x*1j)), str(complex(x*1j))) assert_equal(str(tp(x + x*1j)), str(complex(x + x*1j))) def test_complex_types(): """Check formatting. This is only for the str function, and only for simple types. The precision of np.float and np.longdouble aren't the same as the python float precision. """ for t in [np.cfloat, np.cdouble, np.clongdouble] : yield check_complex_type, t if __name__ == "__main__": run_module_suite()
Fix bug for social authentication
'use strict'; /** * @ngdoc function * @name com.module.core.controller:MainCtrl * @description Login Controller * @requires $scope * @requires $state * @requires $location * @requires CoreService * @requires AppAuth * @requires User * @requires gettextCatalog **/ angular.module('com.module.core') .controller('MainCtrl', function($scope, $rootScope, $state, $location, CoreService, User, gettextCatalog, AppAuth) { AppAuth.ensureHasCurrentUser(function(user) { $scope.currentUser = user; }); $scope.menuoptions = $rootScope.menu; $scope.logout = function() { User.logout(function() { $state.go('login'); CoreService.toastSuccess(gettextCatalog.getString('Logged out'), gettextCatalog.getString('You are logged out!')); }); }; });
'use strict'; /** * @ngdoc function * @name com.module.core.controller:MainCtrl * @description Login Controller * @requires $scope * @requires $state * @requires $location * @requires CoreService * @requires AppAuth * @requires User * @requires gettextCatalog **/ angular.module('com.module.core') .controller('MainCtrl', function($scope, $rootScope, $state, $location, CoreService, User, gettextCatalog) { $scope.currentUser = User.getCurrent(); $scope.menuoptions = $rootScope.menu; $scope.logout = function() { User.logout(function() { $state.go('login'); CoreService.toastSuccess(gettextCatalog.getString('Logged out'), gettextCatalog.getString('You are logged out!')); }); }; });
Change model createdAt and updatedAt fields to default
"use strict"; module.exports = function(sequelize, DataTypes) { var Client = sequelize.define('Client', { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, secret: DataTypes.STRING, //redirect_uris: DataTypes.STRING, name: DataTypes.STRING, //logo_uri //contacts //tos_uri //policy_uri //token_endpoint_auth_method //scope //grant_types //response_types //jwks_uri software_id: DataTypes.STRING, software_version: DataTypes.STRING, ip: DataTypes.STRING }, { associate: function(models) { Client.hasMany(models.AccessToken); } }); return Client; }
"use strict"; module.exports = function(sequelize, DataTypes) { var Client = sequelize.define('Client', { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, secret: DataTypes.STRING, //redirect_uris: DataTypes.STRING, name: DataTypes.STRING, //logo_uri //contacts //tos_uri //policy_uri //token_endpoint_auth_method //scope //grant_types //response_types //jwks_uri software_id: DataTypes.STRING, software_version: DataTypes.STRING, ip: DataTypes.STRING }, { updatedAt: 'last_update', createdAt: 'date_of_creation', associate: function(models) { Client.hasMany(models.AccessToken); } }); return Client; }
Insert explicit cast to malloc implementation
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import import math import unittest from numba2 import jit, types, int32, float64, Type, cast from numba2.runtime import ffi # ______________________________________________________________________ class TestFFI(unittest.TestCase): def test_malloc(self): @jit def f(): p = ffi.malloc(cast(2, types.int64), types.int32) p[0] = 4 p[1] = 5 return p p = f() self.assertEqual(p[0], 4) self.assertEqual(p[1], 5) def test_sizeof(self): def func(x): return ffi.sizeof(x) def apply(signature, arg): return jit(signature)(func)(arg) self.assertEqual(apply('int32 -> int64', 10), 4) self.assertEqual(apply('Type[int32] -> int64', int32), 4) self.assertEqual(apply('float64 -> int64', 10.0), 8) self.assertEqual(apply('Type[float64] -> int64', float64), 8) # ______________________________________________________________________ if __name__ == "__main__": unittest.main()
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import import math import unittest from numba2 import jit, types, int32, float64, Type from numba2.runtime import ffi # ______________________________________________________________________ class TestFFI(unittest.TestCase): def test_malloc(self): raise unittest.SkipTest @jit def f(): p = ffi.malloc(2, types.int32) p[0] = 4 p[1] = 5 return p p = f() self.assertEqual(p[0], 4) self.assertEqual(p[1], 5) def test_sizeof(self): def func(x): return ffi.sizeof(x) def apply(signature, arg): return jit(signature)(func)(arg) self.assertEqual(apply('int32 -> int64', 10), 4) self.assertEqual(apply('Type[int32] -> int64', int32), 4) self.assertEqual(apply('float64 -> int64', 10.0), 8) self.assertEqual(apply('Type[float64] -> int64', float64), 8) # ______________________________________________________________________ if __name__ == "__main__": unittest.main()
Remove println from signalablelogger test Signed-off-by: Charlie Vieth <ea3f0b85bda195c42ceb97da0f596f9d6d014e12@pivotal.io>
package agentlogger_test import ( "bytes" "os" "syscall" "github.com/cloudfoundry/bosh-agent/infrastructure/agentlogger" "github.com/cloudfoundry/bosh-utils/logger" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Signalable logger debug", func() { Describe("when SIGSEGV is recieved", func() { It("it dumps all goroutines to stderr", func() { errBuf := new(bytes.Buffer) outBuf := new(bytes.Buffer) signalChannel := make(chan os.Signal, 1) writerLogger := logger.NewWriterLogger(logger.LevelError, outBuf, errBuf) _, doneChannel := agentlogger.NewSignalableLogger(writerLogger, signalChannel) signalChannel <- syscall.SIGSEGV <-doneChannel Expect(errBuf).To(ContainSubstring("Dumping goroutines")) Expect(errBuf).To(MatchRegexp(`goroutine (\d+) \[(syscall|running)\]`)) }) }) })
package agentlogger_test import ( "bytes" "fmt" "os" "syscall" "github.com/cloudfoundry/bosh-agent/infrastructure/agentlogger" "github.com/cloudfoundry/bosh-utils/logger" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Signalable logger debug", func() { Describe("when SIGSEGV is recieved", func() { It("it dumps all goroutines to stderr", func() { errBuf := new(bytes.Buffer) outBuf := new(bytes.Buffer) signalChannel := make(chan os.Signal, 1) writerLogger := logger.NewWriterLogger(logger.LevelError, outBuf, errBuf) _, doneChannel := agentlogger.NewSignalableLogger(writerLogger, signalChannel) signalChannel <- syscall.SIGSEGV <-doneChannel fmt.Println(errBuf) Expect(errBuf).To(ContainSubstring("Dumping goroutines")) Expect(errBuf).To(MatchRegexp(`goroutine (\d+) \[(syscall|running)\]`)) }) }) })
Use Logo::nails for Nails logo
<div class="email-debugger"> <div class="header"> This page is viewable in development environments only. <a href="http://docs.nailsapp.co.uk"> <img src="<?=\Nails\Common\Helper\Logo::nails()?>" id="nailsLogo" /> </a> </div> <div class="sub-header"> <div class="column variables">Variables</div> <div class="column html">HTML</div> <div class="column text">TEXT</div> </div> <div class="body"> <div class="column variables"> <pre><?=print_r($oEmail->data, true);?></pre> </div> <div class="column html"> <iframe srcdoc="<?=htmlentities($oEmail->body->html)?>"></iframe> </div> <div class="column text"> <pre><?=$oEmail->body->text?></pre> </div> </div> </div>
<div class="email-debugger"> <div class="header"> This page is viewable in development environments only. <a href="http://docs.nailsapp.co.uk"> <img src="<?=NAILS_ASSETS_URL?>img/nails-logo.png" id="nailsLogo"/> </a> </div> <div class="sub-header"> <div class="column variables">Variables</div> <div class="column html">HTML</div> <div class="column text">TEXT</div> </div> <div class="body"> <div class="column variables"> <pre><?=print_r($oEmail->data, true);?></pre> </div> <div class="column html"> <iframe srcdoc="<?=htmlentities($oEmail->body->html)?>"></iframe> </div> <div class="column text"> <pre><?=$oEmail->body->text?></pre> </div> </div> </div>
Add a logging wrapper around the file server.
package main import ( "flag" "fmt" "net/http" "os" "github.com/gorilla/handlers" ) const VERSION = "0.1.0" var clientDir string func init() { clientEnv := os.Getenv("CLIENT") flag.StringVar(&clientDir, "client", clientEnv, "the directory where the client data is stored") } func main() { flag.Parse() fmt.Printf("resolutionizerd %s starting...\n", VERSION) fmt.Printf("listening on port %s\n", os.Getenv("PORT")) if clientDir == "" { clientDir = os.Getenv("CLIENT") } fmt.Printf("client root: %s\n", clientDir) if _, err := os.Stat(clientDir); err != nil { fmt.Println(err) os.Exit(1) } http.Handle("/", handlers.CombinedLoggingHandler(os.Stdout, http.FileServer(http.Dir(clientDir)))) if err := http.ListenAndServe(":"+os.Getenv("PORT"), nil); err != nil { fmt.Println(err) os.Exit(1) } }
package main import ( "flag" "fmt" "net/http" "os" ) const VERSION = "0.1.0" var clientDir string func init() { clientEnv := os.Getenv("CLIENT") flag.StringVar(&clientDir, "client", clientEnv, "the directory where the client data is stored") } func main() { flag.Parse() fmt.Printf("resolutionizerd %s starting...\n", VERSION) fmt.Printf("listening on port %s\n", os.Getenv("PORT")) if clientDir == "" { clientDir = os.Getenv("CLIENT") } fmt.Printf("client root: %s\n", clientDir) if _, err := os.Stat(clientDir); err != nil { fmt.Println(err) os.Exit(1) } http.Handle("/", http.FileServer(http.Dir(clientDir))) if err := http.ListenAndServe(":"+os.Getenv("PORT"), nil); err != nil { fmt.Println(err) os.Exit(1) } }
Add a few unit tests Signed-off-by: David Gageot <aa743a0aaec8f7d7a1f01442503957f4d7a2d634@gageot.net>
/* Copyright 2018 The Skaffold Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package local import ( "context" "testing" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" "github.com/GoogleContainerTools/skaffold/testutil" ) func TestBazelBin(t *testing.T) { defer func(c util.Command) { util.DefaultExecCommand = c }(util.DefaultExecCommand) util.DefaultExecCommand = testutil.NewFakeCmdOut( "bazel info bazel-bin", "/absolute/path/bin\n", nil, ) bazelBin, err := bazelBin(context.Background(), ".") testutil.CheckErrorAndDeepEqual(t, false, err, "/absolute/path/bin", bazelBin) } func TestBuildTarPath(t *testing.T) { buildTarget := "//:skaffold_example.tar" tarPath := buildTarPath(buildTarget) testutil.CheckDeepEqual(t, "skaffold_example.tar", tarPath) } func TestBuildImageTag(t *testing.T) { buildTarget := "//:skaffold_example.tar" imageTag := buildImageTag(buildTarget) testutil.CheckDeepEqual(t, ":skaffold_example", imageTag) }
/* Copyright 2018 The Skaffold Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package local import ( "context" "testing" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" "github.com/GoogleContainerTools/skaffold/testutil" ) func TestBazelBin(t *testing.T) { defer func(c util.Command) { util.DefaultExecCommand = c }(util.DefaultExecCommand) util.DefaultExecCommand = testutil.NewFakeCmdOut( "bazel info bazel-bin", "/absolute/path/bin\n", nil, ) bazelBin, err := bazelBin(context.Background(), ".") testutil.CheckErrorAndDeepEqual(t, false, err, "/absolute/path/bin", bazelBin) }
Add default resolver to api router
package router import ( "github.com/micro/go-micro/v2/api/resolver" "github.com/micro/go-micro/v2/api/resolver/vpath" "github.com/micro/go-micro/v2/registry" ) type Options struct { Handler string Registry registry.Registry Resolver resolver.Resolver } type Option func(o *Options) func NewOptions(opts ...Option) Options { options := Options{ Handler: "meta", Registry: registry.DefaultRegistry, } for _, o := range opts { o(&options) } if options.Resolver == nil { options.Resolver = vpath.NewResolver( resolver.WithHandler(options.Handler), ) } return options } func WithHandler(h string) Option { return func(o *Options) { o.Handler = h } } func WithRegistry(r registry.Registry) Option { return func(o *Options) { o.Registry = r } } func WithResolver(r resolver.Resolver) Option { return func(o *Options) { o.Resolver = r } }
package router import ( "github.com/micro/go-micro/v2/api/resolver" "github.com/micro/go-micro/v2/registry" ) type Options struct { Handler string Registry registry.Registry Resolver resolver.Resolver } type Option func(o *Options) func NewOptions(opts ...Option) Options { options := Options{ Handler: "meta", Registry: registry.DefaultRegistry, } for _, o := range opts { o(&options) } return options } func WithHandler(h string) Option { return func(o *Options) { o.Handler = h } } func WithRegistry(r registry.Registry) Option { return func(o *Options) { o.Registry = r } } func WithResolver(r resolver.Resolver) Option { return func(o *Options) { o.Resolver = r } }
Set public folder as the content base for webpack dev server
var webpack = require('webpack'); module.exports = { entry: { app: './src/js/app.jsx', vendors: ['react', 'react-dom', 'react-router', 'redux', 'redux-thunk', 'es6-promise-polyfill'] }, output: { path: './public/js/', publicPath: '/js/', filename: 'app.js' }, module: { preLoaders: [ { test: /\.jsx?$/, loaders: ['eslint'] } ], loaders: [ { test: /\.jsx?$/, loader: 'babel', exclude: '/node_modules/', query: { cacheDirectory: true, presets: ['react', 'es2015'] } } ] }, resolve: { extensions: ['', '.js', '.jsx'] }, devServer: { historyApiFallback: true, contentBase: './public' }, plugins: [ new webpack.optimize.CommonsChunkPlugin('vendors', 'vendors.js'), new webpack.optimize.UglifyJsPlugin({ sourceMap: true, minimize: true }) ] };
var webpack = require('webpack'); module.exports = { entry: { app: './src/js/app.jsx', vendors: ['react', 'react-dom', 'react-router', 'redux', 'redux-thunk', 'es6-promise-polyfill'] }, output: { path: './public/js/', publicPath: '/js/', filename: 'app.js' }, module: { preLoaders: [ { test: /\.jsx?$/, loaders: ['eslint'] } ], loaders: [ { test: /\.jsx?$/, loader: 'babel', exclude: '/node_modules/', query: { cacheDirectory: true, presets: ['react', 'es2015'] } } ] }, resolve: { extensions: ['', '.js', '.jsx'] }, devServer: { historyApiFallback: true }, plugins: [ new webpack.optimize.CommonsChunkPlugin('vendors', 'vendors.js'), new webpack.optimize.UglifyJsPlugin({ sourceMap: true, minimize: true }) ] };
Send bbox for Point features
var mongoose = require('mongoose'), _ = require('cloneextend'), adHocModels = {}; var adHocModel = function(collectionName, Schema, options) { if (!adHocModels[collectionName]) { var options = options || {}; if (options.strict == undefined) { options.strict = false; } var Schema = Schema || new mongoose.Schema({}, options); adHocModels[collectionName] = mongoose.model( 'adhoc_' + new mongoose.Types.ObjectId().toString(), Schema, collectionName); } return adHocModels[collectionName]; }; /* Modifies the JSON object to be sent to the client as GeoJSON */ var toGeoJSON = function(obj) { delete obj.bounds2d; if (obj.bbox && !obj.bbox.length && obj.geometry.type == 'Point') { obj.bbox = [ obj.geometry.coordinates[0], obj.geometry.coordinates[1], obj.geometry.coordinates[0], obj.geometry.coordinates[1] ]; } return obj; }; module.exports = { adHocModel: adHocModel, toGeoJSON: toGeoJSON };
var mongoose = require('mongoose'), _ = require('cloneextend'), adHocModels = {}; var adHocModel = function(collectionName, Schema, options) { if (!adHocModels[collectionName]) { var options = options || {}; if (options.strict == undefined) { options.strict = false; } var Schema = Schema || new mongoose.Schema({}, options); adHocModels[collectionName] = mongoose.model( 'adhoc_' + new mongoose.Types.ObjectId().toString(), Schema, collectionName); } return adHocModels[collectionName]; }; /* Modifies the JSON object to be sent to the client as GeoJSON */ var toGeoJSON = function(obj) { delete obj.bounds2d; return obj; }; module.exports = { adHocModel: adHocModel, toGeoJSON: toGeoJSON };
Remove trove classifier for python 3.5
from setuptools import find_packages, setup VERSION = '1.0.0' setup( name='django-fakery', version=VERSION, url='https://github.com/fcurella/django-factory/', author='Flavio Curella', author_email='flavio.curella@gmail.com', description='A model instances generator for Django', license='MIT', packages=find_packages(exclude=['*.tests']), platforms=["any"], classifiers=[ 'Development Status :: 4 - Beta', 'Framework :: Django', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', ], install_requires=[ "fake-factory==0.5.3", "Django>=1.7", ], test_suite='django_fakery.tests.runtests.runtests', )
from setuptools import find_packages, setup VERSION = '1.0.0' setup( name='django-fakery', version=VERSION, url='https://github.com/fcurella/django-factory/', author='Flavio Curella', author_email='flavio.curella@gmail.com', description='A model instances generator for Django', license='MIT', packages=find_packages(exclude=['*.tests']), platforms=["any"], classifiers=[ 'Development Status :: 4 - Beta', 'Framework :: Django', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], install_requires=[ "fake-factory==0.5.3", "Django>=1.7", ], test_suite='django_fakery.tests.runtests.runtests', )
Include `config/environment.js` values into application.
import Ember from 'ember'; import { dasherize } from '@ember/string'; import { merge } from '@ember/polyfills'; import { setRegistry } from '../../resolver'; import { setResolver, setApplication } from 'ember-test-helpers'; import require from 'require'; import App from '../../app'; import config from '../../config/environment'; const AppConfig = merge({ autoboot: false }, config.APP); export const application = App.create(AppConfig); export const resolver = application.Resolver.create({ namespace: application, isResolverFromTestHelpers: true, }); setResolver(resolver); setApplication(application); export function setResolverRegistry(registry) { setRegistry(registry); } export default { create() { return resolver; }, }; export function createCustomResolver(registry) { if (require.has('ember-native-dom-event-dispatcher')) { // the raw value looked up by ember and these test helpers registry['event_dispatcher:main'] = require('ember-native-dom-event-dispatcher').default; // the normalized value looked up registry['event-dispatcher:main'] = require('ember-native-dom-event-dispatcher').default; } var Resolver = Ember.DefaultResolver.extend({ registry: null, resolve(fullName) { return this.registry[fullName]; }, normalize(fullName) { return dasherize(fullName); }, }); return Resolver.create({ registry, namespace: {} }); }
import Ember from 'ember'; import { dasherize } from '@ember/string'; import { setRegistry } from '../../resolver'; import { setResolver, setApplication } from 'ember-test-helpers'; import require from 'require'; import App from '../../app'; export const application = App.create({ autoboot: false }); export const resolver = application.Resolver.create({ namespace: application, isResolverFromTestHelpers: true, }); setResolver(resolver); setApplication(application); export function setResolverRegistry(registry) { setRegistry(registry); } export default { create() { return resolver; }, }; export function createCustomResolver(registry) { if (require.has('ember-native-dom-event-dispatcher')) { // the raw value looked up by ember and these test helpers registry['event_dispatcher:main'] = require('ember-native-dom-event-dispatcher').default; // the normalized value looked up registry['event-dispatcher:main'] = require('ember-native-dom-event-dispatcher').default; } var Resolver = Ember.DefaultResolver.extend({ registry: null, resolve(fullName) { return this.registry[fullName]; }, normalize(fullName) { return dasherize(fullName); }, }); return Resolver.create({ registry, namespace: {} }); }
Allow PHP 8.2 in CheckSystemEnvironment
<?php namespace wcf\http\middleware; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; use wcf\system\exception\NamedUserException; use wcf\system\request\RequestHandler; use wcf\system\WCF; /** * Checks whether the system environment is unacceptable and prevents processing in that case. * * @author Tim Duesterhus * @copyright 2001-2022 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\Http\Middleware * @since 5.6 */ final class CheckSystemEnvironment implements MiddlewareInterface { /** * @inheritDoc */ public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { if (!RequestHandler::getInstance()->isACPRequest()) { if (!(80100 <= \PHP_VERSION_ID && \PHP_VERSION_ID <= 80299)) { \header('HTTP/1.1 500 Internal Server Error'); throw new NamedUserException(WCF::getLanguage()->get('wcf.global.incompatiblePhpVersion')); } } return $handler->handle($request); } }
<?php namespace wcf\http\middleware; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; use wcf\system\exception\NamedUserException; use wcf\system\request\RequestHandler; use wcf\system\WCF; /** * Checks whether the system environment is unacceptable and prevents processing in that case. * * @author Tim Duesterhus * @copyright 2001-2022 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\Http\Middleware * @since 5.6 */ final class CheckSystemEnvironment implements MiddlewareInterface { /** * @inheritDoc */ public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { if (!RequestHandler::getInstance()->isACPRequest()) { if (!(80100 <= \PHP_VERSION_ID && \PHP_VERSION_ID <= 80199)) { \header('HTTP/1.1 500 Internal Server Error'); throw new NamedUserException(WCF::getLanguage()->get('wcf.global.incompatiblePhpVersion')); } } return $handler->handle($request); } }
Send the minimal amount of DOM to the client
/** * RouterHistoryContainer is already connected to the router state, so you only * have to pass in `routes`. It also responds to history/click events and * dispatches routeTo actions appropriately. */ import React from 'react'; import createReactClass from 'create-react-class'; import PropTypes from 'prop-types'; import Router from './Router'; import connectRouter from './connectRouter'; import History from './History'; const RouterHistoryContainer = createReactClass({ propTypes: { routes: PropTypes.object.isRequired, }, onChangeAddress(url, state) { this.props.routeTo(url, { state, isHistoryChange: true, }); }, render() { const { router } = this.props; const url = router.current ? router.current.url : null; const state = router.current ? router.current.state : undefined; const replace = router.current ? router.current.replace : undefined; return [ <Router key="router" {...this.props} router={router} />, <History key="history" history={this.props.history} url={url} state={state} replace={replace} isWaiting={!!router.next} onChange={this.onChangeAddress} />, ]; }, }); export default connectRouter(RouterHistoryContainer);
/** * RouterHistoryContainer is already connected to the router state, so you only * have to pass in `routes`. It also responds to history/click events and * dispatches routeTo actions appropriately. */ import React from 'react'; import createReactClass from 'create-react-class'; import PropTypes from 'prop-types'; import Router from './Router'; import connectRouter from './connectRouter'; import History from './History'; const RouterHistoryContainer = createReactClass({ propTypes: { routes: PropTypes.object.isRequired }, onChangeAddress(url, state) { this.props.routeTo(url, { state, isHistoryChange: true }); }, render() { const { router } = this.props; const url = router.current ? router.current.url : null; const state = router.current ? router.current.state : undefined; const replace = router.current ? router.current.replace : undefined; return ( <div> <Router {...this.props} router={router}/> <History history={this.props.history} url={url} state={state} replace={replace} isWaiting={!!router.next} onChange={this.onChangeAddress} /> </div> ); } }); export default connectRouter(RouterHistoryContainer);
Update with reference to global nav partial
var _ = require('lodash') var fs = require('fs') var filesize = require('filesize') var cssstats = require('cssstats') var module = require('tachyons-typography/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-typography/tachyons-typography.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_typography.css', 'utf8') var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8') var template = fs.readFileSync('./templates/docs/measure/garamond/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS, navDocs: navDocs }) fs.writeFileSync('./docs/typography/measure/garamond/index.html', html)
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var cssstats = require('cssstats') var module = require('tachyons-typography/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-typography/tachyons-typography.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_typography.css', 'utf8') var template = fs.readFileSync('./templates/docs/measure/garamond/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS }) fs.writeFileSync('./docs/typography/measure/garamond/index.html', html)
Make sure the JerseryClient thread pools are sized.
package com.yammer.dropwizard.client; import javax.validation.constraints.Max; import javax.validation.constraints.Min; public class JerseyClientConfiguration extends HttpClientConfiguration { // TODO: 11/16/11 <coda> -- validate minThreads <= maxThreads @Max(16 * 1024) @Min(1) private int minThreads = 1; @Max(16 * 1024) @Min(1) private int maxThreads = 128; public int getMinThreads() { return minThreads; } public void setMinThreads(int minThreads) { this.minThreads = minThreads; } public int getMaxThreads() { return maxThreads; } public void setMaxThreads(int maxThreads) { this.maxThreads = maxThreads; } }
package com.yammer.dropwizard.client; import javax.validation.constraints.Max; import javax.validation.constraints.Min; public class JerseyClientConfiguration extends HttpClientConfiguration { // TODO: 11/16/11 <coda> -- validate minThreads <= maxThreads @Max(16 * 1024) @Min(1) private int minThreads; @Max(16 * 1024) @Min(1) private int maxThreads; public int getMinThreads() { return minThreads; } public void setMinThreads(int minThreads) { this.minThreads = minThreads; } public int getMaxThreads() { return maxThreads; } public void setMaxThreads(int maxThreads) { this.maxThreads = maxThreads; } }
Add process to exit function
'use strict'; const exec = require('child_process').exec; const path = require('path'); const javahome = require('find-java-home'); const os = require('os'); const command = (command) => { let child = exec(command, function (error, stdout, stderr) { if (error) { console.error(`exec error: ${error}`); return; } console.log(stdout, stderr); }); }; javahome((err, home) => { if(err) { console.error(err); process.exit(1); } command('"' + path.join(home.trim(), 'bin', 'javac') + '" -classpath "' + path.join(__dirname, 'src-library/*') + (os.platform() == 'win32' ? ';' : '') + '" -d "' + path.join(__dirname, 'out/production/node-pdfbox') + '" ' + path.join(__dirname, 'src/main/java/br/com/appmania/*.java')); });
'use strict'; const exec = require('child_process').exec; const path = require('path'); const javahome = require('find-java-home'); const os = require('os'); const command = (command) => { let child = exec(command, function (error, stdout, stderr) { if (error) { console.error(`exec error: ${error}`); return; } console.log(stdout, stderr); }); }; javahome((err, home) => { if(err) { console.error(err); exit(1); } command('"' + path.join(home.trim(), 'bin', 'javac') + '" -classpath "' + path.join(__dirname, 'src-library/*') + (os.platform() == 'win32' ? ';' : '') + '" -d "' + path.join(__dirname, 'out/production/node-pdfbox') + '" ' + path.join(__dirname, 'src/main/java/br/com/appmania/*.java')); });
Increase timeout for bunyan test Build can sometimes take a long time…
'use strict'; var path = require('path'); var expect = require('thehelp-test').expect; var util = require('./util'); describe('bunyan', function() { var child; before(function(done) { this.timeout(30000); util.setupScenario('bunyan', function(err) { if (err) { throw err; } child = util.startProcess( path.join(__dirname, '../../scenarios/bunyan/go.js')); child.on('close', function() { done(); }); }); }); after(function(done) { util.cleanupScenario('bunyan', done); }); it('does not log verbose by default', function() { expect(child.stdoutResult).not.to.match(/default verbose text/); }); it('should have logged info', function() { expect(child.stdoutResult).to.match(/info text { data: { yes:/); }); it('should have logged warn and printed out the supplied callback', function() { expect(child.stdoutResult).to.match(/warn text/); expect(child.stdoutResult).to.match(/jshint unused/); }); it('should have logged error', function() { expect(child.stdoutResult).to.match(/error interpolation/); }); it('logs custom verbose level', function() { expect(child.stdoutResult).to.match(/custom verbose text/); }); });
'use strict'; var path = require('path'); var expect = require('thehelp-test').expect; var util = require('./util'); describe('bunyan', function() { var child; before(function(done) { this.timeout(10000); util.setupScenario('bunyan', function(err) { if (err) { throw err; } child = util.startProcess( path.join(__dirname, '../../scenarios/bunyan/go.js')); child.on('close', function() { done(); }); }); }); after(function(done) { util.cleanupScenario('bunyan', done); }); it('does not log verbose by default', function() { expect(child.stdoutResult).not.to.match(/default verbose text/); }); it('should have logged info', function() { expect(child.stdoutResult).to.match(/info text { data: { yes:/); }); it('should have logged warn and printed out the supplied callback', function() { expect(child.stdoutResult).to.match(/warn text/); expect(child.stdoutResult).to.match(/jshint unused/); }); it('should have logged error', function() { expect(child.stdoutResult).to.match(/error interpolation/); }); it('logs custom verbose level', function() { expect(child.stdoutResult).to.match(/custom verbose text/); }); });
Fix code dir for docker container
import DockerContainer from './DockerContainer.js' import { checkDockerDaemon } from '../../../utils/index.js' export default class DockerRunner { #codeDir = null #container = null constructor(funOptions, env, dockerOptions) { const { codeDir, functionKey, handler, runtime, layers, provider, servicePath, } = funOptions this.#codeDir = codeDir if ( dockerOptions.hostServicePath && this.#codeDir.startsWith(servicePath) ) { this.#codeDir = this.#codeDir.replace( servicePath, dockerOptions.hostServicePath, ) } this.#container = new DockerContainer( env, functionKey, handler, runtime, layers, provider, dockerOptions, ) } cleanup() { if (this.#container) { return this.#container.stop() } return undefined } // context will be generated in container async run(event) { // FIXME TODO this should run only once -> static private await checkDockerDaemon() if (!this.#container.isRunning) { await this.#container.start(this.#codeDir) } return this.#container.request(event) } }
import DockerContainer from './DockerContainer.js' import { checkDockerDaemon } from '../../../utils/index.js' export default class DockerRunner { #codeDir = null #container = null constructor(funOptions, env, dockerOptions) { const { codeDir, functionKey, handler, runtime, layers, provider, } = funOptions this.#codeDir = codeDir if ( dockerOptions.hostServicePath && this.#codeDir === funOptions.servicePath ) { this.#codeDir = dockerOptions.hostServicePath } this.#container = new DockerContainer( env, functionKey, handler, runtime, layers, provider, dockerOptions, ) } cleanup() { if (this.#container) { return this.#container.stop() } return undefined } // context will be generated in container async run(event) { // FIXME TODO this should run only once -> static private await checkDockerDaemon() if (!this.#container.isRunning) { await this.#container.start(this.#codeDir) } return this.#container.request(event) } }
Fix issue with missing var
package com.xdrop.passlock.core; import org.apache.commons.codec.binary.Base64; import com.xdrop.passlock.crypto.EncryptionModel; import com.xdrop.passlock.crypto.aes.AESEncryptionData; import com.xdrop.passlock.crypto.aes.AESEncryptionModel; import com.xdrop.passlock.datasource.Datasource; import com.xdrop.passlock.datasource.sqlite.SQLiteAESDatasource; import com.xdrop.passlock.model.EncryptionData; import com.xdrop.passlock.model.PasswordEntry; import com.xdrop.passlock.utils.ByteUtils; public class PasswordManager { public void addPassword(String description, char[] newPassword, char[] masterPass, String reference){ EncryptionModel<AESEncryptionData> encryptionModel = new AESEncryptionModel(); AESEncryptionData encryptionData = encryptionModel.encrypt(ByteUtils.getBytes(newPassword), masterPass); PasswordEntry<AESEncryptionData> passwordEntry = new PasswordEntry<>(); passwordEntry.setDescription(description); passwordEntry.setRef(reference); passwordEntry.setEncryptionData(encryptionData); Datasource<AESEncryptionData> datasource = new SQLiteAESDatasource(); datasource.addPass(reference, passwordEntry); byte[] b64 = Base64.encodeBase64(encryptionData.getEncryptedPayload()); System.out.println(new String(b64)); } }
package com.xdrop.passlock.core; import org.apache.commons.codec.binary.Base64; import com.xdrop.passlock.crypto.EncryptionModel; import com.xdrop.passlock.crypto.aes.AESEncryptionData; import com.xdrop.passlock.crypto.aes.AESEncryptionModel; import com.xdrop.passlock.datasource.Datasource; import com.xdrop.passlock.datasource.sqlite.SQLiteAESDatasource; import com.xdrop.passlock.model.EncryptionData; import com.xdrop.passlock.model.PasswordEntry; import com.xdrop.passlock.utils.ByteUtils; public class PasswordManager { public void addPassword(String description, char[] newPassword, String reference){ EncryptionModel<AESEncryptionData> encryptionModel = new AESEncryptionModel(); AESEncryptionData encryptionData = encryptionModel.encrypt(ByteUtils.getBytes(newPassword), pass.toCharArray()); PasswordEntry<AESEncryptionData> passwordEntry = new PasswordEntry<>(); passwordEntry.setDescription(description); passwordEntry.setRef(reference); passwordEntry.setEncryptionData(encryptionData); Datasource<AESEncryptionData> datasource = new SQLiteAESDatasource(); datasource.addPass(reference, passwordEntry); byte[] b64 = Base64.encodeBase64(encryptionData.getEncryptedPayload()); System.out.println(new String(b64)); } }
Tidy up info a little for the PluginModule popup edit form git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@40392 b456876b-0849-0410-b77d-98878d47e9d5
<?php // (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id$ //this script may only be included - so its better to die if called directly. if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) { header("location: index.php"); exit; } function module_forums_most_visited_forums_info() { return array( 'name' => tra('Top Visited Forums'), 'description' => tra('Display the specified number of the forums with the most visits.'), 'prefs' => array('feature_forums'), 'params' => array(), 'common_params' => array('nonums', 'rows') ); } function module_forums_most_visited_forums($mod_reference, $module_params) { global $smarty; global $ranklib; include_once ('lib/rankings/ranklib.php'); $ranking = $ranklib->forums_ranking_most_visited_forums($mod_reference["rows"]); $smarty->assign('modForumsMostVisitedForums', $ranking["data"]); }
<?php // (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id$ //this script may only be included - so its better to die if called directly. if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) { header("location: index.php"); exit; } function module_forums_most_visited_forums_info() { return array( 'name' => tra('Most-Visited Forums'), 'description' => tra('Displays the specified number of the forums with the most visits.'), 'prefs' => array('feature_forums'), 'params' => array(), 'common_params' => array('nonums', 'rows') ); } function module_forums_most_visited_forums($mod_reference, $module_params) { global $smarty; global $ranklib; include_once ('lib/rankings/ranklib.php'); $ranking = $ranklib->forums_ranking_most_visited_forums($mod_reference["rows"]); $smarty->assign('modForumsMostVisitedForums', $ranking["data"]); }
Change run script to use worker pool
#!/usr/bin/env python # Automatically generate phylogenies from a settings file # specifying input fasta and genomes import sys import dendrogenous as dg import dendrogenous.settings import dendrogenous.utils import dendrogenous.core import joblib import pickle #multiprocessing def main(settings_file): settings = dg.settings.Settings(settings_file) input_seqs = dg.utils.parse_seqs(settings.input_seqs) seqs_needing_run = dg.utils.check_already_run(settings, input_seqs) r = joblib.Parallel(n_jobs=24, verbose=5)(joblib.delayed(pool_process)\ (seq, settings_file) for seq in seqs_needing_run) def pool_process(seq, settings_file): """ A hacky and unecessary way to provide a pickle serealisable object for multiprocessing to pass off to workers - inefficiency in reinstantiating a settings class every time """ settings = dg.settings.Settings(settings_file) seq_job = dg.core.Dendrogenous(seq, settings) seq_job.build_named_phylogeny() if __name__=='__main__': if len(sys.argv) != 2: print("USAGE: build_phylogenies.py settings.json") sys.exit(1) main(sys.argv[1])
#!/usr/bin/env python # Automatically generate phylogenies from a settings file # specifying input fasta and genomes import sys import dendrogenous as dg import dendrogenous.settings import dendrogenous.utils import dendrogenous.core import multiprocessing def main(settings_file): settings = dg.settings.Settings(settings_file) input_seqs = dg.utils.parse_seqs(settings.input_seqs) seqs_needing_run = dg.utils.check_already_run(settings, input_seqs) processes = [multiprocessing.Process(target=build_phylogeny, args=(seq, settings)) for seq in seqs_needing_run] for p in processes: p.start() for p in processes: p.join() def build_phylogeny(seq, settings): seq_job = dg.core.Dendrogenous(seq, settings) seq_job.build_named_phylogeny() if __name__=='__main__': if len(sys.argv) != 2: print("USAGE: build_phylogenies.py settings.json") sys.exit(1) main(sys.argv[1])
Make sure app won't crash on missing user email
const _ = require('lodash') const excelWriter = require('./excel-writer') const fs = require('fs') const enums = require('../shared/enums') var dateFormat = 'DD.MM.YYYY' exports.constructUserExportData = function (tmpFile, users) { const columnWidths = [10, 40, 30, 10, 40, 20, 10, 10, 40] const xlsData = [['Aktiivinen', 'Nimi', 'Käyttäjätunnus', 'Rooli', 'Email', 'Puhelinnumero', 'Sertifikaatin ensimmäinen myöntämispäivä', 'Voimassaolo päättyy', 'Työnantaja']] _.forEach(users, (user) => xlsData.push(userDetails(user))) excelWriter.write(tmpFile, xlsData, columnWidths.map((c) => ({wch: c}))) var fileData = fs.readFileSync(tmpFile) fs.unlinkSync(tmpFile) return fileData } function userDetails(user) { const userData = [user.active === true ? '1': '', user.name, user.username, user.role, _.compact(user.emails).join(', '), user.phone] if (enums.util.isClassifier(user.role)) userData.push(user.certificateStartDate, user.certificateEndDate, _.map(user.employers, 'name').join(', ')) return userData }
const _ = require('lodash') const excelWriter = require('./excel-writer') const fs = require('fs') const enums = require('../shared/enums') var dateFormat = 'DD.MM.YYYY' exports.constructUserExportData = function (tmpFile, users) { const columnWidths = [10, 40, 30, 10, 40, 20, 10, 10, 40] const xlsData = [['Aktiivinen', 'Nimi', 'Käyttäjätunnus', 'Rooli', 'Email', 'Puhelinnumero', 'Sertifikaatin ensimmäinen myöntämispäivä', 'Voimassaolo päättyy', 'Työnantaja']] _.forEach(users, (user) => xlsData.push(userDetails(user))) excelWriter.write(tmpFile, xlsData, columnWidths.map((c) => ({wch: c}))) var fileData = fs.readFileSync(tmpFile) fs.unlinkSync(tmpFile) return fileData } function userDetails(user) { const userData = [user.active === true ? '1': '', user.name, user.username, user.role, user.emails.join(', '), user.phone] if (enums.util.isClassifier(user.role)) userData.push(user.certificateStartDate, user.certificateEndDate, _.map(user.employers, 'name').join(', ')) return userData }
Test serving static log file.
var config = require('./config'); var express = require('express'); var bodyParser = require('body-parser'); var winston = require('winston'); winston.add(winston.transports.File, { filename: 'info.log', level: 'info' }); winston.remove(winston.transports.Console); winston.add(winston.transports.Console, { level: 'info' }); var statusHandler = require('./routes/status'); var logHandler = require('./routes/log'); var telegramHandler = require('./routes/telegram'); var app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.get('/status', statusHandler); app.post('/telegramBot', telegramHandler); app.use(express.static()); var server = app.listen(config.SERVER_PORT, function () { var host = server.address().address; var port = server.address().port; winston.info('server listening at http://%s:%s', host, port); });
var config = require('./config'); var express = require('express'); var bodyParser = require('body-parser'); var winston = require('winston'); winston.add(winston.transports.File, { filename: 'info.log', level: 'info' }); winston.remove(winston.transports.Console); winston.add(winston.transports.Console, { level: 'info' }); var statusHandler = require('./routes/status'); var telegramHandler = require('./routes/telegram'); var app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.get('/status', statusHandler); app.post('/telegramBot', telegramHandler); var server = app.listen(config.SERVER_PORT, function () { var host = server.address().address; var port = server.address().port; winston.info('server listening at http://%s:%s', host, port); });
Update string for raw trip collab constant.
/** * This file specifies the database collection and field names. */ export const COLLECTION_TRIPS = 'trips'; export const TRIPS_TITLE = 'title'; export const TRIPS_DESCRIPTION = 'description'; export const TRIPS_DESTINATION = 'destination'; export const TRIPS_START_DATE = 'start_date'; export const TRIPS_END_DATE = 'end_date'; export const TRIPS_ACCEPTED_COLLABS = 'accepted_collaborator_uid_arr'; export const TRIPS_PENDING_COLLABS = 'pending_collaborator_uid_arr'; export const TRIPS_REJECTED_COLLABS = 'rejected_collaborator_uid_arr'; export const TRIPS_UPDATE_TIMESTAMP = 'update_timestamp'; /** * NOTE: The following constant corresponds to the collaborator field in * {@link_RawTripData} and is not a field in a trip document. */ export const RAW_TRIP_COLLABS = 'collaborator_email_arr'; export const COLLECTION_ACTIVITIES = 'activities'; export const ACTIVITIES_START_TIME = 'start_time'; export const ACTIVITIES_END_TIME = 'end_time'; export const ACTIVITIES_START_TZ = 'start_tz'; export const ACTIVITIES_END_TZ = 'end_tz'; export const ACTIVITIES_TITLE = 'title'; export const ACTIVITIES_DESCRIPTION = 'description'; export const ACTIVITIES_START_COUNTRY = 'start_country'; export const ACTIVITIES_END_COUNTRY = 'end_country';
/** * This file specifies the database collection and field names. */ export const COLLECTION_TRIPS = 'trips'; export const TRIPS_TITLE = 'title'; export const TRIPS_DESCRIPTION = 'description'; export const TRIPS_DESTINATION = 'destination'; export const TRIPS_START_DATE = 'start_date'; export const TRIPS_END_DATE = 'end_date'; export const TRIPS_ACCEPTED_COLLABS = 'accepted_collaborator_uid_arr'; export const TRIPS_PENDING_COLLABS = 'pending_collaborator_uid_arr'; export const TRIPS_REJECTED_COLLABS = 'rejected_collaborator_uid_arr'; export const TRIPS_UPDATE_TIMESTAMP = 'update_timestamp'; /** * NOTE: The following constant corresponds to the collaborator field in * {@link_RawTripData} and is not a field in a trip document. */ export const RAW_TRIP_COLLABS export const COLLECTION_ACTIVITIES = 'activities'; export const ACTIVITIES_START_TIME = 'start_time'; export const ACTIVITIES_END_TIME = 'end_time'; export const ACTIVITIES_START_TZ = 'start_tz'; export const ACTIVITIES_END_TZ = 'end_tz'; export const ACTIVITIES_TITLE = 'title'; export const ACTIVITIES_DESCRIPTION = 'description'; export const ACTIVITIES_START_COUNTRY = 'start_country'; export const ACTIVITIES_END_COUNTRY = 'end_country';
Deploy as the buildbot user, not root.
import unipath from fabric.api import * from fabric.contrib import files # Fab settings env.hosts = ['ve.djangoproject.com'] env.user = "buildbot" # Deployment environment paths and settings and such. env.deploy_base = unipath.Path('/home/buildbot') env.virtualenv = env.deploy_base env.code_dir = env.deploy_base.child('master') env.git_url = 'git://github.com/jacobian/django-buildmaster.git' # FIXME: make a deploy branch in this repo to deploy against. env.default_deploy_ref = 'HEAD' def deploy(): """ Full deploy: new code, update dependencies, migrate, and restart services. """ deploy_code() update_dependencies() restart() def restart(): pass #sudo('service buildbot restart') def deploy_code(ref=None): """ Update code on the servers from Git. """ ref = ref or env.default_deploy_ref puts("Deploying %s" % ref) if not files.exists(env.code_dir): run('git clone %s %s' % (env.git_url, env.code_dir)) with cd(env.code_dir): run('git fetch && git reset --hard %s' % ref) def update_dependencies(): """ Update dependencies in the virtualenv. """ pip = env.virtualenv.child('bin', 'pip') reqs = env.code_dir.child('deploy-requirements.txt') run('%s -q install -r %s' % (pip, reqs))
import unipath from fabric.api import * from fabric.contrib import files # Fab settings env.hosts = ['ve.djangoproject.com'] # Deployment environment paths and settings and such. env.deploy_base = unipath.Path('/home/buildbot') env.virtualenv = env.deploy_base env.code_dir = env.deploy_base.child('master') env.git_url = 'git://github.com/jacobian/django-buildmaster.git' # FIXME: make a deploy branch in this repo to deploy against. env.default_deploy_ref = 'HEAD' def deploy(): """ Full deploy: new code, update dependencies, migrate, and restart services. """ deploy_code() update_dependencies() restart() def restart(): sudo('service buildbot restart') def deploy_code(ref=None): """ Update code on the servers from Git. """ ref = ref or env.default_deploy_ref puts("Deploying %s" % ref) if not files.exists(env.code_dir): sudo('git clone %s %s' % (env.git_url, env.code_dir)) with cd(env.code_dir): sudo('git fetch && git reset --hard %s' % ref) def update_dependencies(): """ Update dependencies in the virtualenv. """ pip = env.virtualenv.child('bin', 'pip') reqs = env.code_dir.child('requirements.txt') sudo('%s -q install -r %s' % (pip, reqs))
Fix tests for Python 2.7
import pytest try: import cPickle as pickle except ImportError: import pickle from .models import Post pytestmark = pytest.mark.django_db @pytest.mark.django_db @pytest.fixture def post(): return Post.objects.create(title='Pickling') def test_equal(post): restored = pickle.loads(pickle.dumps(post, -1)) assert restored == post def test_packed(post): stored = pickle.dumps(post) assert b'model_unpickle' in stored # Our unpickling function is used assert b'title' not in stored # Attributes are packed def test_state_packed(post): stored = pickle.dumps(post, -1) assert b'_state' not in stored assert b'db' not in stored assert b'adding' not in stored def test_deferred(post): p = Post.objects.defer('title').get(pk=post.pk) restored = pickle.loads(pickle.dumps(p, -1)) assert restored == p
import pytest try: import cPickle as pickle except ImportError: import pickle from .models import Post pytestmark = pytest.mark.django_db @pytest.mark.django_db @pytest.fixture def post(): return Post.objects.create(title='Pickling') def test_equal(post): restored = pickle.loads(pickle.dumps(post, -1)) assert restored == post def test_packed(post): stored = pickle.dumps(post) assert b'model_unpickle' in stored # Our unpickling function is used assert b'title' not in stored # Attributes are packed def test_state_packed(post): stored = pickle.dumps(post) assert b'_state' not in stored assert b'db' not in stored assert b'adding' not in stored def test_deferred(post): p = Post.objects.defer('title').get(pk=post.pk) restored = pickle.loads(pickle.dumps(p, -1)) assert restored == p
Drop support for arrays and add string type hint in encode()
<?php namespace qnd; /** * Encode * * @param string $var * * @return string */ function encode(string $var) { static $charset; if ($charset === null) { $charset = config('i18n.charset'); } return htmlspecialchars($var, ENT_QUOTES, $charset, false); } /** * HTML * * @param string $string * * @return string */ function filter_html(string $string): string { static $allowed; if ($allowed === null) { $allowed = config('filter.html'); } return strip_tags(trim($string), $allowed); } /** * Converts backslashes to forward slashes in Windows-style paths * * @param string $path * * @return string */ function filter_path(string $path): string { return strpos($path, '\\') !== false ? str_replace('\\', '/', $path) : $path; } /** * Identifier * * @param string $id * * @return string */ function filter_id(string $id): string { static $data, $keys; if ($data === null) { $data = config('filter.identifier'); $keys = array_keys($data); } return trim(preg_replace($keys, $data, strtolower($id)), '-'); }
<?php namespace qnd; /** * Encode * * @param string|array $var * * @return string|array */ function encode($var) { static $charset; if ($charset === null) { $charset = config('i18n.charset'); } if (is_array($var)) { return array_map(__FUNCTION__, $var); } return is_string($var) ? htmlspecialchars($var, ENT_QUOTES, $charset, false) : $var; } /** * HTML * * @param string $string * * @return string */ function filter_html(string $string): string { static $allowed; if ($allowed === null) { $allowed = config('filter.html'); } return strip_tags(trim($string), $allowed); } /** * Converts backslashes to forward slashes in Windows-style paths * * @param string $path * * @return string */ function filter_path(string $path): string { return strpos($path, '\\') !== false ? str_replace('\\', '/', $path) : $path; } /** * Identifier * * @param string $id * * @return string */ function filter_id(string $id): string { static $data, $keys; if ($data === null) { $data = config('filter.identifier'); $keys = array_keys($data); } return trim(preg_replace($keys, $data, strtolower($id)), '-'); }
Put generators at top of targets (experimenting w/ convention)
var path = require('path'); var _ = require('lodash'); var packageJSON = require('../json/package.json.js'); var sailsrc = require('../json/sailsrc'); /** * sails-generate-new * * Usage: * `sails-generate-new` * * @type {Object} */ module.exports = { moduleDir: require('path').resolve(__dirname, '..'), templatesDirectory: require('path').resolve(__dirname,'../templates'), before: require('./before'), targets: { '.': ['backend','frontend'], './Gruntfile.js': 'gruntfile', './.gitignore': { copy: 'gitignore' }, './README.md': { template: './README.md' }, './package.json': { jsonfile: packageJSON }, './.sailsrc': { jsonfile: sailsrc }, './app.js': { copy: 'app.js' } } };
var path = require('path'); var _ = require('lodash'); var packageJSON = require('../json/package.json.js'); var sailsrc = require('../json/sailsrc'); /** * sails-generate-new * * Usage: * `sails-generate-new` * * @type {Object} */ module.exports = { moduleDir: require('path').resolve(__dirname, '..'), templatesDirectory: require('path').resolve(__dirname,'../templates'), before: require('./before'), targets: { '.': ['backend','frontend'], './.gitignore': { copy: 'gitignore' }, './README.md': { template: './README.md' }, './package.json': { jsonfile: packageJSON }, './.sailsrc': { jsonfile: sailsrc }, './app.js': { copy: 'app.js' }, './Gruntfile.js': 'gruntfile' } };
Change class name to CompilerVersionChecker and add space in the description error
const semver = require('semver') const BaseChecker = require('./../base-checker') const ruleId = 'compiler-version' const meta = { type: 'security', docs: { description: `Compiler version must satisfy a semver requirement.`, category: 'Security Rules' }, isDefault: false, recommended: true, defaultSetup: ['error', '^0.5.7'], schema: [ { type: 'array', items: [{ type: 'string' }], uniqueItems: true, minItems: 2 } ] } class CompilerVersionChecker extends BaseChecker { constructor(reporter, config) { super(reporter, ruleId, meta) this.requirement = (config && config.getString(ruleId, '^0.5.8')) || '^0.5.8' } exitVersionConstraint(ctx) { const versionNode = (this.isVersionOperator(ctx.children[0]) && ctx.children[1]) || ctx.children[0] if (!semver.satisfies(versionNode.getText(), this.requirement)) { this.error( ctx, `Compiler version ${versionNode.getText()} does not satisfy the ${ this.requirement } semver requirement` ) } } isVersionOperator(ctx) { return ctx.constructor.name.includes('VersionOperator') } } module.exports = CompilerVersionChecker
const semver = require('semver') const BaseChecker = require('./../base-checker') const ruleId = 'compiler-version' const meta = { type: 'security', docs: { description: `Compiler version must satisfy a semver requirement.`, category: 'Security Rules' }, isDefault: false, recommended: true, defaultSetup: ['error', '^0.5.7'], schema: [ { type: 'array', items: [{ type: 'string' }], uniqueItems: true, minItems: 2 } ] } class CompilerGTChecker extends BaseChecker { constructor(reporter, config) { super(reporter, ruleId, meta) this.requirement = (config && config.getString(ruleId, '^0.5.8')) || '^0.5.8' } exitVersionConstraint(ctx) { const versionNode = (this.isVersionOperator(ctx.children[0]) && ctx.children[1]) || ctx.children[0] if (!semver.satisfies(versionNode.getText(), this.requirement)) { this.error( ctx, `Compiler version ${versionNode.getText()} does not satisfy the ${ this.requirement }semver requirement` ) } } isVersionOperator(ctx) { return ctx.constructor.name.includes('VersionOperator') } } module.exports = CompilerGTChecker
Use latest v1 client by default
'use strict'; const events = require('events'); const utils = require('./utils'); const Listener = require('./listener'); class Server extends events.EventEmitter { constructor(user_options) { super(); this.options = { prefix: '', response_limit: 128*1024, websocket: true, faye_server_options: null, jsessionid: false, heartbeat_delay: 25000, disconnect_delay: 5000, log() {}, sockjs_url: 'https://cdn.jsdelivr.net/sockjs/1/sockjs.min.js' }; Object.assign(this.options, user_options); } listener(handler_options) { const options = Object.assign({}, this.options, handler_options); return new Listener(options, function() { this.emit.apply(this, arguments); }.bind(this)); } installHandlers(http_server, handler_options) { let handler = this.listener(handler_options).getHandler(); utils.overshadowListeners(http_server, 'request', handler); utils.overshadowListeners(http_server, 'upgrade', handler); return true; } middleware(handler_options) { let handler = this.listener(handler_options).getHandler(); handler.upgrade = handler; return handler; } } module.exports = Server;
'use strict'; const events = require('events'); const utils = require('./utils'); const Listener = require('./listener'); class Server extends events.EventEmitter { constructor(user_options) { super(); this.options = { prefix: '', response_limit: 128*1024, websocket: true, faye_server_options: null, jsessionid: false, heartbeat_delay: 25000, disconnect_delay: 5000, log() {}, sockjs_url: 'https://cdn.jsdelivr.net/sockjs/1.0.1/sockjs.min.js' }; Object.assign(this.options, user_options); } listener(handler_options) { const options = Object.assign({}, this.options, handler_options); return new Listener(options, function() { this.emit.apply(this, arguments); }.bind(this)); } installHandlers(http_server, handler_options) { let handler = this.listener(handler_options).getHandler(); utils.overshadowListeners(http_server, 'request', handler); utils.overshadowListeners(http_server, 'upgrade', handler); return true; } middleware(handler_options) { let handler = this.listener(handler_options).getHandler(); handler.upgrade = handler; return handler; } } module.exports = Server;
Add sourceip and target parameters to AttackForm
from django.forms import ModelForm from breach.models import Target, Victim class TargetForm(ModelForm): class Meta: model = Target fields = ( 'name', 'endpoint', 'prefix', 'alphabet', 'secretlength', 'alignmentalphabet', 'recordscardinality', 'method' ) class VictimForm(ModelForm): class Meta: model = Victim fields = ( 'sourceip', ) class AttackForm(ModelForm): class Meta: model = Victim fields = ( 'sourceip', 'target' )
from django.forms import ModelForm from breach.models import Target, Victim class TargetForm(ModelForm): class Meta: model = Target fields = ( 'name', 'endpoint', 'prefix', 'alphabet', 'secretlength', 'alignmentalphabet', 'recordscardinality', 'method' ) class VictimForm(ModelForm): class Meta: model = Victim fields = ( 'sourceip', ) class AttackForm(ModelForm): class Meta: model = Victim fields = ( 'id', )