text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Update tests to use immersive mode
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.badlogic.gdx.tests.android; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration; import com.badlogic.gdx.tests.utils.GdxTest; import com.badlogic.gdx.tests.utils.GdxTests; public class GdxTestActivity extends AndroidApplication { public void onCreate (Bundle bundle) { super.onCreate(bundle); Bundle extras = getIntent().getExtras(); String testName = (String)extras.get("test"); GdxTest test = GdxTests.newTest(testName); AndroidApplicationConfiguration config = new AndroidApplicationConfiguration(); config.useGL20 = test.needsGL20(); config.useImmersiveMode = true; initialize(test, config); } }
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.badlogic.gdx.tests.android; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration; import com.badlogic.gdx.tests.utils.GdxTest; import com.badlogic.gdx.tests.utils.GdxTests; public class GdxTestActivity extends AndroidApplication { public void onCreate (Bundle bundle) { super.onCreate(bundle); Bundle extras = getIntent().getExtras(); String testName = (String)extras.get("test"); GdxTest test = GdxTests.newTest(testName); AndroidApplicationConfiguration config = new AndroidApplicationConfiguration(); config.useGL20 = test.needsGL20(); initialize(test, config); } }
Implement Serializable and Comparable interfaces
package io.github.arpankapoor.country; import android.support.annotation.NonNull; import com.google.i18n.phonenumbers.PhoneNumberUtil; import java.io.Serializable; import java.util.Locale; public class Country implements Comparable<Country>, Serializable { private static final long serialVersionUID = 8116297477768564397L; private String name; private String isoCode; private int callingCode; public Country(String isoCode) { setIsoCode(isoCode.toUpperCase()); setName(new Locale("", getIsoCode()).getDisplayCountry()); setCallingCode(PhoneNumberUtil.getInstance().getCountryCodeForRegion(getIsoCode())); } @Override public String toString() { return name + " (+" + callingCode + ")"; } public int getCallingCode() { return callingCode; } public void setCallingCode(int callingCode) { this.callingCode = callingCode; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getIsoCode() { return isoCode; } public void setIsoCode(String isoCode) { this.isoCode = isoCode; } @Override public int compareTo(@NonNull Country another) { return this.name.compareTo(another.name); } }
package io.github.arpankapoor.country; import com.google.i18n.phonenumbers.PhoneNumberUtil; import java.util.Locale; public class Country { private String name; private String isoCode; private int callingCode; public Country(String isoCode) { this.isoCode = isoCode.toUpperCase(); this.name = new Locale("", this.isoCode).getDisplayCountry(); this.callingCode = PhoneNumberUtil.getInstance().getCountryCodeForRegion(this.isoCode); } @Override public String toString() { return name + " (+" + callingCode + ")"; } public int getCallingCode() { return callingCode; } public void setCallingCode(int callingCode) { this.callingCode = callingCode; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getIsoCode() { return isoCode; } public void setIsoCode(String isoCode) { this.isoCode = isoCode; } }
Make version info tuple of ints.
__version__ = '0.6.0' __version_info__ = tuple(map(int, __version__.split('.'))) from django.utils.translation import ugettext_lazy as _ def __activate_social_auth_monkeypatch(): from social_core.backends.base import BaseAuth from social_core.backends.open_id import (OPENID_ID_FIELD, OpenIdAuth) from social_core.backends.livejournal import LiveJournalOpenId from social_core.backends.yahoo import YahooOpenId from social_core.backends.google import GoogleOpenId from social_core.backends.yandex import YandexOpenId BaseAuth.REQUIRED_FIELD_NAME = None BaseAuth.REQUIRED_FIELD_VERBOSE_NAME = None OpenIdAuth.REQUIRED_FIELD_NAME = OPENID_ID_FIELD OpenIdAuth.REQUIRED_FIELD_VERBOSE_NAME = _('OpenID identity') LiveJournalOpenId.REQUIRED_FIELD_NAME = 'openid_lj_user' LiveJournalOpenId.REQUIRED_FIELD_VERBOSE_NAME = _('LiveJournal username') # Reset to None in those OpenID backends where nothing is required. GoogleOpenId.REQUIRED_FIELD_NAME = None GoogleOpenId.REQUIRED_FIELD_VERBOSE_NAME = None YahooOpenId.REQUIRED_FIELD_NAME = None YahooOpenId.REQUIRED_FIELD_VERBOSE_NAME = None YandexOpenId.REQUIRED_FIELD_NAME = None YandexOpenId.REQUIRED_FIELD_VERBOSE_NAME = None __activate_social_auth_monkeypatch()
__version__ = '0.6.0' __version_info__ = __version__.split('.') from django.utils.translation import ugettext_lazy as _ def __activate_social_auth_monkeypatch(): from social_core.backends.base import BaseAuth from social_core.backends.open_id import (OPENID_ID_FIELD, OpenIdAuth) from social_core.backends.livejournal import LiveJournalOpenId from social_core.backends.yahoo import YahooOpenId from social_core.backends.google import GoogleOpenId from social_core.backends.yandex import YandexOpenId BaseAuth.REQUIRED_FIELD_NAME = None BaseAuth.REQUIRED_FIELD_VERBOSE_NAME = None OpenIdAuth.REQUIRED_FIELD_NAME = OPENID_ID_FIELD OpenIdAuth.REQUIRED_FIELD_VERBOSE_NAME = _('OpenID identity') LiveJournalOpenId.REQUIRED_FIELD_NAME = 'openid_lj_user' LiveJournalOpenId.REQUIRED_FIELD_VERBOSE_NAME = _('LiveJournal username') # Reset to None in those OpenID backends where nothing is required. GoogleOpenId.REQUIRED_FIELD_NAME = None GoogleOpenId.REQUIRED_FIELD_VERBOSE_NAME = None YahooOpenId.REQUIRED_FIELD_NAME = None YahooOpenId.REQUIRED_FIELD_VERBOSE_NAME = None YandexOpenId.REQUIRED_FIELD_NAME = None YandexOpenId.REQUIRED_FIELD_VERBOSE_NAME = None __activate_social_auth_monkeypatch()
Fix security issue with password recovery. Now a not used recovery token need to be used for password reset ... before account id was enough.
const service = require('feathers-mongoose'); const passwordRecovery = require('./model'); const hooks = require('./hooks'); const AccountModel = require('./../account/model'); class ChangePasswordService { create(data) { return passwordRecovery.findOne({ _id: data.resetId, changed: false }) .then((pwrecover) => AccountModel.update({ _id: pwrecover.account }, { password: data.password }) .then((account) => passwordRecovery.update({ _id: data.resetId }, { changed: true }) .then((_ => account)))).catch((error) => error); } } module.exports = function () { const app = this; const options = { Model: passwordRecovery, paginate: { default: 100, max: 100, }, lean: true, }; app.use('/passwordRecovery', service(options)); app.use('/passwordRecovery/reset', new ChangePasswordService()); const passwordRecoveryService = app.service('/passwordRecovery'); const changePasswordService = app.service('/passwordRecovery/reset'); passwordRecoveryService.hooks(hooks); changePasswordService.hooks(hooks); };
const service = require('feathers-mongoose'); const passwordRecovery = require('./model'); const hooks = require('./hooks'); const AccountModel = require('./../account/model'); class ChangePasswordService { constructor() { } create(data) { return AccountModel.update({ _id: data.accountId }, { password: data.password }) .then(account => passwordRecovery.update({ _id: data.resetId }, { changed: true }) .then((_ => account))).catch(error => error); } } module.exports = function () { const app = this; const options = { Model: passwordRecovery, paginate: { default: 100, max: 100, }, lean: true, }; app.use('/passwordRecovery', service(options)); app.use('/passwordRecovery/reset', new ChangePasswordService()); const passwordRecoveryService = app.service('/passwordRecovery'); const changePasswordService = app.service('/passwordRecovery/reset'); passwordRecoveryService.hooks(hooks); changePasswordService.hooks(hooks); };
Remove errant reference to old link field
import datetime from django.contrib import admin from django.db import models from django.db.models.signals import post_save from activity.models import broadcast class Entry(models.Model): title = models.CharField(max_length=100) published = models.DateTimeField(default=datetime.datetime.now()) url = models.URLField() body = models.TextField() link = models.ForeignKey('projects.Link') class Meta: verbose_name_plural = u'entries' def __unicode__(self): return u'%s -> %s' % (self.title, self.url) @property def project(self): return self.link.project or None admin.site.register(Entry) def entry_save_handler(sender, instance, **kwargs): broadcast(instance) post_save.connect(entry_save_handler, sender=Entry)
import datetime from django.contrib import admin from django.db import models from django.db.models.signals import post_save from activity.models import broadcast class Entry(models.Model): title = models.CharField(max_length=100) published = models.DateTimeField(default=datetime.datetime.now()) url = models.URLField() body = models.TextField() link = models.ForeignKey('projects.Link') class Meta: verbose_name_plural = u'entries' def __unicode__(self): return u'%s -> %s' % (self.title, self.link) @property def project(self): return self.link.project or None admin.site.register(Entry) def entry_save_handler(sender, instance, **kwargs): broadcast(instance) post_save.connect(entry_save_handler, sender=Entry)
Fix parametre passé à formulaire
<?php namespace Leha\HistoriqueBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class HistorySearchType extends AbstractType { /** * Returns the name of this type. * * @return string The name of this type */ public function getName() { return 'leha_historique_history_search'; } public function buildForm(FormBuilderInterface $builder, array $options) { parent::buildForm($builder, $options); foreach ($options['attribut_requete'] as $attributRequete) { $attribut = $attributRequete->getAttribut(); $builder->add($attribut->getFieldId(), $attribut->getType(), $attribut->getFieldOptions()); } } public function setDefaultOptions(OptionsResolverInterface $resolver) { parent::setDefaultOptions($resolver); // TODO: Change the autogenerated stub $resolver->setRequired(array( 'attribut_requete' )); } }
<?php namespace Leha\HistoriqueBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; class HistorySearchType extends AbstractType { /** * Returns the name of this type. * * @return string The name of this type */ public function getName() { return 'leha_historique_history_search'; } public function buildForm(FormBuilderInterface $builder, array $options) { parent::buildForm($builder, $options); foreach ($options['attribut_requete'] as $attribut_requete) { $attribut = $attribut_requete->getAttribut(); $builder->add($attribut->getFieldId(), $attribut->getType(), $attribut->getFieldOptions()); } } }
Fix bugs for updating from tf 2.0b0 to rc0 Updating the dependency of tensorflow from 2.0.0b1 to 2.0.0rc0 is causing crashes in keras-tuner. Not sure the "set" operation is really useful, but it is causing the crash because it tries to hash a tensor with equality enabled. ``` ../../.virtualenvs/ak/lib/python3.6/site-packages/kerastuner/utils.py:23: in compute_model_size params = [K.count_params(p) for p in set(model.trainable_weights)] _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <tf.Variable 'dense/kernel:0' shape=(32, 32) dtype=float32, numpy= array([[ 0.03147817, -0.30117437, -0.08552131, ...,...], [ 0.23273078, -0.10847142, 0.0151484 , ..., 0.16468436, -0.21210298, -0.1087181 ]], dtype=float32)> def __hash__(self): if ops.Tensor._USE_EQUALITY and ops.executing_eagerly_outside_functions(): # pylint: disable=protected-access > raise TypeError("Variable is unhashable if Tensor equality is enabled. " "Instead, use tensor.experimental_ref() as the key.") E TypeError: Variable is unhashable if Tensor equality is enabled. Instead, use tensor.experimental_ref() as the key. ../../.virtualenvs/ak/lib/python3.6/site-packages/tensorflow_core/python/ops/variables.py:1085: TypeError ```
# Copyright 2019 The Keras Tuner 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import gc import numpy as np from tensorflow.python import Session, ConfigProto from tensorflow.python.keras import backend as K def compute_model_size(model): "comput the size of a given model" params = [K.count_params(p) for p in model.trainable_weights] return int(np.sum(params)) def clear_tf_session(): "Clear tensorflow graph to avoid OOM issues" K.clear_session() # K.get_session().close() # unsure if it is needed gc.collect() if hasattr(K, 'set_session'): cfg = ConfigProto() cfg.gpu_options.allow_growth = True # pylint: disable=no-member K.set_session(Session(config=cfg))
# Copyright 2019 The Keras Tuner 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import gc import numpy as np from tensorflow.python import Session, ConfigProto from tensorflow.python.keras import backend as K def compute_model_size(model): "comput the size of a given model" params = [K.count_params(p) for p in set(model.trainable_weights)] return int(np.sum(params)) def clear_tf_session(): "Clear tensorflow graph to avoid OOM issues" K.clear_session() # K.get_session().close() # unsure if it is needed gc.collect() if hasattr(K, 'set_session'): cfg = ConfigProto() cfg.gpu_options.allow_growth = True # pylint: disable=no-member K.set_session(Session(config=cfg))
Archive logs from the tools Change-Id: I184473d20cc2763fbc97c993bfcab36b80d1c864 Reviewed-on: http://review.couchbase.org/76571 Tested-by: Build Bot <80754af91bfb6d1073585b046fe0a474ce868509@couchbase.com> Reviewed-by: Pavel Paulau <dd88eded64e90046a680e3a6c0828ceb8fe8a0e7@gmail.com>
import glob import os.path import shutil from optparse import OptionParser from perfrunner.helpers.remote import RemoteHelper from perfrunner.settings import ClusterSpec def get_options(): usage = '%prog -c cluster' parser = OptionParser(usage) parser.add_option('-c', dest='cluster_spec_fname', help='path to the cluster specification file', metavar='cluster.spec') options, args = parser.parse_args() if not options.cluster_spec_fname: parser.error('Please specify a cluster specification') return options, args def main(): options, args = get_options() cluster_spec = ClusterSpec() cluster_spec.parse(options.cluster_spec_fname, args) remote = RemoteHelper(cluster_spec, test_config=None, verbose=False) remote.collect_info() for hostname in cluster_spec.yield_hostnames(): for fname in glob.glob('{}/*.zip'.format(hostname)): shutil.move(fname, '{}.zip'.format(hostname)) if cluster_spec.backup is not None: logs = os.path.join(cluster_spec.backup, 'logs') if os.path.exists(logs): shutil.make_archive('tools', 'zip', logs) if __name__ == '__main__': main()
import glob import shutil from optparse import OptionParser from perfrunner.helpers.remote import RemoteHelper from perfrunner.settings import ClusterSpec def get_options(): usage = '%prog -c cluster' parser = OptionParser(usage) parser.add_option('-c', dest='cluster_spec_fname', help='path to the cluster specification file', metavar='cluster.spec') options, args = parser.parse_args() if not options.cluster_spec_fname: parser.error('Please specify a cluster specification') return options, args def main(): options, args = get_options() cluster_spec = ClusterSpec() cluster_spec.parse(options.cluster_spec_fname, args) remote = RemoteHelper(cluster_spec, test_config=None, verbose=False) remote.collect_info() for hostname in cluster_spec.yield_hostnames(): for fname in glob.glob('{}/*.zip'.format(hostname)): shutil.move(fname, '{}.zip'.format(hostname)) if __name__ == '__main__': main()
Update the benchmark to use the document.readyState to measure page-completedness rather than the onload event. Extensions were moved from the pre-onload state to running at document idle some time ago. BUG=none TEST=none Review URL: http://codereview.chromium.org/397013 git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@32076 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
// The port for communicating back to the extension. var benchmarkExtensionPort = chrome.extension.connect(); // The url is what this page is known to the benchmark as. // The benchmark uses this id to differentiate the benchmark's // results from random pages being browsed. // TODO(mbelshe): If the page redirects, the location changed and the // benchmark stalls. var benchmarkExtensionUrl = window.location.toString(); function sendTimesToExtension() { if (window.parent != window) { return; } var times = window.chrome.loadTimes(); // If the load is not finished yet, schedule a timer to check again in a // little bit. if (times.finishLoadTime != 0) { benchmarkExtensionPort.postMessage({message: "load", url: benchmarkExtensionUrl, values: times}); } else { window.setTimeout(sendTimesToExtension, 100); } } // We can't use the onload event because this script runs at document idle, // which may run after the onload has completed. sendTimesToExtension();
// The port for communicating back to the extension. var benchmarkExtensionPort = chrome.extension.connect(); // The url is what this page is known to the benchmark as. // The benchmark uses this id to differentiate the benchmark's // results from random pages being browsed. // TODO(mbelshe): If the page redirects, the location changed and the // benchmark stalls. var benchmarkExtensionUrl = window.location.toString(); function sendTimesToExtension() { var times = window.chrome.loadTimes(); if (times.finishLoadTime != 0) { benchmarkExtensionPort.postMessage({message: "load", url: benchmarkExtensionUrl, values: times}); } else { window.setTimeout(sendTimesToExtension, 100); } } function loadComplete() { // Only trigger for top-level frames (e.g. the one we benchmarked) if (window.parent == window) { sendTimesToExtension(); } } window.addEventListener("load", loadComplete);
Feature: Add a `toString()` method that can accept options.
<?PHP /** * A common interface for all value objects. * * * @author Adamo Crespi <hello@aerendir.me> * @copyright Copyright (c) 2015, Adamo Crespi * @license MIT License */ namespace SerendipityHQ\Component\ValueObjects\Common; /** * Defines the minimum requisites of Value Objects. */ interface ValueObjectInterface { /** * The string representation of the object. * * This method can accept options to refine the string returned. * * @return string */ public function toString(array $options = []); /** * The string representation of the object. * * @return string */ public function __toString(); /** * Disable the __set magic method. * * Implement this way: * * public function __set($field, $value) * { * // Body MUST BE EMPTY * } * * @param mixed $field * @param mixed $value */ public function __set($field, $value); }
<?PHP /** * A common interface for all value objects. * * * @author Adamo Crespi <hello@aerendir.me> * @copyright Copyright (c) 2015, Adamo Crespi * @license MIT License */ namespace SerendipityHQ\Component\ValueObjects\Common; /** * Defines the minimum requisites of Value Objects. */ interface ValueObjectInterface { /** * The string representation of the object. * * @return string */ public function __toString(); /** * Disable the __set magic method. * * Implement this way: * * public function __set($field, $value) * { * // Body MUST BE EMPTY * } * * @param mixed $field * @param mixed $value */ public function __set($field, $value); }
Fix the phpcs code style error.
<?php /** * Class Google\Site_Kit\Modules\Analytics\Plugin_Detector * * @package Google\Site_Kit\Modules\Analytics * @copyright 2019 Google LLC * @license https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://sitekit.withgoogle.com */ namespace Google\Site_Kit\Modules\Analytics; /** * Detects the user's current active plugins that ShirshuClass supports * * Class Plugin_Detector */ class Plugin_Detector { /** * A list of Shirshu_Class supported plugins * * @var array */ private $supported_plugins = array(); /** * Plugin_Detector constructor. * * @param array $supported_plugins list of supported plugins. */ public function __construct( $supported_plugins ) { $this->supported_plugins = $supported_plugins; } /** * Determines the user's current active plugins that Shirshu_Class supports * * @return array */ public function get_active_plugins() { $active_plugins = array(); foreach ( $this->supported_plugins as $key => $function_name ) { if ( defined( $function_name ) || function_exists( $function_name ) ) { array_push( $active_plugins, $key ); } } return $active_plugins; } }
<?php /** * Class Google\Site_Kit\Modules\Analytics\Plugin_Detector * * @package Google\Site_Kit\Modules\Analytics * @copyright 2019 Google LLC * @license https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://sitekit.withgoogle.com */ namespace Google\Site_Kit\Modules\Analytics; /** * Detects the user's current active plugins that ShirshuClass supports * * Class Plugin_Detector */ class Plugin_Detector { /** * A list of Shirshu_Class supported plugins * * @var array */ private $supported_plugins = array(); /** * Plugin_Detector constructor. * * @param array $supported_plugins list of supported plugins. */ public function __construct( $supported_plugins ) { $this->supported_plugins = $supported_plugins; } /** * Determines the user's current active plugins that Shirshu_Class supports * * @return array */ public function get_active_plugins() { $active_plugins = array(); foreach ( $this->supported_plugins as $key => $function_name ) { if ( defined( $function_name ) || function_exists( $function_name ) ) { array_push( $active_plugins, $key); } } return $active_plugins; } }
Add touchstart to support touch devices
function Prefetch() { this.hooks(); } Prefetch.prototype.hooks = function () { var links = document.querySelectorAll('a'); var length = links.length; for (var n = 0; n < length; n++) { var prefetchFunction = function (event) { // Left mouse click or Touch if (event.constructor.name === 'TouchEvent' || event.which === 1) { var prefetch = document.createElement('link'); prefetch.rel = 'prefetch'; prefetch.href = this.href; document.head.appendChild(prefetch); } }; ['touchstart', 'mousedown'].forEach(value => { links[n].addEventListener(value, prefetchFunction, false); }); } };
function Prefetch() { this.hooks(); } Prefetch.prototype.hooks = function () { var links = document.querySelectorAll('a'); for (var n = 0; n < links.length; n++) { links[n].addEventListener('mousedown', function (event) { // Left mouse click if (event.which == 1) { var prefetch = document.createElement('link'); prefetch.rel = 'prefetch'; prefetch.href = this.href; document.head.appendChild(prefetch); } }, false); } };
Check for lotteries data before trying to process them.
/** * Created by mgab on 14/05/2017. */ import React,{ Component } from 'react' import Title from './common/styled-components/Title' import Lottery from './Lottery' export default class Lotteries extends Component { render() { const lotteries = [] if (this.props.lotteriesData) { this.props.lotteriesData.forEach((entry) => { lotteries.push(<Lottery name={entry.id} jackpot={entry.jackpots[0].jackpot} drawingDate={entry.drawingDate} key={entry.id} />) }) } return ( <div> <Title>Lotteries</Title> <div> {lotteries} </div> </div> ) } }
/** * Created by mgab on 14/05/2017. */ import React,{ Component } from 'react' import Title from './common/styled-components/Title' import Lottery from './Lottery' export default class Lotteries extends Component { render() { const lotteries = [] this.props.lotteriesData.forEach((entry) => { lotteries.push(<Lottery name={entry.id} jackpot={entry.jackpots[0].jackpot} drawingDate={entry.drawingDate} key={entry.id} />) }) return ( <div> <Title>Lotteries</Title> <div> {lotteries} </div> </div> ) } }
Check config values before dropping DB data
import fs from 'fs' import path from 'path' import prepare from 'mocha-prepare' import chai from 'chai' import chaiHttp from 'chai-http' import redis from 'redis' import { promisify } from 'util' import config from './src/config' import db from './src/utils/db' import api from './src/server' chai.use(chaiHttp); prepare((done) => { if (!config.database.uri) throw new Error('Missing MongoDB connection string. Check config'); if (!config.cache.uri) throw new Error('Missing Redis connection string. Check config'); const redisClient = redis.createClient(config.cache.uri); //XXX: drop all data before running tests db.then((db) => { return db.connection.dropDatabase(); }).then(() => { return promisify(redisClient.send_command.bind(redisClient))('FLUSHDB'); }).then(() => {; fs.readdirSync(path.join(__dirname, "src", "routes")).forEach(file => { if (file.endsWith(".js")) { require("./src/routes/" + file)(api) } }) }).then(done).catch(done); }, () => { // XXX: don't care about open connections setTimeout(process.exit, 3000); });
import fs from 'fs' import path from 'path' import prepare from 'mocha-prepare' import chai from 'chai' import chaiHttp from 'chai-http' import redis from 'redis' import { promisify } from 'util' import config from './src/config' import db from './src/utils/db' import api from './src/server' chai.use(chaiHttp); prepare((done) => { const redisClient = redis.createClient(config.cache.uri); //XXX: drop all data before running tests db.then((db) => { return db.connection.dropDatabase(); }).then(() => { return promisify(redisClient.send_command.bind(redisClient))('FLUSHDB'); }).then(() => {; fs.readdirSync(path.join(__dirname, "src", "routes")).forEach(file => { if (file.endsWith(".js")) { require("./src/routes/" + file)(api) } }) }).then(done).catch(done); }, () => { // XXX: don't care about open connections setTimeout(process.exit, 3000); });
[JupyROOT] Update logic to check for IPython To sync it with what was already introduced in ROOT/__init__.py
#----------------------------------------------------------------------------- # Author: Danilo Piparo <Danilo.Piparo@cern.ch> CERN # Author: Enric Tejedor <enric.tejedor.saavedra@cern.ch> CERN #----------------------------------------------------------------------------- ################################################################################ # Copyright (C) 1995-2020, Rene Brun and Fons Rademakers. # # All rights reserved. # # # # For the licensing terms see $ROOTSYS/LICENSE. # # For the list of contributors see $ROOTSYS/README/CREDITS. # ################################################################################ from JupyROOT.helpers import cppcompleter, utils # Check if we are in the IPython shell try: import builtins except ImportError: import __builtin__ as builtins # Py2 _is_ipython = hasattr(builtins, '__IPYTHON__') if _is_ipython: cppcompleter.load_ipython_extension(get_ipython()) utils.iPythonize()
#----------------------------------------------------------------------------- # Author: Danilo Piparo <Danilo.Piparo@cern.ch> CERN # Author: Enric Tejedor <enric.tejedor.saavedra@cern.ch> CERN #----------------------------------------------------------------------------- ################################################################################ # Copyright (C) 1995-2020, Rene Brun and Fons Rademakers. # # All rights reserved. # # # # For the licensing terms see $ROOTSYS/LICENSE. # # For the list of contributors see $ROOTSYS/README/CREDITS. # ################################################################################ from JupyROOT.helpers import cppcompleter, utils if '__IPYTHON__' in __builtins__ and __IPYTHON__: cppcompleter.load_ipython_extension(get_ipython()) utils.iPythonize()
Make module.exports reasonable and only print when being run as main
#!/usr/bin/env node function getUserHome() { return process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME']; } function stringStartsWith (string, prefix) { return string.slice(0, prefix.length) == prefix; } var cwd = process.cwd(); var home = getUserHome(); var p = cwd; for (var v in process.env) { var rw = process.env[v]; switch (v) { case 'HOME': case 'OLDPWD': case 'PWD': break; default: if (stringStartsWith(p, rw)) { p = '$' + v + p.slice(rw.length); } break; } } if (stringStartsWith(p, home)) { p = '~' + p.slice(home.length); } module.exports = p; if (require.main === module) { console.log(p); }
#!/usr/bin/env node function getUserHome() { return process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME']; } function stringStartsWith (string, prefix) { return string.slice(0, prefix.length) == prefix; } var cwd = process.cwd(); var home = getUserHome(); var p = cwd; for (var v in process.env) { var rw = process.env[v]; switch (v) { case 'HOME': case 'OLDPWD': case 'PWD': break; default: if (stringStartsWith(p, rw)) { p = '$' + v + p.slice(rw.length); } break; } } if (stringStartsWith(p, home)) { p = '~' + p.slice(home.length); } console.log(p);
Increase maximum query length to 10K
""" Copyright [2009-2014] EMBL-European Bioinformatics Institute 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. """ # minimum query sequence length MIN_LENGTH = 11 # maximum query sequence length MAX_LENGTH = 10000 # Redis results expiration time EXPIRATION = 60*60*24*7 # seconds # maximum time to run nhmmer MAX_RUN_TIME = 60*60 # seconds # full path to query files QUERY_DIR = '' # full path to results files RESULTS_DIR = '' # full path to nhmmer executable NHMMER_EXECUTABLE = '' # full path to sequence database SEQDATABASE = ''
""" Copyright [2009-2014] EMBL-European Bioinformatics Institute 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. """ # minimum query sequence length MIN_LENGTH = 11 # maximum query sequence length MAX_LENGTH = 1000 # Redis results expiration time EXPIRATION = 60*60*24*7 # seconds # maximum time to run nhmmer MAX_RUN_TIME = 60*60 # seconds # full path to query files QUERY_DIR = '' # full path to results files RESULTS_DIR = '' # full path to nhmmer executable NHMMER_EXECUTABLE = '' # full path to sequence database SEQDATABASE = ''
Add form content to the index page.
from django.shortcuts import render,render_to_response from django.template import RequestContext from new_buildings.models import Builder, ResidentalComplex, NewApartment from new_buildings.forms import SearchForm from feedback.models import Feedback from company.views import about_company_in_digits_context_processor def corporation_benefit_plan(request): return render(request, 'corporation_benefit_plan.html') def index(request): feedbacks = Feedback.objects.all()[:4] context = { 'feedbacks': feedbacks, 'form': SearchForm, } context.update(about_company_in_digits_context_processor(request)) return render(request, 'index.html', context, ) def privacy_policy(request): return render(request, 'privacy_policy.html') def thanks(request): return render(request, 'thanks.html')
from django.shortcuts import render,render_to_response from django.template import RequestContext from new_buildings.models import Builder, ResidentalComplex, NewApartment from feedback.models import Feedback from company.views import about_company_in_digits_context_processor def corporation_benefit_plan(request): return render(request, 'corporation_benefit_plan.html') def index(request): feedbacks = Feedback.objects.all()[:4] context = { 'feedbacks': feedbacks, } context.update(about_company_in_digits_context_processor(request)) return render(request, 'index.html', context, ) def privacy_policy(request): return render(request, 'privacy_policy.html') def thanks(request): return render(request, 'thanks.html')
Update intersphinx links to Django 1.7
# -*- coding: utf-8 -*- # # This file is execfile()d with the current directory set to its containing # directory. import sys, os sys.path.append(os.path.join(os.path.abspath('.'), '_ext')) sys.path.append(os.path.dirname(os.path.abspath('.'))) import analytical # -- General configuration ----------------------------------------------------- project = u'django-analytical' copyright = u'2011, Joost Cassee <joost@cassee.net>' release = analytical.__version__ # The short X.Y version. version = release.rsplit('.', 1)[0] extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'local'] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' add_function_parentheses = True pygments_style = 'sphinx' intersphinx_mapping = { 'http://docs.python.org/2.7': None, 'http://docs.djangoproject.com/en/1.7': 'http://docs.djangoproject.com/en/1.7/_objects/', } # -- Options for HTML output --------------------------------------------------- html_theme = 'default' htmlhelp_basename = 'analyticaldoc' # -- Options for LaTeX output -------------------------------------------------- latex_documents = [ ('index', 'django-analytical.tex', u'Documentation for django-analytical', u'Joost Cassee', 'manual'), ]
# -*- coding: utf-8 -*- # # This file is execfile()d with the current directory set to its containing # directory. import sys, os sys.path.append(os.path.join(os.path.abspath('.'), '_ext')) sys.path.append(os.path.dirname(os.path.abspath('.'))) import analytical # -- General configuration ----------------------------------------------------- project = u'django-analytical' copyright = u'2011, Joost Cassee <joost@cassee.net>' release = analytical.__version__ # The short X.Y version. version = release.rsplit('.', 1)[0] extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'local'] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' add_function_parentheses = True pygments_style = 'sphinx' intersphinx_mapping = { 'http://docs.python.org/2.7': None, 'http://docs.djangoproject.com/en/1.6': 'http://docs.djangoproject.com/en/1.6/_objects/', } # -- Options for HTML output --------------------------------------------------- html_theme = 'default' htmlhelp_basename = 'analyticaldoc' # -- Options for LaTeX output -------------------------------------------------- latex_documents = [ ('index', 'django-analytical.tex', u'Documentation for django-analytical', u'Joost Cassee', 'manual'), ]
Fix calling afterCommand function in ClipBoard.js
import lists from '../core/lists'; export default class Clipboard { constructor(context) { this.context = context; this.$editable = context.layoutInfo.editable; } initialize() { this.$editable.on('paste', this.pasteByEvent.bind(this)); } /** * paste by clipboard event * * @param {Event} event */ pasteByEvent(event) { const clipboardData = event.originalEvent.clipboardData; if (clipboardData && clipboardData.items && clipboardData.items.length) { const item = clipboardData.items.length > 1 ? clipboardData.items[1] : lists.head(clipboardData.items); if (item.kind === 'file' && item.type.indexOf('image/') !== -1) { // paste img file this.context.invoke('editor.insertImagesOrCallback', [item.getAsFile()]); this.context.invoke('editor.afterCommand'); } else if (item.kind === 'string') { // paste text with maxTextLength check if (this.context.invoke('editor.isLimited', clipboardData.getData('Text').length)) { event.preventDefault(); } else { this.context.invoke('editor.afterCommand'); } } } } }
import lists from '../core/lists'; export default class Clipboard { constructor(context) { this.context = context; this.$editable = context.layoutInfo.editable; } initialize() { this.$editable.on('paste', this.pasteByEvent.bind(this)); } /** * paste by clipboard event * * @param {Event} event */ pasteByEvent(event) { const clipboardData = event.originalEvent.clipboardData; if (clipboardData && clipboardData.items && clipboardData.items.length) { // paste img file const item = clipboardData.items.length > 1 ? clipboardData.items[1] : lists.head(clipboardData.items); if (item.kind === 'file' && item.type.indexOf('image/') !== -1) { this.context.invoke('editor.insertImagesOrCallback', [item.getAsFile()]); } this.context.invoke('editor.afterCommand'); } } }
Fix linting errors in GoBot
""" GoBot Example """ from minibot.bot import Bot from minibot.hardware.rpi.gpio import PWM from minibot.interface.servo import Servo L_MOTOR_PIN = 12 R_MOTOR_PIN = 18 class GoBot(Bot): """ GoBot """ def __init__(self): Bot.__init__(self, "GoBot") self.l_motor = Servo(PWM(L_MOTOR_PIN, 2, 15)) self.r_motor = Servo(PWM(R_MOTOR_PIN, 2, 15)) self.l_motor.set(17) self.r_motor.set(13) def run(self): pass if __name__ == "__main__": bot = GoBot() while True: bot.run()
from minibot.bot import Bot from minibot.hardware.rpi.gpio import PWM from minibot.interface.servo import Servo import math import time L_MOTOR_PIN = 12 R_MOTOR_PIN = 18 class GoBot(Bot): def __init__(self): Bot.__init__(self, "GoBot") self.l_motor = Servo(PWM(L_MOTOR_PIN, 2, 15)) self.r_motor = Servo(PWM(R_MOTOR_PIN, 2, 15)) self.l_motor.set(17) self.r_motor.set(13) def run(self): pass if __name__ == "__main__": bot = GoBot() while True: bot.run()
Include user agent in logged CSP reports
<?php namespace Nelmio\SecurityBundle\ContentSecurityPolicy\Violation\Log; use Nelmio\SecurityBundle\ContentSecurityPolicy\Violation\Report; use Psr\Log\LoggerInterface; class Logger { private $logger; private $logFormatter; private $level; public function __construct(LoggerInterface $logger, LogFormatterInterface $logFormatter, $level) { $this->logger = $logger; $this->logFormatter = $logFormatter; $this->level = $level; } public function log(Report $report) { $this->logger->log($this->level, $this->logFormatter->format($report), array('csp-report' => $report->getData(), 'user-agent' => $report->getUserAgent())); } public function getLogger() { return $this->logger; } }
<?php namespace Nelmio\SecurityBundle\ContentSecurityPolicy\Violation\Log; use Nelmio\SecurityBundle\ContentSecurityPolicy\Violation\Report; use Psr\Log\LoggerInterface; class Logger { private $logger; private $logFormatter; private $level; public function __construct(LoggerInterface $logger, LogFormatterInterface $logFormatter, $level) { $this->logger = $logger; $this->logFormatter = $logFormatter; $this->level = $level; } public function log(Report $report) { $this->logger->log($this->level, $this->logFormatter->format($report), array('csp-report' => $report->getData())); } public function getLogger() { return $this->logger; } }
Fix the context scope of SystemJS.register when called from browser's System.register
import { global, isBrowser, isWorker } from './common.js'; import SystemJSProductionLoader from './systemjs-production-loader.js'; SystemJSProductionLoader.prototype.version = VERSION; var System = new SystemJSProductionLoader(); // only set the global System on the global in browsers if (isBrowser || isWorker) { global.SystemJS = System; // dont override an existing System global if (!global.System) { global.System = System; } // rather just extend or set a System.register on the existing System global else { var register = global.System.register; global.System.register = function () { if (register) register.apply(this, arguments); System.register.apply(System, arguments); }; } } if (typeof module !== 'undefined' && module.exports) module.exports = System;
import { global, isBrowser, isWorker } from './common.js'; import SystemJSProductionLoader from './systemjs-production-loader.js'; SystemJSProductionLoader.prototype.version = VERSION; var System = new SystemJSProductionLoader(); // only set the global System on the global in browsers if (isBrowser || isWorker) { global.SystemJS = System; // dont override an existing System global if (!global.System) { global.System = System; } // rather just extend or set a System.register on the existing System global else { var register = global.System.register; global.System.register = function () { if (register) register.apply(this, arguments); System.register.apply(this, arguments); }; } } if (typeof module !== 'undefined' && module.exports) module.exports = System;
Use message as param name
/** Errors @description defines custom errors used for the middleware @exports {class} APIError **/ /** @class APIError @desc given when API response gives error outside of 200 range @param {number} status HTTP Status given in response @param {string} message message given along with the error @param {object} response **/ export class APIError extends Error { constructor(status, message, response) { super(); this.name = 'APIError'; this.status = status; this.statusText = message; this.response = response; this.message = `${status} - ${message}`; } } /** @class CallProcessingError @desc given when an error occurs while processing the remote call action @param {string} msg @param {string} processStep the part of the call process that threw the error @param {error} sourceError (optional) **/ export class CallProcessingError extends Error { constructor(msg, processStep, sourceError) { super(); this.name = 'CallProcessingError'; this.processStep = processStep; this.sourceError = sourceError; this.message = sourceError ? `${msg}\nOriginal Error: ${sourceError}` : msg; } }
/** Errors @description defines custom errors used for the middleware @exports {class} APIError **/ /** @class APIError @desc given when API response gives error outside of 200 range @param {number} status HTTP Status given in response @param {string} data message given along with the error @param {object} response **/ export class APIError extends Error { constructor(status, data, response) { super(); this.name = 'APIError'; this.status = status; this.statusText = data; this.data = data; this.response = response; this.message = `${status} - ${data}`; } } /** @class CallProcessingError @desc given when an error occurs while processing the remote call action @param {string} msg @param {string} processStep the part of the call process that threw the error @param {error} sourceError (optional) **/ export class CallProcessingError extends Error { constructor(msg, processStep, sourceError) { super(); this.name = 'CallProcessingError'; this.processStep = processStep; this.sourceError = sourceError; this.message = sourceError ? `${msg}\nOriginal Error: ${sourceError}` : msg; } }
Disable Elixir and BrowserSync notifications
process.env.DISABLE_NOTIFIER = true; var gulp = require('gulp'); var elixir = require('laravel-elixir'); var argv = require('yargs').argv; var bin = require('./tasks/bin'); elixir.config.assetsPath = 'source/_assets'; elixir.config.publicPath = 'source'; elixir.config.sourcemaps = false; elixir(function(mix) { var env = argv.e || argv.env || 'local'; var port = argv.p || argv.port || 3000; mix.sass('main.scss') .sass('reset.scss') .exec(bin.path() + ' build ' + env, ['./source/*', './source/**/*', '!./source/_assets/**/*']) .browserSync({ port: port, server: { baseDir: 'build_' + env }, proxy: null, files: [ 'build_' + env + '/**/*' ], notify: false, open: false, }); });
var gulp = require('gulp'); var elixir = require('laravel-elixir'); var argv = require('yargs').argv; var bin = require('./tasks/bin'); elixir.config.assetsPath = 'source/_assets'; elixir.config.publicPath = 'source'; elixir.config.sourcemaps = false; elixir(function(mix) { var env = argv.e || argv.env || 'local'; var port = argv.p || argv.port || 3000; mix.sass('main.scss') .sass('reset.scss') .exec(bin.path() + ' build ' + env, ['./source/*', './source/**/*', '!./source/_assets/**/*']) .browserSync({ port: port, server: { baseDir: 'build_' + env }, proxy: null, files: [ 'build_' + env + '/**/*' ] }); });
Include the body of what we are parsing when we get an error
var express = require('express') var bodyParser = require('body-parser') var manifestParser = require('./lib/manifest-parser') var app = express() var port = process.env.PORT || 5000; app.disable('x-powered-by'); app.use(function(req, res, next) { res.set('Access-Control-Allow-Origin', '*'); next(); }); app.post("/parse/", bodyParser.text({type: '*/*', limit: '5mb'}), function(req,res){ var deps = manifestParser.parseDependencies(req.body); res.json(deps); }); app.get("/", function(req,res) { res.send("OK") }); app.use(function(err, req, res, next) { console.error('ERR:', err); console.error('STACK:', err.stack); console.error('FILE:' req.body); res.status(500).send({error: 'Something went wrong.'}); }); app.listen(port, function() { console.log('Listening on', port); });
var express = require('express') var bodyParser = require('body-parser') var manifestParser = require('./lib/manifest-parser') var app = express() var port = process.env.PORT || 5000; app.disable('x-powered-by'); app.use(function(req, res, next) { res.set('Access-Control-Allow-Origin', '*'); next(); }); app.post("/parse/", bodyParser.text({type: '*/*', limit: '5mb'}), function(req,res){ var deps = manifestParser.parseDependencies(req.body); res.json(deps); }); app.get("/", function(req,res) { res.send("OK") }); app.use(function(err, req, res, next) { console.error('ERR:', err); console.error('STACK:', err.stack); res.status(500).send({error: 'Something went wrong.'}); }); app.listen(port, function() { console.log('Listening on', port); });
Change name to reference new schema name
import pyxb.binding.generate import os.path schema_path = '%s/../../pyxb/standard/schemas/kml.xsd' % (os.path.dirname(__file__),) code = pyxb.binding.generate.GeneratePython(schema_file=schema_path) rv = compile(code, 'test', 'exec') eval(rv) from pyxb.exceptions_ import * import unittest class TestKML (unittest.TestCase): def testAngle180 (self): self.assertEqual(25.4, angle360(25.4)) self.assertRaises(BadTypeValueError, angle360, 420.0) self.assertRaises(BadTypeValueError, angle360, -361.0) if __name__ == '__main__': unittest.main()
import pyxb.binding.generate import os.path schema_path = '%s/../../pyxb/standard/schemas/kml21.xsd' % (os.path.dirname(__file__),) code = pyxb.binding.generate.GeneratePython(schema_file=schema_path) rv = compile(code, 'test', 'exec') eval(rv) from pyxb.exceptions_ import * import unittest class TestKML (unittest.TestCase): def testAngle180 (self): self.assertEqual(25.4, angle360(25.4)) self.assertRaises(BadTypeValueError, angle360, 420.0) self.assertRaises(BadTypeValueError, angle360, -361.0) if __name__ == '__main__': unittest.main()
Remove unused div and style
import React, {PropTypes} from 'react' import classNames from 'classnames' const VisHeader = ({views, view, onToggleView, name}) => ( <div className="graph-heading"> {views.length ? <ul className="toggle toggle-sm"> {views.map(v => ( <li key={v} onClick={() => onToggleView(v)} className={classNames('toggle-btn ', {active: view === v})} > {v} </li> ))} </ul> : null} <div className="graph-title">{name}</div> </div> ) const {arrayOf, func, string} = PropTypes VisHeader.propTypes = { views: arrayOf(string).isRequired, view: string.isRequired, onToggleView: func.isRequired, name: string.isRequired, } export default VisHeader
import React, {PropTypes} from 'react' import classNames from 'classnames' const VisHeader = ({views, view, onToggleView, name}) => ( <div className="graph-heading"> <div className="graph-actions"> {views.length ? <ul className="toggle toggle-sm"> {views.map(v => ( <li key={v} onClick={() => onToggleView(v)} className={classNames('toggle-btn ', {active: view === v})} > {v} </li> ))} </ul> : null} </div> <div className="graph-title">{name}</div> </div> ) const {arrayOf, func, string} = PropTypes VisHeader.propTypes = { views: arrayOf(string).isRequired, view: string.isRequired, onToggleView: func.isRequired, name: string.isRequired, } export default VisHeader
Update method to use Match check for audit-argument-checks compliance. If a system is using the presence package and also forcing security checks using the Meteor package (audit-argument-checks)[http://docs.meteor.com/#auditargumentchecks] The security check will fail, throwing errors. This adds the checks for all parameters of Meteor Methods to satisfy the audit-argument-checks package
PRESENCE_TIMEOUT_MS = 10000; PRESENCE_INTERVAL = 1000; // a method to indicate that the user is still online Meteor.methods({ setPresence: function(sessionId, state) { // console.log(sessionId, state); check(sessionId, String); check(state, Match.Any); // we use the sessionId to tell if this is a new record or not var props = { state: state, lastSeen: new Date() }; var userId = _.isUndefined(Meteor.userId) ? null : Meteor.userId(); if (sessionId && Meteor.presences.findOne(sessionId)) { var update = {$set: props}; // need to unset userId if it's not defined as they may have just logged out if (userId) { update.$set.userId = userId; } else { update.$unset = {userId: true}; } Meteor.presences.update({_id: sessionId}, update); return sessionId; } else { props.userId = userId; return Meteor.presences.insert(props) } } }); Meteor.setInterval(function() { var since = new Date(new Date().getTime() - PRESENCE_TIMEOUT_MS); Meteor.presences.remove({lastSeen: {$lt: since}}); }, PRESENCE_INTERVAL);
PRESENCE_TIMEOUT_MS = 10000; PRESENCE_INTERVAL = 1000; // a method to indicate that the user is still online Meteor.methods({ setPresence: function(sessionId, state) { // console.log(sessionId, state); // we use the sessionId to tell if this is a new record or not var props = { state: state, lastSeen: new Date() }; var userId = _.isUndefined(Meteor.userId) ? null : Meteor.userId(); if (sessionId && Meteor.presences.findOne(sessionId)) { var update = {$set: props}; // need to unset userId if it's not defined as they may have just logged out if (userId) { update.$set.userId = userId; } else { update.$unset = {userId: true}; } Meteor.presences.update({_id: sessionId}, update); return sessionId; } else { props.userId = userId; return Meteor.presences.insert(props) } } }); Meteor.setInterval(function() { var since = new Date(new Date().getTime() - PRESENCE_TIMEOUT_MS); Meteor.presences.remove({lastSeen: {$lt: since}}); }, PRESENCE_INTERVAL);
Add unit test to pass Trigger instance.
import unittest import mock from chainer import testing from chainer.training import extensions from chainer.training import trigger @testing.parameterize( {'trigger': ('epoch', 2)}, {'trigger': ('iteration', 10)}, {'trigger': trigger.IntervalTrigger(5, 'epoch')}, {'trigger': trigger.IntervalTrigger(20, 'iteration')}, ) class TestSnapshotObject(unittest.TestCase): def test_trigger(self): target = mock.MagicMock() snapshot_object = extensions.snapshot_object(target, 'myfile.dat', trigger=self.trigger) self.assertEqual(snapshot_object.trigger, self.trigger) @testing.parameterize( {'trigger': ('epoch', 2)}, {'trigger': ('iteration', 10)}, {'trigger': trigger.IntervalTrigger(5, 'epoch')}, {'trigger': trigger.IntervalTrigger(20, 'iteration')}, ) class TestSnapshot(unittest.TestCase): def test_trigger(self): snapshot = extensions.snapshot(trigger=self.trigger) self.assertEqual(snapshot.trigger, self.trigger) testing.run_module(__name__, __file__)
import unittest import mock from chainer import testing from chainer.training import extensions @testing.parameterize( {'trigger': ('epoch', 2)}, {'trigger': ('iteration', 10)}, ) class TestSnapshotObject(unittest.TestCase): def test_trigger(self): target = mock.MagicMock() snapshot_object = extensions.snapshot_object(target, 'myfile.dat', trigger=self.trigger) self.assertEqual(snapshot_object.trigger, self.trigger) @testing.parameterize( {'trigger': ('epoch', 2)}, {'trigger': ('iteration', 10)}, ) class TestSnapshot(unittest.TestCase): def test_trigger(self): snapshot = extensions.snapshot(trigger=self.trigger) self.assertEqual(snapshot.trigger, self.trigger) testing.run_module(__name__, __file__)
Check if data is not None instead of if data is true
import json from os.path import exists from os import mkdir class Config: config_path = "config/" def __init__(self, filename, data=None, load=True): self.filepath = "{}{}.json".format(self.config_path, filename) if not exists(self.config_path): mkdir(self.config_path) loaded_data = None if load: loaded_data = self.load() if data is not None and not loaded_data: self.data = data elif loaded_data: self.data = loaded_data else: self.data = None if not self.data == loaded_data: self.save() def save(self): with open(self.filepath, "w") as f: json.dump(self.data, f) def load(self): if exists(self.filepath): with open(self.filepath, "r") as f: return json.load(f) return None
import json from os.path import exists from os import mkdir class Config: config_path = "config/" def __init__(self, filename, data=None, load=True): self.filepath = "{}{}.json".format(self.config_path, filename) if not exists(self.config_path): mkdir(self.config_path) loaded_data = None if load: loaded_data = self.load() if data and not loaded_data: self.data = data elif loaded_data: self.data = loaded_data else: self.data = None if not self.data == loaded_data: self.save() def save(self): with open(self.filepath, "w") as f: json.dump(self.data, f) def load(self): if exists(self.filepath): with open(self.filepath, "r") as f: return json.load(f) return None
Add de421 as an install dependency
from distutils.core import setup import skyfield # to learn the version setup( name='skyfield', version=skyfield.__version__, description=skyfield.__doc__, long_description=open('README.rst').read(), license='MIT', author='Brandon Rhodes', author_email='brandon@rhodesmill.org', url='http://github.com/brandon-rhodes/python-skyfield/', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Topic :: Scientific/Engineering :: Astronomy', ], packages=[ 'skyfield', 'skyfield.tests' ], install_requires=['de421', 'jplephem', 'numpy', 'sgp4'], )
from distutils.core import setup import skyfield # to learn the version setup( name='skyfield', version=skyfield.__version__, description=skyfield.__doc__, long_description=open('README.rst').read(), license='MIT', author='Brandon Rhodes', author_email='brandon@rhodesmill.org', url='http://github.com/brandon-rhodes/python-skyfield/', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Topic :: Scientific/Engineering :: Astronomy', ], packages=[ 'skyfield', 'skyfield.tests' ], install_requires=['jplephem', 'numpy', 'sgp4'], )
FIX: Use entwine so that a new link has the correct settigns in the GUI
/*jslint white: true */ (function($) { $.entwine(function($) { $('#Form_ItemEditForm_LinkType').entwine({ onmatch: function(e) { if(this.val() == 'Internal') { $('#Form_ItemEditForm_URL_Holder').hide(); } else { $('#Form_ItemEditForm_InternalPageID_Holder').hide(); } this._super(); }, onchange: function(e) { if(this.val() == 'Internal') { $('#Form_ItemEditForm_URL_Holder').hide(); $('#Form_ItemEditForm_InternalPageID_Holder').show(); } else { $('#Form_ItemEditForm_URL_Holder').show(); $('#Form_ItemEditForm_InternalPageID_Holder').hide(); } } }); }); })(jQuery);
/*jslint white: true */ (function($) { $(document).ready(function() { // Find the select box, named differently on the update and add forms var sel = $('#Form_ItemEditForm_LinkType'); // hide either the internal or external link editing box depending on which link type the link is // (internal or external) if(sel.val() == 'Internal') { $('#Form_ItemEditForm_URL_Holder').hide(); } else { $('#Form_ItemEditForm_InternalPageID_Holder').hide(); } // toggle boxes on drop down change sel.change(function(e) { if(sel.val() == 'Internal') { $('#Form_ItemEditForm_URL_Holder').hide(); $('#Form_ItemEditForm_InternalPageID_Holder').show(); } else { $('#Form_ItemEditForm_URL_Holder').show(); $('#Form_ItemEditForm_InternalPageID_Holder').hide(); } }); }); })(jQuery);
Enable the new collections UI on stage
import { amoStageCDN } from './lib/shared'; const staticHost = 'https://addons-amo-cdn.allizom.org'; module.exports = { staticHost, CSP: { directives: { fontSrc: [ staticHost, ], scriptSrc: [ staticHost, 'https://www.google-analytics.com/analytics.js', ], styleSrc: [staticHost], imgSrc: [ "'self'", 'data:', amoStageCDN, staticHost, 'https://www.google-analytics.com', ], }, }, enableNewCollectionsUI: true, enableUserProfile: true, };
import { amoStageCDN } from './lib/shared'; const staticHost = 'https://addons-amo-cdn.allizom.org'; module.exports = { staticHost, CSP: { directives: { fontSrc: [ staticHost, ], scriptSrc: [ staticHost, 'https://www.google-analytics.com/analytics.js', ], styleSrc: [staticHost], imgSrc: [ "'self'", 'data:', amoStageCDN, staticHost, 'https://www.google-analytics.com', ], }, }, enableUserProfile: true, };
Use a factory function for simple arg-passing actions
var { ADD_LESSON, ADD_STEP, DELETE_LESSON, DELETE_STEP, IMPORT_LESSONS, SELECT_LESSON, SELECT_STEP, TOGGLE_EDITING, UPDATE_LESSON, UPDATE_STEP } = require('../ActionTypes') var createAction = (type, ...props) => (...args) => props.reduce((action, prop, i) => (action[prop] = args[i], action), {type}) module.exports = { addLesson: createAction(ADD_LESSON), addStep: createAction(ADD_STEP), deleteLesson: createAction(DELETE_LESSON), deleteStep: createAction(DELETE_STEP), importLessons: createAction(IMPORT_LESSONS, 'lessons'), selectLesson: createAction(SELECT_LESSON, 'lessonIndex'), selectStep: createAction(SELECT_STEP, 'stepIndex'), toggleEditing: createAction(TOGGLE_EDITING, 'editing'), updateLesson: createAction(UPDATE_LESSON, 'update'), updateStep: createAction(UPDATE_STEP, 'update') }
var { ADD_LESSON, ADD_STEP, DELETE_LESSON, DELETE_STEP, IMPORT_LESSONS, SELECT_LESSON, SELECT_STEP, TOGGLE_EDITING, UPDATE_LESSON, UPDATE_STEP } = require('../ActionTypes') function addLesson() { return { type: ADD_LESSON } } function addStep() { return { type: ADD_STEP } } function deleteLesson() { return { type: DELETE_LESSON } } function deleteStep() { return { type: DELETE_STEP } } function importLessons(lessons) { return { type: IMPORT_LESSONS, lessons } } function selectLesson(lessonIndex) { return { type: SELECT_LESSON, lessonIndex } } function selectStep(stepIndex) { return { type: SELECT_STEP, stepIndex } } function toggleEditing(editing) { return { type: TOGGLE_EDITING, editing } } function updateLesson(update) { return { type: UPDATE_LESSON, update } } function updateStep(update) { return { type: UPDATE_STEP, update } } module.exports = { toggleEditing, addLesson, selectLesson, updateLesson, deleteLesson, importLessons, addStep, selectStep, updateStep, deleteStep }
Fix wrong options variable assignment This caused the name options's function to ran only for the first file.
'use strict'; var gutil = require('gulp-util'); var through = require('through2'); var assign = require('object-assign'); var nunjucks = require('nunjucks'); module.exports = function (opts) { return through.obj(function (file, enc, cb) { if (file.isNull()) { cb(null, file); return; } if (file.isStream()) { cb(new gutil.PluginError('gulp-nunjucks', 'Streaming not supported')); return; } var options = assign({}, opts); var filePath = file.path; try { options.name = typeof options.name === 'function' && options.name(file) || file.relative; file.contents = new Buffer(nunjucks.precompileString(file.contents.toString(), options)); file.path = gutil.replaceExtension(file.path, '.js'); this.push(file); } catch (err) { this.emit('error', new gutil.PluginError('gulp-nunjucks', err, {fileName: filePath})); } cb(); }); };
'use strict'; var gutil = require('gulp-util'); var through = require('through2'); var assign = require('object-assign'); var nunjucks = require('nunjucks'); module.exports = function (opts) { return through.obj(function (file, enc, cb) { if (file.isNull()) { cb(null, file); return; } if (file.isStream()) { cb(new gutil.PluginError('gulp-nunjucks', 'Streaming not supported')); return; } opts = assign({}, opts); var filePath = file.path; try { opts.name = typeof opts.name === 'function' && opts.name(file) || file.relative; file.contents = new Buffer(nunjucks.precompileString(file.contents.toString(), opts)); file.path = gutil.replaceExtension(file.path, '.js'); this.push(file); } catch (err) { this.emit('error', new gutil.PluginError('gulp-nunjucks', err, {fileName: filePath})); } cb(); }); };
refactor(make-dir): Update test to move test double replacement to before block
'use strict'; const td = require('testdouble'); const MakeDir = require('../../../src/utils/make-dir'); const fs = require('fs'); const path = require('path'); describe('MakeDir', () => { context('when base and destPath', () => { let mkdirSync; beforeEach(() => { mkdirSync = td.replace(fs, 'mkdirSync'); }); afterEach(() => { td.reset(); }); it('makes the directory', () => { let base = './'; const destPath = 'foo/bar'; MakeDir(base, destPath); // Verify replaced property was invoked. destPath.split('/').forEach((segment) => { base = path.join(base, segment); td.verify(mkdirSync(base)); }); }); }); });
'use strict'; const td = require('testdouble'); const MakeDir = require('../../../src/utils/make-dir'); const fs = require('fs'); const path = require('path'); describe('MakeDir', () => { context('when base and destPath', () => { afterEach(() => { td.reset(); }); it('makes the directory', () => { var mkdirSync = td.replace(fs, 'mkdirSync'); let base = './'; const destPath = 'foo/bar'; MakeDir(base, destPath); // Verify replaced property was invoked. destPath.split('/').forEach((segment) => { base = path.join(base, segment); td.verify(mkdirSync(base)); }); }); }); });
Throw exception if no attribute set id is found
<?php namespace SnowIO\AttributeSetCode\Plugin; use Magento\Catalog\Api\Data\ProductInterface; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Phrase; class AttributeSetCodeProductRepositoryPlugin { private $attributeSetCodeRepository; public function __construct(\SnowIO\AttributeSetCode\Model\AttributeSetCodeRepository $attributeSetCodeRepository) { $this->attributeSetCodeRepository = $attributeSetCodeRepository; } public function beforeSave( \Magento\Catalog\Api\ProductRepositoryInterface $productRepository, ProductInterface $product, $saveOptions = false ) { if (!$extensionAttributes = $product->getExtensionAttributes()) { return [$product, $saveOptions]; } if (null === ($attributeSetCode = $extensionAttributes->getAttributeSetCode())) { return [$product, $saveOptions]; } $attributeSetId = $this->attributeSetCodeRepository->getAttributeSetId(4, $attributeSetCode); if ($attributeSetId === null) { throw new LocalizedException(new Phrase("The specified attribute set code %1 does not exist", [$attributeSetCode])); } $product->setAttributeSetId($attributeSetId); return [$product, $saveOptions]; } }
<?php namespace SnowIO\AttributeSetCode\Plugin; use Magento\Catalog\Api\Data\ProductInterface; class AttributeSetCodeProductRepositoryPlugin { private $attributeSetCodeRepository; public function __construct(\SnowIO\AttributeSetCode\Model\AttributeSetCodeRepository $attributeSetCodeRepository) { $this->attributeSetCodeRepository = $attributeSetCodeRepository; } public function beforeSave( \Magento\Catalog\Api\ProductRepositoryInterface $productRepository, ProductInterface $product, $saveOptions = false ) { if (!$extensionAttributes = $product->getExtensionAttributes()) { return [$product, $saveOptions]; } if (null === ($attributeSetCode = $extensionAttributes->getAttributeSetCode())) { return [$product, $saveOptions]; } $attributeSetId = $this->attributeSetCodeRepository->getAttributeSetId(4, $attributeSetCode); $product->setAttributeSetId($attributeSetId); return [$product, $saveOptions]; } }
Remove unsetting of request flash session key No need to unset it.
<?php /* * Lily, a web application library * * (c) Luke Morton <lukemorton.dev@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Lily\Middleware; class Flash { public function __invoke($handler) { return function ($request) use ($handler) { if (isset($request['session']['_flash'])) { $request['flash'] = $request['session']['_flash']; } $response = $handler($request); if (isset($response['flash'])) { $response['session']['_flash'] = $response['flash']; } else if (isset($request['flash'])) { $response['session']['_flash'] = NULL; } return $response; }; } }
<?php /* * Lily, a web application library * * (c) Luke Morton <lukemorton.dev@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Lily\Middleware; class Flash { public function __invoke($handler) { return function ($request) use ($handler) { if (isset($request['session']['_flash'])) { $request['flash'] = $request['session']['_flash']; unset($request['session']['_flash']); } $response = $handler($request); if (isset($response['flash'])) { $response['session']['_flash'] = $response['flash']; } else if (isset($request['flash'])) { $response['session']['_flash'] = NULL; } return $response; }; } }
Update travel factory to ensure return date is after departure date
<?php declare(strict_types=1); namespace Database\Factories; use App\Models\User; use Illuminate\Database\Eloquent\Factories\Factory; /** * A factory for Travel. * * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Travel> */ class TravelFactory extends Factory { /** * Define the model's default state. * * @return array<string,string|int|\DateTime> */ public function definition() { return [ 'name' => $this->faker->word(), 'primary_contact_user_id' => User::all()->random()->id, 'destination' => $this->faker->word(), 'departure_date' => $this->faker->dateTimeBetween('now', '1 week'), 'return_date' => $this->faker->dateTimeBetween('1 week', '2 weeks'), 'fee_amount' => (string) $this->faker->randomFloat(2, 0, 1000), 'included_with_fee' => $this->faker->paragraph(), ]; } }
<?php declare(strict_types=1); namespace Database\Factories; use App\Models\User; use Illuminate\Database\Eloquent\Factories\Factory; /** * A factory for Travel. * * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Travel> */ class TravelFactory extends Factory { /** * Define the model's default state. * * @return array<string,string|int|\DateTime> */ public function definition() { return [ 'name' => $this->faker->word(), 'primary_contact_user_id' => User::all()->random()->id, 'destination' => $this->faker->word(), 'departure_date' => $this->faker->dateTimeBetween('now', '1 year'), 'return_date' => $this->faker->dateTimeBetween('now', '1 year'), 'fee_amount' => (string) $this->faker->randomFloat(2, 0, 1000), 'included_with_fee' => $this->faker->paragraph(), ]; } }
Revert "refactor(StackedPaneDisplay): Experiment with Save button on top." This reverts commit 42a08c15a62bae19466052598a2a2416f8641a1a.
import PropTypes from 'prop-types' import React from 'react' import FormNavigationButtons from './form-navigation-buttons' import { PageHeading, StackedPaneContainer } from './styled' /** * This component handles the flow between screens for new OTP user accounts. */ const StackedPaneDisplay = ({ onCancel, paneSequence, title }) => ( <> {title && <PageHeading>{title}</PageHeading>} { paneSequence.map(({ pane: Pane, props, title }, index) => ( <StackedPaneContainer key={index}> <h3>{title}</h3> <div><Pane {...props} /></div> </StackedPaneContainer> )) } <FormNavigationButtons backButton={{ onClick: onCancel, text: 'Cancel' }} okayButton={{ text: 'Save Preferences', type: 'submit' }} /> </> ) StackedPaneDisplay.propTypes = { onCancel: PropTypes.func.isRequired, paneSequence: PropTypes.array.isRequired } export default StackedPaneDisplay
import PropTypes from 'prop-types' import React from 'react' import { Button } from 'react-bootstrap' import FormNavigationButtons from './form-navigation-buttons' import { PageHeading, StackedPaneContainer } from './styled' /** * This component handles the flow between screens for new OTP user accounts. */ const StackedPaneDisplay = ({ onCancel, paneSequence, title }) => ( <> {title && ( <PageHeading> <Button bsStyle='primary' className='pull-right' type='submit'>Save</Button> {title} </PageHeading> )} { paneSequence.map(({ pane: Pane, props, title }, index) => ( <StackedPaneContainer key={index}> <h3>{title}</h3> <div><Pane {...props} /></div> </StackedPaneContainer> )) } <FormNavigationButtons backButton={{ onClick: onCancel, text: 'Cancel' }} okayButton={{ text: 'Save', type: 'submit' }} /> </> ) StackedPaneDisplay.propTypes = { onCancel: PropTypes.func.isRequired, paneSequence: PropTypes.array.isRequired } export default StackedPaneDisplay
Add logging for requested password and result
#!/usr/bin/python3 import logging import subprocess import sys from flask import Flask, request app = Flask(__name__) SPASS=sys.argv[1] if len(sys.argv) > 1 else '/usr/local/bin/spass' @app.before_first_request def setup(): app.logger.addHandler(logging.StreamHandler()) app.logger.setLevel(logging.INFO) def call_spass(name, master): p = subprocess.Popen([ SPASS, 'get', name], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) try: out, err = p.communicate(bytes('%s\n' % master, 'utf8'), timeout=5) except subprocess.TimeoutExpired: p.kill() return 'Error: spass process timedout' return (out if p.returncode == 0 else err), p.returncode @app.route('/getpwd', methods=['POST']) def getpwd(): val, code = call_spass(request.form['name'], request.form['master']) app.logger.info('%s %s %d', request.remote_addr, request.form['name'], code) return val @app.route('/') def index(): return app.send_static_file('index.html') if __name__ == '__main__': app.run()
#!/usr/bin/python3 import subprocess import sys from flask import Flask, request app = Flask(__name__) SPASS=sys.argv[1] if len(sys.argv) > 1 else '/usr/local/bin/spass' def call_spass(name, master): p = subprocess.Popen([ SPASS, 'get', name], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) try: out, err = p.communicate(bytes('%s\n' % master, 'utf8'), timeout=5) except subprocess.TimeoutExpired: p.kill() return 'Error: spass process timedout' return out if p.returncode == 0 else err @app.route('/getpwd', methods=['POST']) def getpwd(): return call_spass(request.form['name'], request.form['master']) @app.route('/') def index(): return app.send_static_file('index.html') if __name__ == '__main__': app.run()
Add gulp task to deploy jsDocs
var gulp = require('gulp'), jsdoc = require('gulp-jsdoc'), ghPages = require('gulp-gh-pages'), docsSrcDir = './assets/js/**/*.js', docsDestDir = './docs/js', jsDocTask; jsDocTask = function() { return gulp.src(docsSrcDir) .pipe( jsdoc(docsDestDir, { path: './node_modules/jaguarjs-jsdoc', applicationName: 'Dough JavaScript', cleverLinks: true, copyright: 'Copyright Money Advice Service &copy;', linenums: true, collapseSymbols: false }, { plugins: ['plugins/markdown'], } ) ); }; gulp.task('deploy', function() { return gulp.src(docsDestDir + '/**/*') .pipe(ghPages()); }); gulp.task('default', ['jsdoc']); gulp.task('build', ['jsdoc', 'deploy']); gulp.task('jsdoc', jsDocTask); gulp.task('watch', function() { jsDocTask(); gulp.watch(docsSrcDir, ['jsdoc']); });
var gulp = require('gulp'), jsdoc = require('gulp-jsdoc'), docsSrcDir = './assets/js/**/*.js', docsDestDir = './docs/js', jsDocTask; jsDocTask = function() { return gulp.src(docsSrcDir) .pipe( jsdoc(docsDestDir, { path: './node_modules/jaguarjs-jsdoc', applicationName: 'Dough JavaScript', cleverLinks: true, copyright: 'Copyright Money Advice Service &copy;', linenums: true, collapseSymbols: false }, { plugins: ['plugins/markdown'], } ) ); }; gulp.task('default', ['jsdoc']); gulp.task('jsdoc', jsDocTask); gulp.task('watch', function() { jsDocTask(); gulp.watch(docsSrcDir, ['jsdoc']); });
Add more functionality to vectors
class Vector2D { constructor(x, y) { this.x = x; this.y = y; } add(vec) { return new Vector2D(this.x + vec.x, this.y + vec.y); } multiply(factor) { return new Vector2D(this.x * factor, this.y * factor); } length() { return Math.sqrt(this.x * this.x, this.y * this.y); } angle() { return Math.atan2(this.y, this.x) * (180 / Math.PI); } toPolar() { return [this.angle(), this.length()]; } } Vector2D.fromPolar = function(deg, len) { let rad = deg / (180 / Math.PI), xf = Math.round(Math.cos(rad) * 1000) / 1000, yf = Math.round(Math.sin(rad) * 1000) / 1000; return new Vector2D(xf, yf).multiply(len); }; export default function Vecor2DFactory(...args) { return new Vector2D(...args); };
class Vector2D { constructor(x, y) { this.x = x; this.y = y; } add(vec) { return new Vector2D(this.x + vec.x, this.y + vec.y); } multiply(factor) { return new Vector2D(this.x * factor, this.y * factor); } } Vector2D.fromPolar = function(deg, len) { let rad = deg * (180 / Math.PI), xf = Math.round(Math.cos(rad) * 1000) / 1000, yf = Math.round(Math.sin(rad) * 1000) / 1000; return new Vector2D(xf, yf).multiply(len); }; export default function Vecor2DFactory(...args) { return new Vector2D(...args); };
Remove ParseTime from mysql connection
/* * Copyright 2015 Benoit LETONDOR * * 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 db import ( "database/sql" _ "github.com/go-sql-driver/mysql" ) var database *sql.DB func Init(user string, pass string, schema string) (*sql.DB, error) { // Init Mysql DB dbLink, err := sql.Open("mysql", user+":"+pass+"@"+schema) if err != nil { return nil, err } // Open doesn't open a connection. Validate DSN data: err = dbLink.Ping() if err != nil { return nil, err } // Set up global var database = dbLink return database, nil }
/* * Copyright 2015 Benoit LETONDOR * * 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 db import ( "database/sql" _ "github.com/go-sql-driver/mysql" ) var database *sql.DB func Init(user string, pass string, schema string) (*sql.DB, error) { // Init Mysql DB dbLink, err := sql.Open("mysql", user+":"+pass+"@"+schema+"?parseTime=True") if err != nil { return nil, err } // Open doesn't open a connection. Validate DSN data: err = dbLink.Ping() if err != nil { return nil, err } // Set up global var database = dbLink return database, nil }
Test to get single instance in PoolImpl
/** * Copyright 2015 Peter Nerg * * 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 simplepool; import org.junit.Test; import javascalautils.Try; import simplepool.Constants.PoolMode; /** * Test the class {@link PoolImpl} * @author Peter Nerg */ public class TestPoolImpl extends BaseAssert { private final PoolImpl<PoolableObject> pool = new PoolImpl<>(() -> new PoolableObject(), 2, po -> true, po -> {}, PoolMode.FIFO); @Test public void getInstance() throws Throwable { Try<PoolableObject> instance = pool.getInstance(); assertTrue(instance.isSuccess()); assertTrue(instance.get() instanceof PoolableObject); } @Test public void return_nullInstance() { pool.returnInstance(null); } }
/** * Copyright 2015 Peter Nerg * * 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 simplepool; import org.junit.Test; import simplepool.Constants.PoolMode; /** * Test the class {@link PoolImpl} * @author Peter Nerg */ public class TestPoolImpl extends BaseAssert { private final PoolImpl<PoolableObject> pool = new PoolImpl<>(() -> new PoolableObject(), 2, po -> true, po -> {}, PoolMode.FIFO); @Test public void return_nullInstance() { pool.returnInstance(null); } }
Use the interface for this
package com.mooo.aimmac23.hub.proxy; import java.util.Map; import org.openqa.grid.internal.utils.CapabilityMatcher; public class ReliableCapabilityMatcher implements CapabilityMatcher { private CapabilityMatcher innerMatcher; private ReliabilityAwareProxy proxy; public ReliableCapabilityMatcher(ReliabilityAwareProxy proxy, CapabilityMatcher innerMatcher) { this.proxy = proxy; this.innerMatcher = innerMatcher; } @Override public boolean matches(Map<String, Object> currentCapability, Map<String, Object> requestedCapability) { // to allow the node to be tested - we're calling enough internal // methods to ensure that we're calling this on the correct node if(requestedCapability.containsKey("proxyId")) { return innerMatcher.matches(currentCapability, requestedCapability); } // check to see if we're allowed to use that config if(!proxy.isCapabilityWorking(currentCapability)) { return false; } // otherwise, match on the capabilities return innerMatcher.matches(currentCapability, requestedCapability); } }
package com.mooo.aimmac23.hub.proxy; import java.util.Map; import org.openqa.grid.internal.utils.CapabilityMatcher; public class ReliableCapabilityMatcher implements CapabilityMatcher { private CapabilityMatcher innerMatcher; private ReliableProxy proxy; public ReliableCapabilityMatcher(ReliableProxy proxy, CapabilityMatcher innerMatcher) { this.proxy = proxy; this.innerMatcher = innerMatcher; } @Override public boolean matches(Map<String, Object> currentCapability, Map<String, Object> requestedCapability) { // to allow the node to be tested if(requestedCapability.containsKey("proxyId")) { return innerMatcher.matches(currentCapability, requestedCapability); } // check to see if we're allowed to use that config if(!proxy.isCapabilityWorking(currentCapability)) { return false; } // otherwise, match on the capabilities return innerMatcher.matches(currentCapability, requestedCapability); } }
Fix copyRows() and sqlite connection
<?php class OC_Migrate_Provider_Bookmarks extends OC_Migrate_Provider{ // Create the xml for the user supplied function export( $uid ){ OC_Log::write('migration','starting export for bookmarks',OC_Log::INFO); $options = array( 'table'=>'bookmarks', 'matchcol'=>'user_id', 'matchval'=>$uid, 'idcol'=>'id' ); $ids = OC_Migrate::copyRows( $options ); $options = array( 'table'=>'bookmarks_tags', 'matchcol'=>'bookmark_id', 'matchval'=>$ids ); // Export tags OC_Migrate::copyRows( $options ); } // Import function for bookmarks function import( $data, $uid ){ // new id mapping $newids = array(); // Import bookmarks foreach($data['bookmarks'] as $bookmark){ $bookmark['user_id'] = $uid; // import to the db now $newids[$bookmark['id']] = OC_DB::insertid(); } // Import tags foreach($data['bookmarks_tags'] as $tag){ // Map the new ids $tag['id'] = $newids[$tag['id']]; // Import to the db now using OC_DB } } } new OC_Migrate_Provider_Bookmarks( 'bookmarks' );
<?php class OC_Migrate_Provider_Bookmarks extends OC_Migrate_Provider{ // Create the xml for the user supplied function export( $uid ){ $options = array( 'table'=>'bookmarks', 'matchcol'=>'user_id', 'matchval'=>$uid, 'idcol'=>'id' ); $ids = OC_Migrate::copyRows( $options ); $ids = array('1'); $options = array( 'table'=>'bookmarks_tags', 'matchcol'=>'bookmark_id', 'matchval'=>$ids ); // Export tags OC_Migrate::copyRows( $options ); } // Import function for bookmarks function import( $data, $uid ){ // new id mapping $newids = array(); // Import bookmarks foreach($data['bookmarks'] as $bookmark){ $bookmark['user_id'] = $uid; // import to the db now $newids[$bookmark['id']] = OC_DB::insertid(); } // Import tags foreach($data['bookmarks_tags'] as $tag){ // Map the new ids $tag['id'] = $newids[$tag['id']]; // Import to the db now using OC_DB } } } new OC_Migrate_Provider_Bookmarks( 'bookmarks' );
Remove paragraph trimming in the Medium Editor validator to stop it from trimming paragraphs that contain only images.
'use strict'; var sanitizeHTML = require('sanitize-html'); function decodeHtml(html) { var txt = document.createElement("textarea"); txt.innerHTML = html; return txt.value; } function checkVal($field) { var fVal = $field.val().trim(); if (!fVal.length || fVal == "<p>&nbsp;</p>" || fVal == "&nbsp;" || fVal == "<p><br /></p>") { $field.val(''); } // replace double quotes with single quotes to avoid invalid json //fVal = fVal.replace(/\\([\s\S])|(")/g, "'"); //decode text the medium editor encodes, or the medium editor will remove it the second time fVal = decodeHtml(fVal); fVal = sanitizeHTML(fVal, { allowedTags: [ 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'a', 'u', 'ul', 'ol', 'nl', 'li', 'b', 'i', 'strong', 'em', 'strike', 'hr', 'br', 'img', 'blockquote', 'span' ], allowedAttributes: { 'a': [ 'href', 'title', 'alt' ], 'img': [ 'src', 'style'] } }); $field.val(fVal); if (!$field[0].checkValidity()) { $field.parent().addClass('invalid'); } else { $field.parent().removeClass('invalid'); } } module.exports = { checkVal: checkVal };
'use strict'; var sanitizeHTML = require('sanitize-html'); function decodeHtml(html) { var txt = document.createElement("textarea"); txt.innerHTML = html; return txt.value; } function checkVal($field) { var fVal = $field.val().trim(); if (!fVal.length || fVal == "<p>&nbsp;</p>" || fVal == "&nbsp;" || fVal == "<p><br /></p>") { $field.val(''); } // replace double quotes with single quotes to avoid invalid json //fVal = fVal.replace(/\\([\s\S])|(")/g, "'"); //decode text the medium editor encodes, or the medium editor will remove it the second time fVal = decodeHtml(fVal); fVal = sanitizeHTML(fVal, { allowedTags: [ 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'a', 'u', 'ul', 'ol', 'nl', 'li', 'b', 'i', 'strong', 'em', 'strike', 'hr', 'br', 'img', 'blockquote', 'span' ], allowedAttributes: { 'a': [ 'href', 'title', 'alt' ], 'img': [ 'src', 'style'] }, exclusiveFilter: function(frame) { return frame.tag === 'p' && !frame.text.trim(); } }); $field.val(fVal); if (!$field[0].checkValidity()) { $field.parent().addClass('invalid'); } else { $field.parent().removeClass('invalid'); } } module.exports = { checkVal: checkVal };
Update requests to address security concern
from setuptools import setup, find_packages setup(name='citrination-client', version='4.6.0', url='http://github.com/CitrineInformatics/python-citrination-client', description='Python client for accessing the Citrination api', packages=find_packages(exclude=('docs')), install_requires=[ 'requests>=2.20.0<3', 'pypif', 'six<2', 'pyyaml' ], extras_require={ "dev": [ 'sphinx_rtd_theme', 'sphinx', ], "test": [ 'requests_mock', 'pytest', ] })
from setuptools import setup, find_packages setup(name='citrination-client', version='4.6.0', url='http://github.com/CitrineInformatics/python-citrination-client', description='Python client for accessing the Citrination api', packages=find_packages(exclude=('docs')), install_requires=[ 'requests<3', 'pypif', 'six<2', 'pyyaml' ], extras_require={ "dev": [ 'sphinx_rtd_theme', 'sphinx', ], "test": [ 'requests_mock', 'pytest', ] })
Fix expression: brace is missed
package com.intellij.debugger.streams.trace.smart.handler; import org.jetbrains.annotations.NotNull; /** * @author Vitaliy.Bibaev */ public class HashMapVariableImpl extends VariableImpl { private final String myFromType; public HashMapVariableImpl(@NotNull String name, @NotNull String from, @NotNull String to, boolean isLinked) { super(String.format("Map<%s, %s>", from, to), name, isLinked ? "new LinkedHashMap<>()" : "new HashMap<>()"); myFromType = from; } public String convertToArray(@NotNull String arrayName) { final StringBuilder builder = new StringBuilder(); final String newLine = System.lineSeparator(); builder.append("final ").append(arrayName).append(String.format(" = new Object[%s.size()];", getName())).append(System.lineSeparator()); builder.append("{").append(newLine); builder.append("int i = 0;").append(newLine); builder.append("for (final ").append(myFromType).append(String.format(" key : %s.keySet()) {", getName())).append(newLine); builder.append("final Object value = ").append(String.format("%s.get(key);", getName())).append(newLine); builder.append(String.format("%s[i] = ", arrayName)).append("new Object[] { key, value };").append(newLine); builder.append(" }").append(newLine); builder.append("}").append(newLine); return builder.toString(); } }
package com.intellij.debugger.streams.trace.smart.handler; import org.jetbrains.annotations.NotNull; /** * @author Vitaliy.Bibaev */ public class HashMapVariableImpl extends VariableImpl { private final String myFromType; public HashMapVariableImpl(@NotNull String name, @NotNull String from, @NotNull String to, boolean isLinked) { super(String.format("Map<%s, %s>", from, to), name, isLinked ? "new LinkedHashMap<>()" : "new HashMap<>()"); myFromType = from; } public String convertToArray(@NotNull String arrayName) { final StringBuilder builder = new StringBuilder(); final String newLine = System.lineSeparator(); builder.append("final ").append(arrayName).append(String.format("new Object[%s.size()];", getName())).append(System.lineSeparator()); builder.append("{").append(newLine); builder.append("int i = 0;").append(newLine); builder.append("for (final ").append(myFromType).append(String.format(" key : %s.keySet()) {", getName())).append(newLine); builder.append("final Object value = ").append(String.format("%s.get(key);", getName())).append(newLine); builder.append(String.format("%s[i] = ", arrayName)).append("new Object[] { key, value };").append(newLine); builder.append("}").append(newLine); return builder.toString(); } }
Remove last usage of jQuery
(function() { // fix for printing bug in Windows Safari var windowsSafari = (window.navigator.userAgent.match(/(\(Windows[\s\w\.]+\))[\/\(\s\w\.\,\)]+(Version\/[\d\.]+)\s(Safari\/[\d\.]+)/) !== null), style; if (windowsSafari) { // set the New Transport font to Arial for printing style = document.createElement('style'); style.setAttribute('type', 'text/css'); style.setAttribute('media', 'print'); style.innerHTML = '@font-face { font-family: nta !important; src: local("Arial") !important; }'; document.getElementsByTagName('head')[0].appendChild(style); } if (window.GOVUK && GOVUK.addCookieMessage) { GOVUK.addCookieMessage(); } }).call(this);
$(document).ready(function() { // fix for printing bug in Windows Safari var windowsSafari = (window.navigator.userAgent.match(/(\(Windows[\s\w\.]+\))[\/\(\s\w\.\,\)]+(Version\/[\d\.]+)\s(Safari\/[\d\.]+)/) !== null), style; if (windowsSafari) { // set the New Transport font to Arial for printing style = document.createElement('style'); style.setAttribute('type', 'text/css'); style.setAttribute('media', 'print'); style.innerHTML = '@font-face { font-family: nta !important; src: local("Arial") !important; }'; document.getElementsByTagName('head')[0].appendChild(style); } if (window.GOVUK && GOVUK.addCookieMessage) { GOVUK.addCookieMessage(); } });
Set loading: true on app start
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import moment from './moment'; import App from './components/App'; import rootReducer from './reducers'; import { fetchBookings } from './actions'; import './index.css'; const today = moment().startOf("day"); // today at 00:00 const initialState = { active: false, loading: true, error: null, date: today, diaryDate: today, // holds the date of the current roomDiaries hours: 0, between: [ "08:00", "14:00" ], capacity: [], roomDiaries: {} }; const store = createStore( rootReducer, initialState, applyMiddleware(thunk) ); ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') ); store.dispatch(fetchBookings(today));
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import moment from './moment'; import App from './components/App'; import rootReducer from './reducers'; import { fetchBookings } from './actions'; import './index.css'; const today = moment().startOf("day"); // today at 00:00 const initialState = { active: false, loading: false, error: null, date: today, diaryDate: today, // holds the date of the current roomDiaries hours: 0, between: [ "08:00", "14:00" ], capacity: [], roomDiaries: {} }; const store = createStore( rootReducer, initialState, applyMiddleware(thunk) ); ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') ); store.dispatch(fetchBookings(today));
Debug the whole execution 🎯
import { execFile } from 'child_process' import flow from 'flow-bin' import { logError, log } from '../util/log' const errorCodes = { TYPECHECK_ERROR: 2 } export default (saguiOptions) => new Promise((resolve, reject) => { const commandArgs = ['check', '--color=always'] if (saguiOptions.javaScript && saguiOptions.javaScript.typeCheckAll) { commandArgs.push('--all') } try { execFile(flow, commandArgs, { cwd: saguiOptions.projectPath }, (err, stdout, stderr) => { console.log('SOMETHING FAILED 👾') console.error(err) console.error(stderr) console.log('END OF FAILURE 👾') if (err) { logError('Type check failed:\n') switch (err.code) { case errorCodes.TYPECHECK_ERROR: console.log(stdout) break default: console.log(err) } reject() } else { log('Type check completed without errors') resolve() } }) } catch (e) { console.log('THE EXECUTION FAILED 🎯') console.log('MESSAGE', e.message) console.log('TRACE', e.trace) console.log('END 🎯') } })
import { execFile } from 'child_process' import flow from 'flow-bin' import { logError, log } from '../util/log' const errorCodes = { TYPECHECK_ERROR: 2 } export default (saguiOptions) => new Promise((resolve, reject) => { const commandArgs = ['check', '--color=always'] if (saguiOptions.javaScript && saguiOptions.javaScript.typeCheckAll) { commandArgs.push('--all') } execFile(flow, commandArgs, { cwd: saguiOptions.projectPath }, (err, stdout, stderr) => { console.log('SOMETHING FAILED 👾') console.error(err) console.error(stderr) console.log('END OF FAILURE 👾') if (err) { logError('Type check failed:\n') switch (err.code) { case errorCodes.TYPECHECK_ERROR: console.log(stdout) break default: console.log(err) } reject() } else { log('Type check completed without errors') resolve() } }) })
Update requests requirement from <2.21,>=2.4.2 to >=2.4.2,<2.22 Updates the requirements on [requests](https://github.com/requests/requests) to permit the latest version. - [Release notes](https://github.com/requests/requests/releases) - [Changelog](https://github.com/requests/requests/blob/master/HISTORY.md) - [Commits](https://github.com/requests/requests/commits/v2.21.0) Signed-off-by: dependabot[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@dependabot.com>
from setuptools import setup, find_packages setup( name='panoptes_client', url='https://github.com/zooniverse/panoptes-python-client', author='Adam McMaster', author_email='adam@zooniverse.org', version='1.0.3', packages=find_packages(), include_package_data=True, install_requires=[ 'requests>=2.4.2,<2.22', 'future>=0.16,<0.18', 'python-magic>=0.4,<0.5', 'redo>=1.7', ], extras_require={ 'testing': [ 'mock>=2.0,<2.1', ], 'docs': [ 'sphinx', ], ':python_version == "2.7"': ['futures'], } )
from setuptools import setup, find_packages setup( name='panoptes_client', url='https://github.com/zooniverse/panoptes-python-client', author='Adam McMaster', author_email='adam@zooniverse.org', version='1.0.3', packages=find_packages(), include_package_data=True, install_requires=[ 'requests>=2.4.2,<2.21', 'future>=0.16,<0.18', 'python-magic>=0.4,<0.5', 'redo>=1.7', ], extras_require={ 'testing': [ 'mock>=2.0,<2.1', ], 'docs': [ 'sphinx', ], ':python_version == "2.7"': ['futures'], } )
Remove window reference from UMD module
const webpack = require('webpack'); const path = require('path'); module.exports = { context: path.resolve(__dirname, '..'), entry: { 'easy-bits.min': './src/index.js' }, target: 'web', output: { path: path.resolve(__dirname, '../dist/'), publicPath: '/', filename: '[name].js', libraryTarget: 'umd', globalObject: 'this' }, resolve: { extensions: ['.js'] }, module: { rules: [{ test: /\.(js)$/, exclude: /node_modules/, use: [{ loader: 'babel-loader', options: { presets: [['@babel/preset-env', { useBuiltIns: 'usage', corejs: 3, targets: { node: '8', chrome: '26', firefox: '4', edge: '13', ie: '10', safari: '7' } }]], plugins: [ '@babel/plugin-proposal-class-properties' ] } }] }] }, plugins: [ new webpack.NoEmitOnErrorsPlugin() ], performance: { hints: false } };
const webpack = require('webpack'); const path = require('path'); module.exports = { context: path.resolve(__dirname, '..'), entry: { 'easy-bits.min': './src/index.js' }, target: 'web', output: { path: path.resolve(__dirname, '../dist/'), publicPath: '/', filename: '[name].js', libraryTarget: 'umd' }, resolve: { extensions: ['.js'] }, module: { rules: [{ test: /\.(js)$/, exclude: /node_modules/, use: [{ loader: 'babel-loader', options: { presets: [['@babel/preset-env', { useBuiltIns: 'usage', corejs: 3, targets: { node: '8', chrome: '26', firefox: '4', edge: '13', ie: '10', safari: '7' } }]], plugins: [ '@babel/plugin-proposal-class-properties' ] } }] }] }, plugins: [ new webpack.NoEmitOnErrorsPlugin() ], performance: { hints: false } };
Add OCA as author of OCA addons In order to get visibility on https://www.odoo.com/apps the OCA board has decided to add the OCA as author of all the addons maintained as part of the association.
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013 ABF OSIELL (<http://osiell.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': "Audit Log", 'version': "1.0", 'author': "ABF OSIELL,Odoo Community Association (OCA)", 'website': "http://www.osiell.com", 'category': "Tools", 'depends': [ 'base', ], 'data': [ 'security/ir.model.access.csv', 'views/auditlog_view.xml', ], 'application': True, 'installable': True, 'pre_init_hook': 'pre_init_hook', }
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013 ABF OSIELL (<http://osiell.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': "Audit Log", 'version': "1.0", 'author': "ABF OSIELL", 'website': "http://www.osiell.com", 'category': "Tools", 'depends': [ 'base', ], 'data': [ 'security/ir.model.access.csv', 'views/auditlog_view.xml', ], 'application': True, 'installable': True, 'pre_init_hook': 'pre_init_hook', }
Drop unnecessary wrapper element in time-machine-links
import select from 'select-dom'; import {h} from 'dom-chef'; import * as icons from '../libs/icons'; import {getRepoURL} from '../libs/page-detect'; export default async () => { const comments = select.all('.timeline-comment-header:not(.rgh-timestamp-tree-link)'); for (const comment of comments) { const timestampEl = select('relative-time', comment); const timestamp = timestampEl.attributes.datetime.value; const href = `/${getRepoURL()}/tree/HEAD@{${timestamp}}`; timestampEl.parentNode.after( ' ', <a href={href} class="timeline-comment-action btn-link rgh-timestamp-button tooltipped tooltipped-n rgh-tooltipped" aria-label="View repo at the time of this comment" > {icons.code()} </a> ); comment.classList.add('rgh-timestamp-tree-link'); } };
import select from 'select-dom'; import {h} from 'dom-chef'; import * as icons from '../libs/icons'; import {getRepoURL} from '../libs/page-detect'; export default async () => { const comments = select.all('.timeline-comment-header:not(.rgh-timestamp-tree-link)'); for (const comment of comments) { const timestampEl = select('relative-time', comment); const timestamp = timestampEl.attributes.datetime.value; const href = `/${getRepoURL()}/tree/HEAD@{${timestamp}}`; timestampEl.parentNode.after( <span> &nbsp; <a href={href} class="timeline-comment-action btn-link rgh-timestamp-button tooltipped tooltipped-n rgh-tooltipped" aria-label="View repo at the time of this comment" > {icons.code()} </a> </span> ); comment.classList.add('rgh-timestamp-tree-link'); } };
Fix outdated refernce to connected components
<?php namespace Fhaculty\Graph\Algorithm; use Fhaculty\Graph\Algorithm\BaseGraph; use Fhaculty\Graph\Graph; use Fhaculty\Graph\Algorithm\Degree; class Eulerian extends BaseGraph { /** * check whether this graph has an eulerian cycle * * @return boolean * @uses ConnectedComponents::isSingle() * @uses Degree::getDegreeVertex() * @todo isolated vertices should be ignored * @todo definition is only valid for undirected graphs */ public function hasCycle() { $components = new ConnectedComponents($this->graph); if ($components->isSingle()) { $alg = new Degree($this->graph); foreach ($this->graph->getVertices() as $vertex) { // uneven degree => fail if ($alg->getDegreeVertex($vertex) & 1) { return false; } } return true; } return false; } }
<?php namespace Fhaculty\Graph\Algorithm; use Fhaculty\Graph\Algorithm\BaseGraph; use Fhaculty\Graph\Graph; use Fhaculty\Graph\Algorithm\Degree; class Eulerian extends BaseGraph { /** * check whether this graph has an eulerian cycle * * @return boolean * @uses Graph::isConnected() * @uses Degree::getDegreeVertex() * @todo isolated vertices should be ignored * @todo definition is only valid for undirected graphs */ public function hasCycle() { if ($this->graph->isConnected()) { $alg = new Degree($this->graph); foreach ($this->graph->getVertices() as $vertex) { // uneven degree => fail if ($alg->getDegreeVertex($vertex) & 1) { return false; } } return true; } return false; } }
Add `-logs` suffix to default log archive file name
/* * Copyright 2022 Google LLC * Copyright 2013-2021 CompilerWorks * * 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.google.edwmigration.dumper.application.dumper.connector; /** * * @author shevek */ public interface LogsConnector extends Connector { @Override default public String getDefaultFileName() { return "dwh-migration-" + getName() + "-logs.zip"; } }
/* * Copyright 2022 Google LLC * Copyright 2013-2021 CompilerWorks * * 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.google.edwmigration.dumper.application.dumper.connector; /** * * @author shevek */ public interface LogsConnector extends Connector { @Override default public String getDefaultFileName() { return "dwh-migration-" + getName() + ".zip"; } }
Convert pointcut to interface that will be implemented later
<?php /** * Go! OOP&AOP PHP framework * * @copyright Copyright 2011, Lissachenko Alexander <lisachenko.it@gmail.com> * @license http://www.opensource.org/licenses/mit-license.php The MIT License */ namespace Go\Aop; /** * Pointcut realization for PHP * * Pointcuts are defined as a predicate over the syntax-tree of the program, and define an interface that constrains * which elements of the base program are exposed by the pointcut. A pointcut picks out certain join points and values * at those points * * @package go * @subpackage aop */ interface Pointcut { /** * Return the ClassFilter for this pointcut. * * @return ClassFilter */ public function getClassFilter(); /** * Return the PointFilter for this pointcut. * * This can be method filter, property filter. * * @return PointFilter */ public function getPointFilter(); }
<?php /** * Go! OOP&AOP PHP framework * * @copyright Copyright 2011, Lissachenko Alexander <lisachenko.it@gmail.com> * @license http://www.opensource.org/licenses/mit-license.php The MIT License */ namespace Go\Aop; /** * Pointcut realization for PHP * * Pointcuts are defined as a predicate over the syntax-tree of the program, and define an interface that constrains * which elements of the base program are exposed by the pointcut. A pointcut picks out certain join points and values * at those points * * @package go * @subpackage aop */ class Pointcut { protected $processor = null; public function __construct($processor) { if (!is_callable($processor)) { throw new \InvalidArgumentException('Processor should be callable'); } $this->processor = $processor; } /** * @param string $className Name of class to check for * @param \Go\AopAlliance\Intercept\Joinpoint[] $joinPoints * @param Aspect $aspect * @return void */ function __invoke($className, array $joinPoints, Aspect $aspect) { $processor = $this->processor; $processor($className, $joinPoints, $aspect); } }
Move Conf to a global for consistency with build executable Former-commit-id: b47323e5980edce87d5ba5eb277d6ae6d914f711
package main import ( "net/http" "path" "strconv" log "github.com/Sirupsen/logrus" "github.com/brandur/sorg" "github.com/joeshaw/envdecode" ) // Conf contains configuration information for the command. type Conf struct { // Port is the port on which the command will serve the site over HTTP. Port int `env:"PORT,default=5001"` // TargetDir is the target location where the site was built to. TargetDir string `env:"TARGET_DIR,default=./public"` } // Left as a global for now for the sake of convenience, but it's not used in // very many places and can probably be refactored as a local if desired. var conf Conf func main() { sorg.InitLog(false) err := envdecode.Decode(&conf) if err != nil { log.Fatal(err) } err = sorg.CreateOutputDirs(conf.TargetDir) if err != nil { log.Fatal(err) } err = serve(conf.TargetDir, conf.Port) if err != nil { log.Fatal(err) } } func serve(targetDir string, port int) error { log.Infof("Serving '%v' on port %v", path.Clean(targetDir), port) log.Infof("Open browser to: http://localhost:%v/", port) handler := http.FileServer(http.Dir(targetDir)) return http.ListenAndServe(":"+strconv.Itoa(port), handler) }
package main import ( "net/http" "path" "strconv" log "github.com/Sirupsen/logrus" "github.com/brandur/sorg" "github.com/joeshaw/envdecode" ) // Conf contains configuration information for the command. type Conf struct { // Port is the port on which the command will serve the site over HTTP. Port int `env:"PORT,default=5001"` // TargetDir is the target location where the site was built to. TargetDir string `env:"TARGET_DIR,default=./public"` } func main() { sorg.InitLog(false) var conf Conf err := envdecode.Decode(&conf) if err != nil { log.Fatal(err) } err = sorg.CreateOutputDirs(conf.TargetDir) if err != nil { log.Fatal(err) } err = serve(conf.TargetDir, conf.Port) if err != nil { log.Fatal(err) } } func serve(targetDir string, port int) error { log.Infof("Serving '%v' on port %v", path.Clean(targetDir), port) log.Infof("Open browser to: http://localhost:%v/", port) handler := http.FileServer(http.Dir(targetDir)) return http.ListenAndServe(":"+strconv.Itoa(port), handler) }
Remove @Override from deprecated method
package openmods; import java.util.Map; import java.util.logging.Logger; import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.relauncher.IFMLLoadingPlugin; import cpw.mods.fml.relauncher.IFMLLoadingPlugin.SortingIndex; import cpw.mods.fml.relauncher.IFMLLoadingPlugin.TransformerExclusions; //must be lower than all dependent ones @SortingIndex(16) @TransformerExclusions({ "openmods.asm", "openmods.include" }) public class OpenModsCorePlugin implements IFMLLoadingPlugin { public static Logger log; static { log = Logger.getLogger("OpenModsCore"); log.setParent(FMLLog.getLogger()); } @Override public String[] getASMTransformerClass() { return new String[] { "openmods.OpenModsClassTransformer" }; } @Override public String getModContainerClass() { return "openmods.OpenModsCore"; } @Override public String getSetupClass() { return null; } @Override public void injectData(Map<String, Object> data) {} @Deprecated public String[] getLibraryRequestClass() { return null; } }
package openmods; import java.util.Map; import java.util.logging.Logger; import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.relauncher.IFMLLoadingPlugin; import cpw.mods.fml.relauncher.IFMLLoadingPlugin.SortingIndex; import cpw.mods.fml.relauncher.IFMLLoadingPlugin.TransformerExclusions; //must be lower than all dependent ones @SortingIndex(16) @TransformerExclusions({ "openmods.asm", "openmods.include" }) public class OpenModsCorePlugin implements IFMLLoadingPlugin { public static Logger log; static { log = Logger.getLogger("OpenModsCore"); log.setParent(FMLLog.getLogger()); } @Override public String[] getASMTransformerClass() { return new String[] { "openmods.OpenModsClassTransformer" }; } @Override public String getModContainerClass() { return "openmods.OpenModsCore"; } @Override public String getSetupClass() { return null; } @Override public void injectData(Map<String, Object> data) {} @Override @Deprecated public String[] getLibraryRequestClass() { return null; } }
Use pympler to look for memory leaks
import guv guv.monkey_patch() import guv.server import logging import time from util import create_example import logger from pympler import tracker tr = tracker.SummaryTracker() if not hasattr(time, 'perf_counter'): time.perf_counter = time.clock logger.configure() log = logging.getLogger() response_times = [] def get_avg_time(): global response_times times = response_times[-1000:] avg = sum(times) / len(times) if len(response_times) > 5000: response_times = times return avg def handle(sock, addr): # client connected start_time = time.perf_counter() sock.sendall(create_example()) sock.close() total_time = time.perf_counter() - start_time response_times.append(total_time) if __name__ == '__main__': pool = guv.GreenPool() try: log.debug('Start') server_sock = guv.listen(('0.0.0.0', 8001)) server = guv.server.Server(server_sock, handle, pool, 'spawn_n') server.start() except (SystemExit, KeyboardInterrupt): tr.print_diff() log.debug('Bye!')
# FIXME: pyuv_cffi needs to build the library BEFORE the standard library is patched import pyuv_cffi print('pyuv_cffi imported', pyuv_cffi) import guv guv.monkey_patch() import guv.server import logging import time from util import create_example import logger if not hasattr(time, 'perf_counter'): time.perf_counter = time.clock logger.configure() log = logging.getLogger() response_times = [] def get_avg_time(): global response_times times = response_times[-1000:] avg = sum(times) / len(times) if len(response_times) > 5000: response_times = times return avg def handle(sock, addr): # client connected start_time = time.perf_counter() sock.sendall(create_example()) sock.close() total_time = time.perf_counter() - start_time response_times.append(total_time) if __name__ == '__main__': pool = guv.GreenPool() try: log.debug('Start') server_sock = guv.listen(('0.0.0.0', 8001)) server = guv.server.Server(server_sock, handle, pool, 'spawn_n') server.start() except (SystemExit, KeyboardInterrupt): log.debug('average response time: {}'.format(get_avg_time())) log.debug('Bye!')
Use id instead of name when saving reply for klaxon
var r = require('rethinkdb'); var klaxonPostBody = require('./klaxonPostBody.js'); var reqlRedditDate = require('../reqlRedditDate.js'); module.exports = function postKlaxonReply( subject, reply, forfeits, reddit, conn) { return reddit('/api/comment').post({ thing_id: reply.name, // not `parent`, no matter what the docs say text: klaxonPostBody(forfeits[0], // use self-forfeit template if elf who proposed the forfeit // is the poster who triggered it forfeits[0].elf == reply.author) }).then(function(comment){ return r.table('klaxons').insert({ id: comment.id, subject: subject.name, reply: reply.id, forfeits: forfeits.map(function(forfeit){return forfeit.id}), created: reqlRedditDate(comment,'created')}).run(conn); }); };
var r = require('rethinkdb'); var klaxonPostBody = require('./klaxonPostBody.js'); var reqlRedditDate = require('../reqlRedditDate.js'); module.exports = function postKlaxonReply( subject, reply, forfeits, reddit, conn) { return reddit('/api/comment').post({ thing_id: reply.name, // not `parent`, no matter what the docs say text: klaxonPostBody(forfeits[0], // use self-forfeit template if elf who proposed the forfeit // is the poster who triggered it forfeits[0].elf == reply.author) }).then(function(comment){ return r.table('klaxons').insert({ id: comment.id, subject: subject.name, reply: reply.name, forfeits: forfeits.map(function(forfeit){return forfeit.id}), created: reqlRedditDate(comment,'created')}).run(conn); }); };
Move populate/get into its own method Signed-off-by: Ian Macalinao <b1c1d8736f20db3fb6c1c66bb1455ed43909f0d8@ian.pw>
var async = require("async"); var bay6 = require("../lib/"); var expect = require("chai").expect; var mongoose = require("mongoose"); var request = require("supertest"); describe("Model", function() { var app; var server; var model; beforeEach(function() { app = bay6(); app.options.prefix = ""; model = app.model("Document", { title: String, contents: String }); }); describe("#limit", function() { it("should return a maximum of n documents", function(done) { model.limit(5); server = app.serve(9000); populateAndGet(function(err, res) { expect(res.body.length).to.equal(5); done(); }); }); }); afterEach(function(done) { app.mongoose.db.dropDatabase(done); server.close(); }); function populateAndGet(cb) { var Document = app.mongoose.model("Document"); async.each([1, 2, 3, 4, 5, 6], function(useless, done2) { var doc = new Document({ title: "war and peace", contents: "yolo" }); doc.save(done2); }, function(err) { if (err) { throw err; } request(server).get("/documents").end(cb); }); } });
var async = require("async"); var bay6 = require("../lib/"); var expect = require("chai").expect; var mongoose = require("mongoose"); var request = require("supertest"); describe("Model", function() { var app; var model; beforeEach(function() { app = bay6(); app.options.prefix = ""; model = app.model("Document", { title: String, contents: String }); }); describe("#limit", function() { it("should return a maximum of n documents", function(done) { model.limit(5); var server = app.serve(9000); var Document = app.mongoose.model("Document"); async.each([1, 2, 3, 4, 5, 6], function(useless, done2) { var doc = new Document({ title: "war and peace", contents: "yolo" }); doc.save(done2); }, function(err) { if (err) { throw err; } request(server).get("/documents").end(function(err, res) { expect(res.body.length).to.equal(5); server.close(); done(); }); }); }); }); afterEach(function(done) { app.mongoose.db.dropDatabase(done); }); });
PRJ: Increase version 3.0.0 -> 3.1.1
#!/usr/bin/env python from setuptools import setup, find_packages # This setup relies on setuptools since distutils is insufficient and badly hacked code version = '3.1.1' author = 'David-Leon Pohl, Jens Janssen' author_email = 'pohl@physik.uni-bonn.de, janssen@physik.uni-bonn.de' # requirements for core functionality from requirements.txt with open('requirements.txt') as f: install_requires = f.read().splitlines() setup( name='pixel_clusterizer', version=version, description='A fast, generic, and easy to use clusterizer to cluster hits of a pixel matrix in Python. The clustering happens with numba on numpy arrays to increase the speed.', url='https://github.com/SiLab-Bonn/pixel_clusterizer', license='GNU LESSER GENERAL PUBLIC LICENSE Version 2.1', long_description='', author=author, maintainer=author, author_email=author_email, maintainer_email=author_email, install_requires=install_requires, packages=find_packages(), include_package_data=True, # accept all data files and directories matched by MANIFEST.in or found in source control package_data={'': ['README.*', 'VERSION'], 'docs': ['*'], 'examples': ['*']}, keywords=['cluster', 'clusterizer', 'pixel'], platforms='any' )
#!/usr/bin/env python from setuptools import setup, find_packages # This setup relies on setuptools since distutils is insufficient and badly hacked code version = '3.0.0' author = 'David-Leon Pohl, Jens Janssen' author_email = 'pohl@physik.uni-bonn.de, janssen@physik.uni-bonn.de' # requirements for core functionality from requirements.txt with open('requirements.txt') as f: install_requires = f.read().splitlines() setup( name='pixel_clusterizer', version=version, description='A fast, generic, and easy to use clusterizer to cluster hits of a pixel matrix in Python. The clustering happens with numba on numpy arrays to increase the speed.', url='https://github.com/SiLab-Bonn/pixel_clusterizer', license='GNU LESSER GENERAL PUBLIC LICENSE Version 2.1', long_description='', author=author, maintainer=author, author_email=author_email, maintainer_email=author_email, install_requires=install_requires, packages=find_packages(), include_package_data=True, # accept all data files and directories matched by MANIFEST.in or found in source control package_data={'': ['README.*', 'VERSION'], 'docs': ['*'], 'examples': ['*']}, keywords=['cluster', 'clusterizer', 'pixel'], platforms='any' )
Set up all the URLs
import 'babel-polyfill' import express from 'express' import fallback from 'express-history-api-fallback' import path from 'path' import log from './log' import proxy from 'http-proxy-middleware' // Properly catch async exceptions, log them, and re-throw them // on the main process to crash the program const wrap = (fn) => (...args) => fn(...args) .catch((ex) => { log.error(ex) process.nextTick(() => { throw ex }) }) const app = express() const port = process.env.PORT const publicPath = path.resolve(__dirname, '../../build/frontend') app.enable('trust proxy') app.listen(port, () => { log.info(`Node app is running on port ${port}`) }) app.get('/', wrap((req, res) => { res.redirect('/home') })) app.use(express.static(publicPath, { maxAge: '180 days' })) app.use([ '/home', '/teams', '/about'], proxy({ target: 'http://brandnewcongress.nationbuilder.com/', changeOrigin: true })) app.use([ '/abteam', '/adteam', '/call', '/conferencecallteam', '/dataentryteam', '/faq', '/officeteam', '/researchteam', '/shareteam', '/spreadsheetteam', '/textingteam', '/travelteam'], proxy({ target: 'http://brandnewcongress.github.io/', changeOrigin: true })) app.use(fallback('index.html', { root: publicPath, maxAge: 0 }))
import 'babel-polyfill' import express from 'express' import fallback from 'express-history-api-fallback' import path from 'path' import log from './log' import proxy from 'http-proxy-middleware' // Properly catch async exceptions, log them, and re-throw them // on the main process to crash the program const wrap = (fn) => (...args) => fn(...args) .catch((ex) => { log.error(ex) process.nextTick(() => { throw ex }) }) const app = express() const port = process.env.PORT const publicPath = path.resolve(__dirname, '../../build/frontend') app.enable('trust proxy') app.listen(port, () => { log.info(`Node app is running on port ${port}`) }) app.get('/', wrap((req, res) => { res.redirect('/home') })) app.use(express.static(publicPath, { maxAge: '180 days' })) app.use(['/home', '/teams', '/faq'], proxy({ target: 'http://brandnewcongress.nationbuilder.com/', changeOrigin: true })) app.use(fallback('index.html', { root: publicPath, maxAge: 0 }))
Stop vibrations in default vibration example
package io.myweb.examples; import android.content.Context; import android.os.Vibrator; import org.json.JSONArray; import org.json.JSONException; import io.myweb.api.GET; import io.myweb.http.Response; public class VibratorExample { @GET("/vibrator/*toggle?:pattern=[500,1000,500,1000,500,1000]&:repeat=-1") public Response vibrator(Context context, String toggle, JSONArray pattern, int repeat) throws JSONException { Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); if (!v.hasVibrator()) return Response.serviceUnavailable(); if (toggle.equals("on")) { v.vibrate(jsonArrayToLongArray(pattern), repeat); } else if (toggle.equals("off")) { v.cancel(); } else return Response.notFound(); return Response.ok(); } private long[] jsonArrayToLongArray(JSONArray ja) throws JSONException { long[] la = new long[ja.length()]; for (int i=0; i<la.length; i++) { la[i] = ja.getLong(i); } return la; } }
package io.myweb.examples; import android.content.Context; import android.os.Vibrator; import org.json.JSONArray; import org.json.JSONException; import io.myweb.api.GET; import io.myweb.http.Response; public class VibratorExample { @GET("/vibrator/*toggle?:pattern=[500,1000]&:repeat=0") public Response vibrator(Context context, String toggle, JSONArray pattern, int repeat) throws JSONException { Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); if (!v.hasVibrator()) return Response.serviceUnavailable(); if (toggle.equals("on")) { v.vibrate(jsonArrayToLongArray(pattern), repeat); } else if (toggle.equals("off")) { v.cancel(); } else return Response.notFound(); return Response.ok(); } private long[] jsonArrayToLongArray(JSONArray ja) throws JSONException { long[] la = new long[ja.length()]; for (int i=0; i<la.length; i++) { la[i] = ja.getLong(i); } return la; } }
Make imports compliant to PEP 8 suggestion
import turtle as t GROESSE = 0.5 FARBE = "red" FAERBEN = True SHAPE = "turtle" t.fillcolor(FARBE) t.shape(SHAPE) def zeichneKerze(brennt): t.pd() t.begin_fill() t.forward(GROESSE*100) t.left(90) t.forward(GROESSE*400) t.left(90) t.forward(GROESSE*100) t.right(90) t.forward(GROESSE*30) t.back(GROESSE*30) t.left(90) t.forward(GROESSE*100) t.left(90) t.forward(GROESSE*400) t.left(90) t.forward(GROESSE*100) t.end_fill() t.pu() if brennt: zeichneFlamme() def zeichneFlamme(): t.left(90) t.fd(GROESSE*430) t.pd() t.color("yellow") t.dot(GROESSE*60) t.color("black") t.back(GROESSE*30) t.pu() t.home() if __name__=="__main__": zeichneKerze(True) t.hideturtle()
from turtle import * GROESSE = 0.5 FARBE = "red" FAERBEN = True SHAPE = "turtle" fillcolor(FARBE) shape(SHAPE) def zeichneKerze(brennt): pd() begin_fill() forward(GROESSE*100) left(90) forward(GROESSE*400) left(90) forward(GROESSE*100) right(90) forward(GROESSE*30) back(GROESSE*30) left(90) forward(GROESSE*100) left(90) forward(GROESSE*400) left(90) forward(GROESSE*100) end_fill() pu() if brennt: zeichneFlamme() def zeichneFlamme(): left(90) fd(GROESSE*430) pd() color("yellow") dot(GROESSE*60) color("black") back(GROESSE*30) pu() home() if __name__=="__main__": zeichneKerze(True) hideturtle()
Move static to the front
require('./env'); var mount = require('koa-mount'); var koa = require('koa'); var app = koa(); app.use(require('koa-logger')()); app.use(require('koa-bodyparser')()); app.use(function *(next) { if (typeof this.request.body === 'undefined' || this.request.body === null) { this.request.body = {}; } yield next; }); app.use(require('koa-mount')('/api', require('./api'))); app.use(mount('/build', require('koa-static')('build'))); app.use(function *(next) { this.api = API; var token = this.cookies.get('session-token'); if (token) { this.api.$header('x-session-token', token); } yield next; }); app.use(function *(next) { try { yield next; } catch (err) { if (err.body) { this.body = err.body; this.status = err.statusCode; } else { this.body = { err: 'server error' }; this.status = 500; console.error(err.stack || err); } } }); app.use(require('koa-views')('views/pages', { default: 'jade' })); require('koa-mount-directory')(app, require('path').join(__dirname, 'routes')); if (require.main === module) { app.listen($config.port); } else { module.exports = app; }
require('./env'); var mount = require('koa-mount'); var koa = require('koa'); var app = koa(); app.use(require('koa-logger')()); app.use(require('koa-bodyparser')()); app.use(function *(next) { if (typeof this.request.body === 'undefined' || this.request.body === null) { this.request.body = {}; } yield next; }); app.use(mount('/build', require('koa-static')('build', { defer: true }))); app.use(function *(next) { this.api = API; var token = this.cookies.get('session-token'); if (token) { this.api.$header('x-session-token', token); } yield next; }); app.use(function *(next) { try { yield next; } catch (err) { if (err.body) { this.body = err.body; this.status = err.statusCode; } else { this.body = { err: 'server error' }; this.status = 500; console.error(err.stack || err); } } }); app.use(require('koa-views')('views/pages', { default: 'jade' })); require('koa-mount-directory')(app, require('path').join(__dirname, 'routes')); if (require.main === module) { app.listen($config.port); } else { module.exports = app; }
Use own seeded random generator for string generation
package k import ( "encoding/json" "math/rand" "time" ) // StringArray is an alias for an array of strings // which has common operations defined as methods. type StringArray []string // Contains returns true if the receiver array contains // an element equivalent to needle. func (s StringArray) Contains(needle string) bool { for _, elem := range s { if elem == needle { return true } } return false } // String returns the JSON representation of the array. func (s StringArray) String() string { a, _ := json.Marshal(s) return string(a) } var ( alphaNum = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890" r = rand.New(rand.NewSource(time.Now().UnixNano())) ) // RandomString generates a random alpha-numeric string // of length n func RandomString(n int) string { s := make([]byte, 0, n) for i := 0; i < n; i++ { s = append(s, alphaNum[r.Int63n(int64(len(alphaNum)))]) } return string(s) }
package k import ( "encoding/json" "math/rand" ) // StringArray is an alias for an array of strings // which has common operations defined as methods. type StringArray []string // Contains returns true if the receiver array contains // an element equivalent to needle. func (s StringArray) Contains(needle string) bool { for _, elem := range s { if elem == needle { return true } } return false } // String returns the JSON representation of the array. func (s StringArray) String() string { a, _ := json.Marshal(s) return string(a) } var ( alphaNum = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890" ) // RandomString generates a random alpha-numeric string // of length n func RandomString(n int) string { s := make([]byte, 0, n) for i := 0; i < n; i++ { s = append(s, alphaNum[rand.Int63n(int64(len(alphaNum)))]) } return string(s) }
Check github response before parsing
import json, requests from wagtail.wagtailadmin.edit_handlers import FieldPanel from wagtail.wagtailcore.models import Page, Orderable import django.utils.dateparse as dateparse from django.db import models from django.core.cache import cache class GithubOrgIndexPage(Page): github_org_name = models.CharField(default='City-of-Helsinki', max_length=200) content_panels = Page.content_panels + [ FieldPanel('github_org_name'), ] def events(self): events = cache.get('github') if not events: response = requests.get('https://api.github.com/orgs/' + self.github_org_name + '/events?per_page=20') if response.status_code == 200: cache.add('github', response.json(), 60) events = cache.get('github') for index, event in enumerate(events): event['created_at'] = dateparse.parse_datetime(event['created_at']) # get html repo url event['repo']['url'] = event['repo']['url'].replace('https://api.github.com/repos/', 'https://github.com/') return events def top_events(self): return self.events()[:3]
import json, requests from wagtail.wagtailadmin.edit_handlers import FieldPanel from wagtail.wagtailcore.models import Page, Orderable import django.utils.dateparse as dateparse from django.db import models from django.core.cache import cache class GithubOrgIndexPage(Page): github_org_name = models.CharField(default='City-of-Helsinki', max_length=200) content_panels = Page.content_panels + [ FieldPanel('github_org_name'), ] def events(self): events = cache.get('github') if not events: cache.add('github', requests.get('https://api.github.com/orgs/' + self.github_org_name + '/events?per_page=20').json(), 60) events = cache.get('github') for index, event in enumerate(events): event['created_at'] = dateparse.parse_datetime(event['created_at']) # get html repo url event['repo']['url'] = event['repo']['url'].replace('https://api.github.com/repos/', 'https://github.com/') return events def top_events(self): return self.events()[:3]
Rename test classes to avoid conflicts
<?php class TestModule1 extends PageModule { } class PageModuleTest extends SapphireTest { protected static $fixture_file = 'PageModuleTest.yml'; /** * Test that we're able to create a page module. */ public function testPageModuleCreation() { $hero = $this->objFromFixture('PageModule', 'hero'); $this->assertEquals($hero->Title, 'Hero module'); } /** * Test that the module render function is producing content. */ public function testPageModuleRender() { Director::setBaseURL('http://www.example.com/'); $hero = $this->objFromFixture('PageModule', 'hero'); $this->assertNotEmpty($hero->Content()); } /** * Test that we're able to creat a new module instance, then convert its type to a subclass. */ public function testCreateNewModule() { $module = new PageModule(); $module->NewClassName = 'TestModule1'; $module->Write(); $this->assertEquals($module->ClassName, 'TestModule1'); } }
<?php class HeroModule extends PageModule { } class PageModuleTest extends SapphireTest { protected static $fixture_file = 'PageModuleTest.yml'; /** * Test that we're able to create a page module. */ public function testPageModuleCreation() { $hero = $this->objFromFixture('PageModule', 'hero'); $this->assertEquals($hero->Title, 'Hero module'); } /** * Test that the module render function is producing content. */ public function testPageModuleRender() { Director::setBaseURL('http://www.example.com/'); $hero = $this->objFromFixture('PageModule', 'hero'); $this->assertNotEmpty($hero->Content()); } /** * Test that we're able to creat a new module instance, then convert its type to a subclass. */ public function testCreateNewModule() { $module = new PageModule(); $module->NewClassName = 'HeroModule'; $module->Write(); $this->assertEquals($module->ClassName, 'HeroModule'); } }
Move timeline check before t pull
package com.tmitim.twittercli.commands; import com.github.rvesse.airline.annotations.Command; import com.github.rvesse.airline.annotations.Option; import com.tmitim.twittercli.TimeLiner; import com.tmitim.twittercli.pojos.TimeLine; import twitter4j.TwitterFactory; /** * Get timeline */ @Command(name = "timeline", description = "Get your timeline") public class TimeLineCommand implements Runnable { @Option(name = { "-u", "--user" }, description = "get the timeline for a specific username") private String username; @Option(name = { "-a", "--all" }, description = "get all tweets (defaults is only new tweets)") private boolean allStatuses; @Option(name = { "-c", "--clear" }, description = "clear last checked time before pulling timeline") private boolean clearLast; @Override public void run() { TimeLiner tl = new TimeLiner( new TimeLine(TwitterFactory.getSingleton()).setAllStatuses(allStatuses).setUsername(username)); if (clearLast) { tl.clearLastCheck(); } tl.pullStatuses(); if (username == null) { tl.updateLastCheck(); } tl.printStatuses(); } }
package com.tmitim.twittercli.commands; import com.github.rvesse.airline.annotations.Command; import com.github.rvesse.airline.annotations.Option; import com.tmitim.twittercli.TimeLiner; import com.tmitim.twittercli.pojos.TimeLine; import twitter4j.TwitterFactory; /** * Get timeline */ @Command(name = "timeline", description = "Get your timeline") public class TimeLineCommand implements Runnable { @Option(name = { "-u", "--user" }, description = "get the timeline for a specific username") private String username; @Option(name = { "-a", "--all" }, description = "get all tweets (defaults is only new tweets)") private boolean allStatuses; @Option(name = { "-c", "--clear" }, description = "clear last checked time") private boolean clearLast; @Override public void run() { TimeLiner tl = new TimeLiner( new TimeLine(TwitterFactory.getSingleton()).setAllStatuses(allStatuses).setUsername(username)); tl.pullStatuses(); if (username == null) { tl.updateLastCheck(); } if (clearLast) { tl.clearLastCheck(); } tl.printStatuses(); } }
Add additional Entry test to show distinction between sha and itemhash
package uk.gov.register.core; import org.junit.Test; import java.time.Instant; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; public class EntryTest { @Test public void getTimestampAsISOFormat_returnsTheFormattedTimestamp() { Entry entry = new Entry(123, "abc", Instant.ofEpochSecond(1470403440)); assertThat(entry.getTimestampAsISOFormat(), equalTo("2016-08-05T13:24:00Z")); } @Test public void getSha256hex_returnsTheSha256HexOfItem() { Entry entry = new Entry(123, "abc", Instant.ofEpochSecond(1470403440)); assertThat(entry.getSha256hex(), equalTo("abc")); } @Test public void getItemHash_returnsSha256AsItemHash() { Entry entry = new Entry(123, "abc", Instant.ofEpochSecond(1470403440)); assertThat(entry.getItemHash(), equalTo("sha-256:abc")); } }
package uk.gov.register.core; import org.junit.Test; import java.time.Instant; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; public class EntryTest { @Test public void getTimestampAsISOFormat_returnsTheFormattedTimestamp() { Entry entry = new Entry(123, "abc", Instant.ofEpochSecond(1470403440)); assertThat(entry.getTimestampAsISOFormat(), equalTo("2016-08-05T13:24:00Z")); } @Test public void getItemHash_returnsSha256AsItemHash() { Entry entry = new Entry(123, "abc", Instant.ofEpochSecond(1470403440)); assertThat(entry.getItemHash(), equalTo("sha-256:abc")); } }
Change base API url version to 1
""" There are two ways of constructing a software design. One way is to make it so simple that there are obviously no deficiencies. And the other way is to make it so complicated that there are no obvious deficiencies. - C. A. R. Hoare """ from django.conf.urls import patterns, include, url from django.contrib import admin from django.conf import settings urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), # Grappelli URLs url(r'^grappelli/', include('grappelli.urls')), # Default Root # url(r'^$', 'dpn_registry.views.index', name="siteroot"), # Login URL url(r'^%s$' % settings.LOGIN_URL, 'django.contrib.auth.views.login', {'template_name': 'login.html'}, name="login"), url(r'^%s$' % settings.LOGOUT_URL, 'django.contrib.auth.views.logout', {'template_name': 'logout.html'}, name="logout"), # REST Login/Out url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), # API calls url(r'^api-v1/', include('dpn.api.urls', namespace="api")), # API Documentation url(r'^docs/', include('rest_framework_swagger.urls', namespace="api-docs")) )
""" There are two ways of constructing a software design. One way is to make it so simple that there are obviously no deficiencies. And the other way is to make it so complicated that there are no obvious deficiencies. - C. A. R. Hoare """ from django.conf.urls import patterns, include, url from django.contrib import admin from django.conf import settings urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), # Grappelli URLs url(r'^grappelli/', include('grappelli.urls')), # Default Root # url(r'^$', 'dpn_registry.views.index', name="siteroot"), # Login URL url(r'^%s$' % settings.LOGIN_URL, 'django.contrib.auth.views.login', {'template_name': 'login.html'}, name="login"), url(r'^%s$' % settings.LOGOUT_URL, 'django.contrib.auth.views.logout', {'template_name': 'logout.html'}, name="logout"), # REST Login/Out url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), # API calls url(r'^api-v0/', include('dpn.api.urls', namespace="api")), # API Documentation url(r'^docs/', include('rest_framework_swagger.urls', namespace="api-docs")) )
[Order] Order 2: Login system by https
import json import requests """ Order 2: Login system by https This is the code which use curl to login system ``` curl -k https://192.168.105.88/axapi/v3/auth -H "Content-type:application/json" -d '{ "credentials": { "username": "admin", "password": "a10" } }' ``` """ class LoginSystemByHttps(object): login_url = 'https://192.168.105.88/axapi/v3/auth' def login(self): """ Note: the dict playload must be use json.dumps() to turn to str. :return: Result string data """ payload = {'credentials': {'username': "admin", 'password': "a10"}} headers = {'content-type': 'application/json', 'Connection': 'keep-alive'} response = requests.post(self.login_url, data=json.dumps(payload), verify=False, headers=headers) print(response.text) return response.text # login = LoginSystemByHttps() # login.login()
import json import requests """ Order 2: Login system by https This is the code which use curl to login system ``` curl -k https://192.168.105.88/axapi/v3/auth -H "Content-type:application/json" -d '{ "credentials": { "username": "admin", "password": "a10" } }' ``` """ class LoginSystemByHttps(object): login_url = 'http://192.168.105.88/axapi/v3/auth' def login(self): """ Note: the dict playload must be use json.dumps() to turn to str. :return: Result string data """ payload = {'credentials': {'username': "admin", 'password': "a10"}} headers = {'content-type': 'application/json', 'Connection': 'keep-alive'} response = requests.post(self.login_url, data=json.dumps(payload), verify=False, headers=headers) print(response.text) return response.text # login = LoginSystemByHttps() # login.login()
[fix] Make dataset directory if it does not exist.
import tarfile import os from six.moves.urllib import request url_dir = 'https://www.cs.toronto.edu/~kriz/' file_name = 'cifar-10-python.tar.gz' save_dir = 'dataset' tar_path = os.path.join(save_dir, file_name) if __name__ == '__main__': if not os.path.exists(save_dir): os.makedirs(save_dir) if os.path.exists(tar_path): print('{:s} already downloaded.'.format(file_name)) else: print('Downloading {:s}...'.format(file_name)) request.urlretrieve('{:s}{:s}'.format(url_dir, file_name), tar_path) print('Extracting files...') with tarfile.open(tar_path, 'r:gz') as f: f.extractall(save_dir)
import tarfile import os from six.moves.urllib import request url_dir = 'https://www.cs.toronto.edu/~kriz/' file_name = 'cifar-10-python.tar.gz' save_dir = 'dataset' tar_path = os.path.join(save_dir, file_name) if __name__ == '__main__': if os.path.exists(tar_path): print('{:s} already downloaded.'.format(file_name)) else: print('Downloading {:s}...'.format(file_name)) request.urlretrieve('{:s}{:s}'.format(url_dir, file_name), tar_path) print('Extracting files...') with tarfile.open(tar_path, 'r:gz') as f: f.extractall(save_dir)
Add seating plan to aircraft
"""Model for aircraft flights""" class Flight: def __init__(self, number): if not number[:4].isalpha(): raise ValueError("No airline code in '{}'".format(number)) if not number[:4].isupper(): raise ValueError("Invalid airline code'{}'".format(number)) if not (number[4:].isdigit() and int(number[4:]) <= 999999): raise ValueError("Invalid route number '{}'".format(number)) self._number = number def number(self): return self._number def airline(self): return self._number[:4] class Aircraft: def __init__(self, registration, model, num_rows, num_seats_per_row): self._registration = registration self._model = model self._num_rows = num_rows self._num_seats_per_row = num_seats_per_row def registration(self): return self._registration def model(self): return self._model def seating_plan(self): return (range(1, self._num_rows + 1), "ABCDEFGHJKLMNOP"[:self._num_seats_per_row])
"""Model for aircraft flights""" class Flight: def __init__(self, number): if not number[:4].isalpha(): raise ValueError("No airline code in '{}'".format(number)) if not number[:4].isupper(): raise ValueError("Invalid airline code'{}'".format(number)) if not (number[4:].isdigit() and int(number[4:]) <= 999999): raise ValueError("Invalid route number '{}'".format(number)) self._number = number def number(self): return self._number def airline(self): return self._number[:4] class Aircraft: def __init__(self, registration, model, num_rows, num_seats_per_row): self._registration = registration self._model = model self._num_rows = num_rows self._num_seats_per_row = num_seats_per_row def registration(self): return self._registration def model(self): return self._model
Order sponsors by ID on the sponsors page, too
from django.views.generic.list import ListView from django.views.generic import DetailView from rest_framework import viewsets from rest_framework.permissions import DjangoModelPermissionsOrAnonReadOnly from wafer.sponsors.models import Sponsor, SponsorshipPackage from wafer.sponsors.serializers import SponsorSerializer, PackageSerializer class ShowSponsors(ListView): template_name = 'wafer.sponsors/sponsors.html' model = Sponsor def get_queryset(self): return Sponsor.objects.all().order_by('packages', 'id') class SponsorView(DetailView): template_name = 'wafer.sponsors/sponsor.html' model = Sponsor class ShowPackages(ListView): template_name = 'wafer.sponsors/packages.html' model = SponsorshipPackage class SponsorViewSet(viewsets.ModelViewSet): """API endpoint for users.""" queryset = Sponsor.objects.all() serializer_class = SponsorSerializer permission_classes = (DjangoModelPermissionsOrAnonReadOnly, ) class PackageViewSet(viewsets.ModelViewSet): """API endpoint for users.""" queryset = SponsorshipPackage.objects.all() serializer_class = PackageSerializer permission_classes = (DjangoModelPermissionsOrAnonReadOnly, )
from django.views.generic.list import ListView from django.views.generic import DetailView from rest_framework import viewsets from rest_framework.permissions import DjangoModelPermissionsOrAnonReadOnly from wafer.sponsors.models import Sponsor, SponsorshipPackage from wafer.sponsors.serializers import SponsorSerializer, PackageSerializer class ShowSponsors(ListView): template_name = 'wafer.sponsors/sponsors.html' model = Sponsor def get_queryset(self): return Sponsor.objects.all().order_by('packages') class SponsorView(DetailView): template_name = 'wafer.sponsors/sponsor.html' model = Sponsor class ShowPackages(ListView): template_name = 'wafer.sponsors/packages.html' model = SponsorshipPackage class SponsorViewSet(viewsets.ModelViewSet): """API endpoint for users.""" queryset = Sponsor.objects.all() serializer_class = SponsorSerializer permission_classes = (DjangoModelPermissionsOrAnonReadOnly, ) class PackageViewSet(viewsets.ModelViewSet): """API endpoint for users.""" queryset = SponsorshipPackage.objects.all() serializer_class = PackageSerializer permission_classes = (DjangoModelPermissionsOrAnonReadOnly, )
Switch to applet (Game -> GameApplet extension)
package j2048.jgamegui; import java.awt.Color; import jgame.GContainer; import jgame.GRootContainer; import jgame.GameApplet; /** * The driver class for a 2048 game. * * @author William Chargin * */ public class J2048 extends GameApplet { /** * */ private static final long serialVersionUID = 1L; public static final Color MAIN_COLOR = new Color(187, 173, 160); public static final Color TEXT_COLOR = new Color(119, 110, 101); public static final Color LIGHT_COLOR = new Color(250, 248, 239); public static final Color LIGHT_TEXT = new Color(238, 228, 218); public J2048() { core.setTargetFPS(60); GRootContainer root = new GRootContainer(LIGHT_COLOR); core.setRootContainer(root); GContainer container = new GContainer(); GamePanel game = new GamePanel(); container.setSize(game.getWidth() + 50, game.getHeight() + 50); container.addAtCenter(game); root.add(container); } }
package j2048.jgamegui; import java.awt.Color; import jgame.GContainer; import jgame.GRootContainer; import jgame.Game; /** * The driver class for a 2048 game. * * @author William Chargin * */ public class J2048 extends Game { public static final Color MAIN_COLOR = new Color(187, 173, 160); public static final Color TEXT_COLOR = new Color(119, 110, 101); public static final Color LIGHT_COLOR = new Color(250, 248, 239); public static final Color LIGHT_TEXT = new Color(238, 228, 218); public J2048() { setTargetFPS(60); GRootContainer root = new GRootContainer(LIGHT_COLOR); setRootContainer(root); GContainer container = new GContainer(); GamePanel game = new GamePanel(); container.setSize(game.getWidth() + 50, game.getHeight() + 50); container.addAtCenter(game); root.add(container); } public static void main(String[] args) { new J2048().startGame("2048"); } }
Correct length in exe resource string tables the change done by Matt Ellis (citizenmatt)
/* * Copyright 2006 ProductiveMe Inc. * Copyright 2013 JetBrains s.r.o. * * 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.pme.exe.res.vi; import com.pme.exe.Bin; public class StringTable extends VersionInfoBin { public StringTable(String name) { super(name, null, new VersionInfoFactory() { @Override public VersionInfoBin createChild(int index) { return new StringTableEntry(); } }); } public void setStringValue(String key, String value) { for (Bin bin : getMembers()) { if (bin.getName().equals(key)) { StringTableEntry entry = (StringTableEntry) bin; ((WChar) entry.getMember("Value")).setValue(value); ((Word) entry.getMember("wValueLength")).setValue(value.length() + 1); return; } } assert false: "Could not find string with key " + key; } }
/* * Copyright 2006 ProductiveMe Inc. * Copyright 2013 JetBrains s.r.o. * * 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.pme.exe.res.vi; import com.pme.exe.Bin; public class StringTable extends VersionInfoBin { public StringTable(String name) { super(name, null, new VersionInfoFactory() { @Override public VersionInfoBin createChild(int index) { return new StringTableEntry(); } }); } public void setStringValue(String key, String value) { for (Bin bin : getMembers()) { if (bin.getName().equals(key)) { StringTableEntry entry = (StringTableEntry) bin; ((WChar) entry.getMember("Value")).setValue(value); ((Word) entry.getMember("wValueLength")).setValue(value.length()); return; } } assert false: "Could not find string with key " + key; } }
Add JS for some christmas spirit
/** * main.js */ 'use strict'; // Only run in capable browsers via feature detection var didCutTheMustard = 'querySelector' in document && 'classList' in document.createElement('a') && 'addEventListener' in window; /** * Add line numbers to <pre> */ function numberedLines() { var pre = document.querySelectorAll('pre'), pl = pre.length; for (var i = 0; i < pl; i++) { pre[i].insertAdjacentHTML('beforeend', '<span class="ln" aria-hidden="true"></span>'); var num = pre[i].innerHTML.split(/\n/).length; // Start counter at 1 to circumvent Jekyll adding an extra line in <code> for (var j = 1; j < num; j++) { var lineNum = pre[i].querySelector('.ln'); lineNum.insertAdjacentHTML('beforeend', '<span></span>'); } } } /** * Add a little christmas spirit */ function snowyHeader() { var headElem = document.querySelector('head'); var snowStyles = '<link rel="stylesheet" href="//frippz-se.s3.amazonaws.com/christmas.css">'; var header = document.querySelector('#header'); headElem.insertAdjacentHTML('beforeend', snowStyles); header.classList.add('snow'); } if (didCutTheMustard) { // Add class "js" to html element document.querySelector('html').classList.add('js'); // Add numbered lines to <pre> numberedLines(); // Let it snow! snowyHeader(); }
/** * main.js */ 'use strict'; // Only run in capable browsers via feature detection var didCutTheMustard = 'querySelector' in document && 'classList' in document.createElement('a') && 'addEventListener' in window; /** * Add line numbers to <pre> */ function numberedLines() { var pre = document.querySelectorAll('pre'), pl = pre.length; for (var i = 0; i < pl; i++) { pre[i].insertAdjacentHTML('beforeend', '<span class="ln" aria-hidden="true"></span>'); var num = pre[i].innerHTML.split(/\n/).length; // Start counter at 1 to circumvent Jekyll adding an extra line in <code> for (var j = 1; j < num; j++) { var lineNum = pre[i].querySelector('.ln'); lineNum.insertAdjacentHTML('beforeend', '<span></span>'); } } } if (didCutTheMustard) { // Add class "js" to html element document.querySelector('html').classList.add('js'); // Add numbered lines to <pre> numberedLines(); }
Add Next/Previous page links to the docs.
#!/usr/bin/env python3 project = "dependencies" copyright = "2016-2018, Artem Malyshev" author = "Artem Malyshev" version = "0.15" release = "0.15" templates_path = ["templates"] source_suffix = ".rst" master_doc = "index" language = None exclude_patterns = ["_build"] pygments_style = "sphinx" html_theme = "alabaster" html_static_path = ["static"] html_sidebars = { "**": [ "sidebarlogo.html", "stats.html", "globaltoc.html", "relations.html", "updates.html", "links.html", "searchbox.html", "gitter_sidecar.html", ] } html_theme_options = { "show_powered_by": False, "show_related": True, "show_relbars": True, "description": "Dependency Injection for Humans. It provides a simple low-impact implementation of an IoC container and resolution support for your classes.", "github_user": "dry-python", "github_repo": "dependencies", "github_type": "star", "github_count": True, "github_banner": True, }
#!/usr/bin/env python3 project = "dependencies" copyright = "2016-2018, Artem Malyshev" author = "Artem Malyshev" version = "0.15" release = "0.15" templates_path = ["templates"] source_suffix = ".rst" master_doc = "index" language = None exclude_patterns = ["_build"] pygments_style = "sphinx" html_theme = "alabaster" html_static_path = ["static"] html_sidebars = { "**": [ "sidebarlogo.html", "stats.html", "globaltoc.html", "relations.html", "updates.html", "links.html", "searchbox.html", "gitter_sidecar.html", ] } html_theme_options = { "show_powered_by": False, "show_related": True, "description": "Dependency Injection for Humans. It provides a simple low-impact implementation of an IoC container and resolution support for your classes.", "github_user": "dry-python", "github_repo": "dependencies", "github_type": "star", "github_count": True, "github_banner": True, }
Remove init mrthod from disk test Removed init method from test class for disk test
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P. # # 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. # THIS FILE IS MANAGED BY THE GLOBAL REQUIREMENTS REPO - DO NOT EDIT import pytest from utils.disk_utils import DiskIO class TestDisk: @staticmethod def all_free_disk_space_gb(): return reduce(lambda res, x: res+x[1], DiskIO().disks, 0) @pytest.mark.disk @pytest.mark.storage def test_disk_space_storage(self): assert self.all_free_disk_space_gb() > 3000
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P. # # 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. # THIS FILE IS MANAGED BY THE GLOBAL REQUIREMENTS REPO - DO NOT EDIT import pytest from utils.disk_utils import DiskIO class TestDisk: def __init__(self): self.WRITE_MB = 128 self.WRITE_BLOCK_KB = 1024 self.READ_BLOCK_B = 512 @staticmethod def all_free_disk_space_gb(): return reduce(lambda res, x: res+x[1], DiskIO().disks, 0) @pytest.mark.disk @pytest.mark.storage def test_disk_space_storage(self): assert self.all_free_disk_space_gb() > 3000
Fix response from payment removal API (using wrong ID for txn)
<? include '../scat.php'; include '../lib/txn.php'; bcscale(2); $txn_id= (int)$_REQUEST['txn']; $id= (int)$_REQUEST['id']; if (!$txn_id || !$id) die_jsonp("No transaction or payment specified."); $txn= txn_load($db, $txn_id); if ($txn['paid']) die_jsonp("Transaction is fully paid, can't remove payments."); // add payment record $q= "DELETE FROM payment WHERE id = $id AND txn = $txn_id"; $r= $db->query($q) or die_query($db, $q); echo jsonp(array('txn' => txn_load($db, $txn_id), 'payments' => txn_load_payments($db, $txn_id)));
<? include '../scat.php'; include '../lib/txn.php'; bcscale(2); $txn_id= (int)$_REQUEST['txn']; $id= (int)$_REQUEST['id']; if (!$txn_id || !$id) die_jsonp("No transaction or payment specified."); $txn= txn_load($db, $txn_id); if ($txn['paid']) die_jsonp("Transaction is fully paid, can't remove payments."); // add payment record $q= "DELETE FROM payment WHERE id = $id AND txn = $txn_id"; $r= $db->query($q) or die_query($db, $q); echo jsonp(array('txn' => txn_load($db, $id), 'payments' => txn_load_payments($db, $id)));
Use knex for search index raw query.
import BaseModel from '../models/base' export default (app) => { const service = { create: async () => BaseModel.knex().raw( 'REFRESH MATERIALIZED VIEW CONCURRENTLY entries_search' ), } app.use('/searchindex', service) app .service('searchindex') .hooks({ before: { all: [], find: [], }, after: { all: [], find: [], }, error: { all: [], find: [], }, }) .hooks({ after: { all: [], }, }) }
import BaseModel from '../models/base' export default (app) => { const service = { create: async () => BaseModel.raw('REFRESH MATERIALIZED VIEW CONCURRENTLY entries_search'), } app.use('/searchindex', service) app .service('searchindex') .hooks({ before: { all: [], find: [], }, after: { all: [], find: [], }, error: { all: [], find: [], }, }) .hooks({ after: { all: [], }, }) }
Update code in dipy/reconst (PEP8) Using `pycodestyle` output, the file `dipy/reconst/base.py` was updated to pass `pycodestyle` check Signed-off-by: Antonio Ossa <1ecf3d2f96b6e61cf9b68f0fc294cab57dc5d597@uc.cl>
""" Base-classes for reconstruction models and reconstruction fits. All the models in the reconst module follow the same template: a Model object is used to represent the abstract properties of the model, that are independent of the specifics of the data . These properties are reused whenver fitting a particular set of data (different voxels, for example). """ class ReconstModel(object): """ Abstract class for signal reconstruction models """ def __init__(self, gtab): """Initialization of the abstract class for signal reconstruction models Parameters ---------- gtab : GradientTable class instance """ self.gtab = gtab def fit(self, data, mask=None, **kwargs): return ReconstFit(self, data) class ReconstFit(object): """ Abstract class which holds the fit result of ReconstModel For example that could be holding FA or GFA etc. """ def __init__(self, model, data): self.model = model self.data = data
""" Base-classes for reconstruction models and reconstruction fits. All the models in the reconst module follow the same template: a Model object is used to represent the abstract properties of the model, that are independent of the specifics of the data . These properties are reused whenver fitting a particular set of data (different voxels, for example). """ class ReconstModel(object): """ Abstract class for signal reconstruction models """ def __init__(self, gtab): """Initialization of the abstract class for signal reconstruction models Parameters ---------- gtab : GradientTable class instance """ self.gtab=gtab def fit(self, data, mask=None,**kwargs): return ReconstFit(self, data) class ReconstFit(object): """ Abstract class which holds the fit result of ReconstModel For example that could be holding FA or GFA etc. """ def __init__(self, model, data): self.model = model self.data = data
Revert "Added module path to require lookup tree." This reverts commit a32fa1402ca903d66e9626146ebcf0001660ff4d.
(function(ns) { var modules = {}, cache = {}, canon = {}; if (typeof ns.__fhtagn__ == "undefined") { ns.__fhtagn__ = {}; } ns.__fhtagn__.exp = function(paths,cpath,mod) { for (var i in paths) { modules[paths[i]] = mod; canon[paths[i]] = cpath; } }; ns.__fhtagn__.req = function(path,rel) { if (cache[path]) return cache[path]; path = path.replace("/client", ''); path = path.replace(/^\.\//, ''); if (rel) rel = rel.replace("/client", ''); function grab(p) { if (!cache[p]) { cache[p] = modules[p](function(mod) { return ns.__fhtagn__.req(mod, canon[p]); }); } return cache[p]; } for (var mod in modules) { if (mod==path+'.js' || mod==path+'.js' || rel+'/'+path+'.js'==mod || mod==path || mod.replace(/node_modules\//g, '')==path || rel+'/'+path==mod ) return grab(mod); } throw "Cannot find module "+path+" (called from "+(rel||"root")+")"; }; })(this);
(function() { var modules = {}, cache = {}; if (typeof __fhtagn__ == "undefined") { window.__fhtagn__ = {}; __fhtagn__ = window.__fhtagn__; } __fhtagn__.exp = function(paths, mod) { for (var i in paths) modules[paths[i]] = mod; }; __fhtagn__.req = function(path,relative) { var mod_relative; if (relative=="__index__") relative = null; mod_relative = relative+'/node_modules/'+path; if (relative) path = relative+'/'+path; if (cache[path]) return cache[path]; function grab(p) { cache[p] = modules[p](function(mod) { return __fhtagn__.req(mod, p); }); return cache[p]; } for (var mod in modules) { if (mod==path+'.js' || mod==path.replace(/^\.\//, '')+'.js' || mod==path || mod.replace(/node_modules\//g, '')==path || mod_relative==mod ) return grab(mod); } console.error("Cannot find module", path); } __fhtagn__ = __fhtagn__; })();
Fix ptsname() for big-endian architectures On big-endian architectures unix.IoctlGetInt() leads to a wrong result because a 32 bit value is stored into a 64 bit buffer. When dereferencing the result is left shifted by 32. Without this patch ptsname() returns a wrong path from the second pty onwards. To protect syscalls against re-arranging by the GC the conversion from unsafe.Pointer to uintptr must occur in the Syscall expression itself. See the documentation of the unsafe package for details. Signed-off-by: Peter Morjan <964d0cf54dbf76d367f54f543a3db8d083ad8566@de.ibm.com>
package console import ( "fmt" "os" "unsafe" "golang.org/x/sys/unix" ) const ( cmdTcGet = unix.TCGETS cmdTcSet = unix.TCSETS ) // unlockpt unlocks the slave pseudoterminal device corresponding to the master pseudoterminal referred to by f. // unlockpt should be called before opening the slave side of a pty. func unlockpt(f *os.File) error { var u int32 if _, _, err := unix.Syscall(unix.SYS_IOCTL, f.Fd(), unix.TIOCSPTLCK, uintptr(unsafe.Pointer(&u))); err != 0 { return err } return nil } // ptsname retrieves the name of the first available pts for the given master. func ptsname(f *os.File) (string, error) { var u uint32 if _, _, err := unix.Syscall(unix.SYS_IOCTL, f.Fd(), unix.TIOCGPTN, uintptr(unsafe.Pointer(&u))); err != 0 { return "", err } return fmt.Sprintf("/dev/pts/%d", u), nil }
package console import ( "fmt" "os" "unsafe" "golang.org/x/sys/unix" ) const ( cmdTcGet = unix.TCGETS cmdTcSet = unix.TCSETS ) func ioctl(fd, flag, data uintptr) error { if _, _, err := unix.Syscall(unix.SYS_IOCTL, fd, flag, data); err != 0 { return err } return nil } // unlockpt unlocks the slave pseudoterminal device corresponding to the master pseudoterminal referred to by f. // unlockpt should be called before opening the slave side of a pty. func unlockpt(f *os.File) error { var u int32 return ioctl(f.Fd(), unix.TIOCSPTLCK, uintptr(unsafe.Pointer(&u))) } // ptsname retrieves the name of the first available pts for the given master. func ptsname(f *os.File) (string, error) { n, err := unix.IoctlGetInt(int(f.Fd()), unix.TIOCGPTN) if err != nil { return "", err } return fmt.Sprintf("/dev/pts/%d", n), nil }
Add note about build-generated members
/* * Copyright 2015 John "LuaMilkshake" Marion * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.pktr.smartbackup; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.event.FMLServerStartingEvent; @Mod(modid = SmartBackup.MOD_ID, name = SmartBackup.MOD_NAME, version = SmartBackup.VERSION, acceptableRemoteVersions = "*") public class SmartBackup { public static final String MOD_ID = "smartbackup"; public static final String MOD_NAME = "SmartBackup"; // These are filled in by the build process. public static final String VERSION = "$VERSION$"; public static final String SOURCE_REVISION = "$SOURCE_REVISION$"; public static final String BUILD_TIMESTAMP = "$BUILD_TIMESTAMP$"; @EventHandler public void serverStartingEvent(FMLServerStartingEvent event) { event.registerServerCommand(new BackupCommand()); } }
/* * Copyright 2015 John "LuaMilkshake" Marion * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.pktr.smartbackup; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.event.FMLServerStartingEvent; @Mod(modid = SmartBackup.MOD_ID, name = SmartBackup.MOD_NAME, version = SmartBackup.VERSION, acceptableRemoteVersions = "*") public class SmartBackup { public static final String MOD_ID = "smartbackup"; public static final String MOD_NAME = "SmartBackup"; public static final String VERSION = "$VERSION$"; public static final String SOURCE_REVISION = "$SOURCE_REVISION$"; public static final String BUILD_TIMESTAMP = "$BUILD_TIMESTAMP$"; @EventHandler public void serverStartingEvent(FMLServerStartingEvent event) { event.registerServerCommand(new BackupCommand()); } }
Use new sgactions progress dialog
from sgfs import SGFS from sgactions.utils import notify, progress def run_create(**kwargs): _run(False, **kwargs) def run_preview(**kwargs): _run(True, **kwargs) def _run(dry_run, entity_type, selected_ids, **kwargs): title='Preview Folders' if dry_run else 'Creating Folders' progress(title=title, message='Running; please wait...') sgfs = SGFS() entities = sgfs.session.merge([dict(type=entity_type, id=id_) for id_ in selected_ids]) heirarchy = sgfs.session.fetch_heirarchy(entities) sgfs.session.fetch_core(heirarchy) commands = sgfs.create_structure(entities, dry_run=dry_run) notify( title=title, message='\n'.join(commands) or 'Everything is up to date.', )
from sgfs import SGFS from sgactions.utils import notify def run_create(**kwargs): _run(False, **kwargs) def run_preview(**kwargs): _run(True, **kwargs) def _run(dry_run, entity_type, selected_ids, **kwargs): sgfs = SGFS() entities = sgfs.session.merge([dict(type=entity_type, id=id_) for id_ in selected_ids]) heirarchy = sgfs.session.fetch_heirarchy(entities) sgfs.session.fetch_core(heirarchy) commands = sgfs.create_structure(entities, dry_run=dry_run) notify( title='Preview Folders' if dry_run else 'Creating Folders', message='\n'.join(commands) or 'Everything is up to date.', )
feat: Add initial arrow function test
describe("About Functions", function () { describe("Default Parameters", function () { it("should understand default parameters basic usage", function () { function greeting(string = 'party') { return 'Welcome to the ' + string + ' pal!'; } expect(greeting()).toEqual(FILL_ME_IN); expect(greeting('get together')).toEqual(FILL_ME_IN); expect(undefined).toEqual(FILL_ME_IN); expect(null).toEqual(FILL_ME_IN); function getDefaultValue() { return 'party'; } function greetingAgain(string = getDefaultValue()) { return 'Welcome to the ' + string + ' pal!'; } expect(greetingAgain()).toEqual(FILL_ME_IN); }); }); // describe('Rest Paramaters', function() { // // }) // // describe('Spread Parameters', function() { // // }) // describe('Arrow Functions', function() { it('shound understand basic usage', function() { var arrowFn = () => { 'hello world!'; }; expect(arrowFn()).toEqual(FILL_ME_IN); var arrowFnTwo = (number) => { number * 2; } expect(arrowFnTwo(4)).toEqual(FILL_ME_IN); }) }) });
describe("About Functions", function () { describe("Default Parameters", function () { it("should understand default parameters basic usage", function () { function greeting(string = 'party') { return 'Welcome to the ' + string + ' pal!'; } expect(greeting()).toEqual(FILL_ME_IN); expect(greeting('get together')).toEqual(FILL_ME_IN); expect(undefined).toEqual(FILL_ME_IN); expect(null).toEqual(FILL_ME_IN); function getDefaultValue() { return 'party'; } function greetingAgain(string = getDefaultValue()) { return 'Welcome to the ' + string + ' pal!'; } expect(greetingAgain()).toEqual(FILL_ME_IN); }); }); // describe('Rest Paramaters', function() { // // }) // // describe('Spread Parameters', function() { // // }) // // describe('Arrow Functions', function() { // // }) });
Create table in the database via console.
<?php namespace DTR\DTRBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * ShopType * * @ORM\Table(name="shoptype") * @ORM\Entity */ class ShopType { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="name", type="string", length=255) */ private $name; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set name * * @param string $name * * @return ShopType */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } } //Table created
<?php namespace DTR\DTRBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * ShopType * * @ORM\Table(name="shoptype") * @ORM\Entity */ class ShopType { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="name", type="string", length=255) */ private $name; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set name * * @param string $name * * @return ShopType */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } }
Update for github commit settings
import React, { Component } from 'react' import '../../css/style.css' import FA from 'react-fontawesome' class Footer extends Component { render(){ return( <div className="Footer" > <br /> <FA name="linkedin" border={true} size="2x" /> <FA name="facebook" border={true} size="2x" /> <br /> <p>Beautifully designed with ❤️ by .this</p> </div> ) } } export default Footer
import React, { Component } from 'react' import '../../css/style.css' import FA from 'react-fontawesome' class Footer extends Component { render(){ return( <div className="Footer" > <br /> <FA name="linkedin" border={true} size="2x" /> <FA name="facebook" border={true} size="2x" /> <br /> <p>Designed with ❤️ by .this</p> </div> ) } } export default Footer
Make some modules flow strict Summary: TSIA Changelog: [Internal] Reviewed By: mdvacca Differential Revision: D28412774 fbshipit-source-id: 899a78e573bb49633690275052d5e7cb069327fb
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow strict * @format */ import * as React from 'react'; import {useContext} from 'react'; import GlobalPerformanceLogger from './GlobalPerformanceLogger'; import type {IPerformanceLogger} from './createPerformanceLogger'; /** * This is a React Context that provides a scoped instance of IPerformanceLogger. * We wrap every <AppContainer /> with a Provider for this context so the logger * should be available in every component. * See React docs about using Context: https://reactjs.org/docs/context.html */ const PerformanceLoggerContext: React.Context<IPerformanceLogger> = React.createContext( GlobalPerformanceLogger, ); if (__DEV__) { PerformanceLoggerContext.displayName = 'PerformanceLoggerContext'; } export function usePerformanceLogger(): IPerformanceLogger { return useContext(PerformanceLoggerContext); } export default PerformanceLoggerContext;
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow strict-local * @format */ import * as React from 'react'; import {useContext} from 'react'; import GlobalPerformanceLogger from './GlobalPerformanceLogger'; import type {IPerformanceLogger} from './createPerformanceLogger'; /** * This is a React Context that provides a scoped instance of IPerformanceLogger. * We wrap every <AppContainer /> with a Provider for this context so the logger * should be available in every component. * See React docs about using Context: https://reactjs.org/docs/context.html */ const PerformanceLoggerContext: React.Context<IPerformanceLogger> = React.createContext( GlobalPerformanceLogger, ); if (__DEV__) { PerformanceLoggerContext.displayName = 'PerformanceLoggerContext'; } export function usePerformanceLogger(): IPerformanceLogger { return useContext(PerformanceLoggerContext); } export default PerformanceLoggerContext;
Reset search on page change
/* By default the search is hidden. When you add a component on the page that wants to use the search, * then add this as a mixin. It will use CSS to activate the search while the component is shown. * * WARNING: this assumes that it is called within a <keep-alive> tag, therefore it listens * at activated/deactivated lifecycle hooks. */ export default { data () { return { searchTerm: '' } }, activated: function () { this.eventbus.$emit('search.reset') this.eventbus.$emit('search.visible', true) }, deactivated: function () { this.eventbus.$emit('search.visible', false) }, created () { this.eventbus.$on('search.term', this.searchEventReceived) this.eventbus.$emit('search.init') }, beforeDestroy: function () { this.eventbus.$off('search.term', this.searchEventReceived) }, methods: { searchEventReceived (term) { this.searchTerm = term } } }
/* By default the search is hidden. When you add a component on the page that wants to use the search, * then add this as a mixin. It will use CSS to activate the search while the component is shown. * * WARNING: this assumes that it is called within a <keep-alive> tag, therefore it listens * at activated/deactivated lifecycle hooks. */ export default { data () { return { searchTerm: '' } }, activated: function () { this.eventbus.$emit('search.visible', true) }, deactivated: function () { this.eventbus.$emit('search.visible', false) }, created () { this.eventbus.$on('search.term', this.searchEventReceived) this.eventbus.$emit('search.init') }, beforeDestroy: function () { this.eventbus.$off('search.term', this.searchEventReceived) }, methods: { searchEventReceived (term) { this.searchTerm = term } } }
Load the backend with get_cache
import time from django.test import TestCase from django.core.cache import get_cache class InfiniteMemcached(TestCase): def test_handle_timeouts(self): mc = get_cache('infinite_memcached.cache.MemcachedCache', LOCATION='127.0.0.1:11211') self.assertEqual(0, mc._get_memcache_timeout(0)) self.assertEqual(60, mc._get_memcache_timeout(60)) self.assertEqual(300, mc._get_memcache_timeout(None)) # For timeouts over 30 days, the expire time is stored as a # UNIX timestamp. Just make sure that happens. sixty_days = (60*60*24*60) self.assertEqual(int(time.time() + sixty_days), mc._get_memcache_timeout(sixty_days))
import time from django.test import TestCase from infinite_memcached.cache import MemcachedCache class InfiniteMemcached(TestCase): def test_handle_timeouts(self): mc = MemcachedCache( server="127.0.0.1:11211", params={}, ) self.assertEqual(0, mc._get_memcache_timeout(0)) self.assertEqual(60, mc._get_memcache_timeout(60)) self.assertEqual(300, mc._get_memcache_timeout(None)) # For timeouts over 30 days, the expire time is stored as a # UNIX timestamp. Just make sure that happens. sixty_days = (60*60*24*60) self.assertEqual(int(time.time() + sixty_days), mc._get_memcache_timeout(sixty_days))
Use the proper test code.
"use strict"; var exampleTests = require('../example-tests'); function Controls(mochaRunner) { this._mochaRunner = mochaRunner; } Controls.prototype = { connectButtons: function(passingButtonId, failingButtonId, manyButtonId) { function connect(id, fn) { document.getElementById(id).addEventListener('click', fn); } connect(passingButtonId, this._postPassingTest.bind(this)); connect(failingButtonId, this._postFailingTest.bind(this)); connect(manyButtonId, this._postManyTests.bind(this)); }, _postPassingTest: function() { this._postTestSourceCode(exampleTests.simplePassingTestCode); }, _postFailingTest: function() { this._postTestSourceCode(exampleTests.simpleFailingTestCode); }, _postManyTests: function() { this._postTestSourceCode([ exampleTests.simplePassingTestCode, exampleTests.simplePassingTestCode, exampleTests.simplePassingTestCode, exampleTests.simpleFailingTestCode, exampleTests.simpleFailingTestCode, exampleTests.simplePassingTestCode ].join('\n')); }, _postTestSourceCode: function(sourceCode) { this._mochaRunner.send(sourceCode); } }; module.exports = Controls;
"use strict"; var exampleTests = require('../example-tests'); function Controls(mochaRunner) { this._mochaRunner = mochaRunner; } Controls.prototype = { connectButtons: function(passingButtonId, failingButtonId, manyButtonId) { function connect(id, fn) { document.getElementById(id).addEventListener('click', fn); } connect(passingButtonId, this._postPassingTest.bind(this)); connect(failingButtonId, this._postFailingTest.bind(this)); connect(manyButtonId, this._postManyTests.bind(this)); }, _postPassingTest: function() { this._postTestSourceCode(exampleTests.simplePassingTestCode); }, _postFailingTest: function() { this._postTestSourceCode(exampleTests.simplePassingTestCode); }, _postManyTests: function() { this._postTestSourceCode([ exampleTests.simplePassingTestCode, exampleTests.simplePassingTestCode, exampleTests.simplePassingTestCode, exampleTests.simpleFailingTestCode, exampleTests.simpleFailingTestCode, exampleTests.simplePassingTestCode ].join('\n')); }, _postTestSourceCode: function(sourceCode) { this._mochaRunner.send(sourceCode); } }; module.exports = Controls;