text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Remove unnecessary code and libraries
import sys from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream import tweepy #Get Hashtag to track argTag = sys.argv[1] #Class for listening to all tweets class TweetListener(StreamListener): def on_status(self, status): print status.created_at #Write timestamp to file f = open("logs/" + argTag + ".txt", "a") f.write(str(status.created_at) + "\n") f.close() return True def on_error(self, status): print status if __name__ == '__main__': listener = TweetListener() #Keys CONSUMER_KEY = '' CONSUMER_SECRET = '' ACCESS_KEY = '' ACCESS_SECRET = '' #Initialise and Authorise auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_KEY, ACCESS_SECRET) stream = Stream(auth, listener) stream.filter(track = [argTag])
#-*- coding: utf-8 -*- import time import sys from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream import tweepy import json #Get Hashtag to track argTag = sys.argv[1] #Class for listening to all tweets class TweetListener(StreamListener): def on_status(self, status): print status.created_at #Write timestamp to file f = open("logs/" + argTag + ".txt", "a") f.write(str(status.created_at) + "\n") f.close() return True def on_error(self, status): print status if __name__ == '__main__': listener = TweetListener() #Keys CONSUMER_KEY = '' CONSUMER_SECRET = '' ACCESS_KEY = '' ACCESS_SECRET = '' #Initialise and Authorise auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_KEY, ACCESS_SECRET) stream = Stream(auth, listener) stream.filter(track = [argTag])
Use META.SERVER_NAME in template view. We may want to access this example from a different machine.
# -*- coding: utf-8 -*- from django.contrib.auth.models import User from django.http import HttpResponse from django.views.generic.base import TemplateView from django.views.decorators.csrf import csrf_exempt import redis from ws4redis import settings as redis_settings class BaseTemplateView(TemplateView): def get_context_data(self, **kwargs): context = super(BaseTemplateView, self).get_context_data(**kwargs) context.update(ws_url='ws://{SERVER_NAME}:{SERVER_PORT}/ws/foobar'.format(**self.request.META)) return context class BroadcastChatView(BaseTemplateView): template_name = 'broadcast_chat.html' class UserChatView(BaseTemplateView): template_name = 'user_chat.html' def __init__(self): self._connection = redis.StrictRedis(host=redis_settings.REDIS_HOST, port=redis_settings.REDIS_PORT, db=0) def get_context_data(self, **kwargs): users = User.objects.all() context = super(UserChatView, self).get_context_data(**kwargs) context.update(users=users) return context @csrf_exempt def post(self, request, *args, **kwargs): channel = u'{0}:foobar'.format(request.POST.get('user')) self._connection.publish(channel, request.POST.get('message')) return HttpResponse('OK')
# -*- coding: utf-8 -*- from django.contrib.auth.models import User from django.http import HttpResponse from django.views.generic.base import TemplateView from django.views.decorators.csrf import csrf_exempt import redis from ws4redis import settings as redis_settings class BaseTemplateView(TemplateView): def get_context_data(self, **kwargs): context = super(BaseTemplateView, self).get_context_data(**kwargs) context.update(ws_url='ws://localhost:{SERVER_PORT}/ws/foobar'.format(**self.request.META)) return context class BroadcastChatView(BaseTemplateView): template_name = 'broadcast_chat.html' class UserChatView(BaseTemplateView): template_name = 'user_chat.html' def __init__(self): self._connection = redis.StrictRedis(host=redis_settings.REDIS_HOST, port=redis_settings.REDIS_PORT, db=0) def get_context_data(self, **kwargs): users = User.objects.all() context = super(UserChatView, self).get_context_data(**kwargs) context.update(users=users) return context @csrf_exempt def post(self, request, *args, **kwargs): channel = u'{0}:foobar'.format(request.POST.get('user')) self._connection.publish(channel, request.POST.get('message')) return HttpResponse('OK')
Fix typo where wrong column name was checked for being null
""" Revision ID: 0313_email_access_validated_at Revises: 0312_populate_returned_letters Create Date: 2020-01-28 18:03:22.237386 """ from alembic import op import sqlalchemy as sa revision = '0313_email_access_validated_at' down_revision = '0312_populate_returned_letters' def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('users', sa.Column('email_access_validated_at', sa.DateTime(), nullable=True)) # if user has email_auth, set email_access_validated_at on last login, else set it at user created_at date. op.execute(""" UPDATE users SET email_access_validated_at = created_at """) op.execute(""" UPDATE users SET email_access_validated_at = logged_in_at WHERE auth_type = 'email_auth' AND logged_in_at IS NOT NULL """) op.alter_column('users', 'email_access_validated_at', nullable=False) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('users', 'email_access_validated_at') # ### end Alembic commands ###
""" Revision ID: 0313_email_access_validated_at Revises: 0312_populate_returned_letters Create Date: 2020-01-28 18:03:22.237386 """ from alembic import op import sqlalchemy as sa revision = '0313_email_access_validated_at' down_revision = '0312_populate_returned_letters' def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('users', sa.Column('email_access_validated_at', sa.DateTime(), nullable=True)) # if user has email_auth, set email_access_validated_at on last login, else set it at user created_at date. op.execute(""" UPDATE users SET email_access_validated_at = created_at """) op.execute(""" UPDATE users SET email_access_validated_at = logged_in_at WHERE auth_type = 'email_auth' AND email_access_validated_at IS NOT NULL """) op.alter_column('users', 'email_access_validated_at', nullable=False) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('users', 'email_access_validated_at') # ### end Alembic commands ###
Allow the default Remarkup <p> tag to be inline-styled for mail Summary: Ref T10694. Browsers / mail clients have default `<p>` rules, particularly margin/padding. This allows the inline stuff to turn them off with explicit `"padding: 0; margin: 0;"` so it can control spacing more precisely. Test Plan: See D15857. Reviewers: chad Reviewed By: chad Maniphest Tasks: T10694 Differential Revision: https://secure.phabricator.com/D15858
<?php final class PhutilRemarkupDefaultBlockRule extends PhutilRemarkupBlockRule { public function getPriority() { return 750; } public function getMatchingLineCount(array $lines, $cursor) { return 1; } public function markupText($text, $children) { $engine = $this->getEngine(); $text = trim($text); $text = $this->applyRules($text); if ($engine->isTextMode()) { if (!$this->getEngine()->getConfig('preserve-linebreaks')) { $text = preg_replace('/ *\n */', ' ', $text); } return $text; } if ($engine->getConfig('preserve-linebreaks')) { $text = phutil_escape_html_newlines($text); } if (!strlen($text)) { return null; } $default_attributes = $engine->getConfig('default.p.attributes'); if ($default_attributes) { $attributes = $default_attributes; } else { $attributes = array(); } return phutil_tag('p', $attributes, $text); } }
<?php final class PhutilRemarkupDefaultBlockRule extends PhutilRemarkupBlockRule { public function getPriority() { return 750; } public function getMatchingLineCount(array $lines, $cursor) { return 1; } public function markupText($text, $children) { $text = trim($text); $text = $this->applyRules($text); if ($this->getEngine()->isTextMode()) { if (!$this->getEngine()->getConfig('preserve-linebreaks')) { $text = preg_replace('/ *\n */', ' ', $text); } return $text; } if ($this->getEngine()->getConfig('preserve-linebreaks')) { $text = phutil_escape_html_newlines($text); } if (!strlen($text)) { return null; } return phutil_tag('p', array(), $text); } }
Adjust epoch estimation time for Homestead
HandlebarsIntl.registerWith(Handlebars); $(function() { window.state = {}; var source = $("#stats-template").html(); var template = Handlebars.compile(source); refreshStats(template); setInterval(function() { refreshStats(template); }, 5000) }); function refreshStats(template) { $.getJSON("/stats", function(stats) { $("#alert").addClass('hide'); // Sort miners by ID if (stats.miners) { stats.miners = stats.miners.sort(compare) } var epochOffset = (30000 - (stats.height % 30000)) * 1000 * 15 stats.nextEpoch = stats.now + epochOffset // Repaint stats var html = template(stats); $('#stats').html(html); }).fail(function() { $("#alert").removeClass('hide'); }); } function compare(a, b) { if (a.name < b.name) return -1; if (a.name > b.name) return 1; return 0; }
HandlebarsIntl.registerWith(Handlebars); $(function() { window.state = {}; var source = $("#stats-template").html(); var template = Handlebars.compile(source); refreshStats(template); setInterval(function() { refreshStats(template); }, 5000) }); function refreshStats(template) { $.getJSON("/stats", function(stats) { $("#alert").addClass('hide'); // Sort miners by ID if (stats.miners) { stats.miners = stats.miners.sort(compare) } var epochOffset = (30000 - (stats.height % 30000)) * 1000 * 17 stats.nextEpoch = stats.now + epochOffset // Repaint stats var html = template(stats); $('#stats').html(html); }).fail(function() { $("#alert").removeClass('hide'); }); } function compare(a, b) { if (a.name < b.name) return -1; if (a.name > b.name) return 1; return 0; }
Test: Add debug info to diagnose failing tests on Travis CI
'use strict'; const fs = require('fs'); const path = require('path'); const glob = require('glob'); const isCreateReactApp = require('./isCreateReactApp'); const CREATE_REACT_APP_WEBPACK_CONFIG = 'react-scripts/config/webpack.config.dev'; const USER_WEBPACK_CONFIG_NAMES = [ 'webpack.config.dev.js', 'webpack.config.js', ]; const USER_WEBPACK_CONFIG_MASK = '!(node_modules)*/**/webpack.config{.dev,}.js'; /** * Find user’s Webpack config and return its path. * Fixed location for create-react-app or search for the first webpack.config.dev.js or webpack.config.js. * Returns false if config not found. * * @return {string|boolean} */ module.exports = function findUserWebpackConfig() { // create-react-app if (isCreateReactApp()) { return CREATE_REACT_APP_WEBPACK_CONFIG; } // Quick check in the root folder for (const configFile of USER_WEBPACK_CONFIG_NAMES) { if (fs.existsSync(configFile)) { return path.resolve(configFile); } } // Slower glob for ancestor folders console.log('CWD', process.cwd()); // eslint-disable-line no-console const foundConfig = glob.sync(USER_WEBPACK_CONFIG_MASK); if (foundConfig.length) { return path.resolve(foundConfig[0]); } return false; };
'use strict'; const fs = require('fs'); const path = require('path'); const glob = require('glob'); const isCreateReactApp = require('./isCreateReactApp'); const CREATE_REACT_APP_WEBPACK_CONFIG = 'react-scripts/config/webpack.config.dev'; const USER_WEBPACK_CONFIG_NAMES = [ 'webpack.config.dev.js', 'webpack.config.js', ]; const USER_WEBPACK_CONFIG_MASK = '!(node_modules)*/**/webpack.config{.dev,}.js'; /** * Find user’s Webpack config and return its path. * Fixed location for create-react-app or search for the first webpack.config.dev.js or webpack.config.js. * Returns false if config not found. * * @return {string|boolean} */ module.exports = function findUserWebpackConfig() { // create-react-app if (isCreateReactApp()) { return CREATE_REACT_APP_WEBPACK_CONFIG; } // Quick check in the root folder for (const configFile of USER_WEBPACK_CONFIG_NAMES) { if (fs.existsSync(configFile)) { return path.resolve(configFile); } } // Slower glob for ancestor folders const foundConfig = glob.sync(USER_WEBPACK_CONFIG_MASK); if (foundConfig.length) { return path.resolve(foundConfig[0]); } return false; };
Fix OOM by reducing batch
#%% Setup. import numpy as np import scipy.io.wavfile from keras.utils.visualize_util import plot from keras.callbacks import TensorBoard, ModelCheckpoint from keras.utils import np_utils from eva.models.wavenet import Wavenet, compute_receptive_field from eva.util.mutil import sparse_labels #%% Data RATE, DATA = scipy.io.wavfile.read('./data/undertale/undertale_001_once_upon_a_time.comp.wav') #%% Model Config. MODEL = Wavenet FILTERS = 32 DEPTH = 7 STACKS = 4 LENGTH = 1 + compute_receptive_field(RATE, DEPTH, STACKS)[0] BINS = 256 LOAD = False #%% Model. INPUT = (LENGTH, BINS) ARGS = (INPUT, FILTERS, DEPTH, STACKS) M = MODEL(*ARGS) if LOAD: M.load_weights('model.h5') M.summary() plot(M) #%% Train. TRAIN = np_utils.to_categorical(DATA, BINS) TRAIN = TRAIN[:TRAIN.shape[0]//LENGTH*LENGTH].reshape(TRAIN.shape[0]//LENGTH, LENGTH, BINS) M.fit(TRAIN, sparse_labels(TRAIN), nb_epoch=2000, batch_size=8, callbacks=[TensorBoard(), ModelCheckpoint('model.h5')])
#%% Setup. import numpy as np import scipy.io.wavfile from keras.utils.visualize_util import plot from keras.callbacks import TensorBoard, ModelCheckpoint from keras.utils import np_utils from eva.models.wavenet import Wavenet, compute_receptive_field from eva.util.mutil import sparse_labels #%% Data RATE, DATA = scipy.io.wavfile.read('./data/undertale/undertale_001_once_upon_a_time.comp.wav') #%% Model Config. MODEL = Wavenet FILTERS = 32 DEPTH = 7 STACKS = 4 LENGTH = 1 + compute_receptive_field(RATE, DEPTH, STACKS)[0] BINS = 256 LOAD = False #%% Model. INPUT = (LENGTH, BINS) ARGS = (INPUT, FILTERS, DEPTH, STACKS) M = MODEL(*ARGS) if LOAD: M.load_weights('model.h5') M.summary() plot(M) #%% Train. TRAIN = np_utils.to_categorical(DATA, BINS) TRAIN = TRAIN[:TRAIN.shape[0]//LENGTH*LENGTH].reshape(TRAIN.shape[0]//LENGTH, LENGTH, BINS) M.fit(TRAIN, sparse_labels(TRAIN), nb_epoch=2000, batch_size=32, callbacks=[TensorBoard(), ModelCheckpoint('model.h5')])
Change send bulk message display verb to 'Send message'.
from go.vumitools.conversation.definition import ( ConversationDefinitionBase, ConversationAction) class BulkSendAction(ConversationAction): action_name = 'bulk_send' action_display_name = 'Write and send bulk message' action_display_verb = 'Send message' needs_confirmation = True needs_group = True needs_running = True def check_disabled(self): if self._conv.has_channel_supporting_generic_sends(): return None return ("This action needs channels capable of sending" " messages attached to this conversation.") def perform_action(self, action_data): return self.send_command( 'bulk_send', batch_id=self._conv.batch.key, msg_options={}, content=action_data['message'], delivery_class=self._conv.delivery_class, dedupe=action_data['dedupe']) class ConversationDefinition(ConversationDefinitionBase): conversation_type = 'bulk_message' actions = (BulkSendAction,)
from go.vumitools.conversation.definition import ( ConversationDefinitionBase, ConversationAction) class BulkSendAction(ConversationAction): action_name = 'bulk_send' action_display_name = 'Write and send bulk message' needs_confirmation = True needs_group = True needs_running = True def check_disabled(self): if self._conv.has_channel_supporting_generic_sends(): return None return ("This action needs channels capable of sending" " messages attached to this conversation.") def perform_action(self, action_data): return self.send_command( 'bulk_send', batch_id=self._conv.batch.key, msg_options={}, content=action_data['message'], delivery_class=self._conv.delivery_class, dedupe=action_data['dedupe']) class ConversationDefinition(ConversationDefinitionBase): conversation_type = 'bulk_message' actions = (BulkSendAction,)
Change org-name to what is now lowercase
#!/bin/env python """ Fork github repos """ # technical debt: # -------------- from github3 import login from getpass import getuser import os import sys import time token = '' debug = os.getenv("DM_SQUARE_DEBUG") user = getuser() if debug: print user # I have cut and pasted code # I am a bad person # I promise to make a module file_credential = os.path.expanduser('~/.sq_github_token') if not os.path.isfile(file_credential): print "You don't have a token in {0} ".format(file_credential) print "Have you run github_auth.py?" sys.exit(1) with open(file_credential, 'r') as fd: token = fd.readline().strip() gh = login(token=token) # get the organization object organization = gh.organization('lsst') # list of all LSST repos repos = [g for g in organization.iter_repos()] if debug: print repos for repo in repos: if debug: print repo.name forked_repo = repo.create_fork(user+'-shadow') forked_name = forked_repo.name # Trap previous fork with dm_ prefix if not forked_name.startswith("dm_"): newname = "dm_" + forked_name forked_repo.edit(newname)
#!/bin/env python """ Fork github repos """ # technical debt: # -------------- from github3 import login from getpass import getuser import os import sys import time token = '' debug = os.getenv("DM_SQUARE_DEBUG") user = getuser() if debug: print user # I have cut and pasted code # I am a bad person # I promise to make a module file_credential = os.path.expanduser('~/.sq_github_token') if not os.path.isfile(file_credential): print "You don't have a token in {0} ".format(file_credential) print "Have you run github_auth.py?" sys.exit(1) with open(file_credential, 'r') as fd: token = fd.readline().strip() gh = login(token=token) # get the organization object organization = gh.organization('LSST') # list of all LSST repos repos = [g for g in organization.iter_repos()] if debug: print repos for repo in repos: if debug: print repo.name forked_repo = repo.create_fork(user+'-shadow') forked_name = forked_repo.name # Trap previous fork with dm_ prefix if not forked_name.startswith("dm_"): newname = "dm_" + forked_name forked_repo.edit(newname)
Change finishing main window to finishing applicatoin
'use strict'; var app = require('app'); var path = require('path'); var BrowserWindow = require('browser-window'); module.exports.createMainWindow = function() { const WINDOW_WIDTH = 300; const WINDOW_HEIGHT = 120; var screen = require('screen'); var displaySize = screen.getPrimaryDisplay().size; var mainWindow = new BrowserWindow({ x: (displaySize.width / 2) - (WINDOW_WIDTH / 2), y: displaySize.height - WINDOW_HEIGHT - 50, width: WINDOW_WIDTH, height: WINDOW_HEIGHT, frame: false, resizable: true }); mainWindow.setAlwaysOnTop(true); var htmlPath = path.join(__dirname, '/../../main.html'); mainWindow.loadUrl('file://' + htmlPath); mainWindow.on('closed', function() { app.quit(); }); return mainWindow; };
'use strict'; var path = require('path'); var BrowserWindow = require('browser-window'); module.exports.createMainWindow = function() { const WINDOW_WIDTH = 300; const WINDOW_HEIGHT = 120; var screen = require('screen'); var displaySize = screen.getPrimaryDisplay().size; var mainWindow = new BrowserWindow({ x: (displaySize.width / 2) - (WINDOW_WIDTH / 2), y: displaySize.height - WINDOW_HEIGHT - 50, width: WINDOW_WIDTH, height: WINDOW_HEIGHT, frame: false, resizable: true }); mainWindow.setAlwaysOnTop(true); var htmlPath = path.join(__dirname, '/../../main.html'); mainWindow.loadUrl('file://' + htmlPath); mainWindow.on('closed', function() { mainWindow = null; }); return mainWindow; };
Add a test to create an stream from an string
<?php namespace Http\FactoryTest; use Interop\Http\Factory\StreamFactoryInterface; use PHPUnit_Framework_TestCase as TestCase; use Psr\Http\Message\StreamInterface; class StreamFactoryTest extends TestCase { /** @var StreamFactoryInterface */ private $factory; public function setUp() { $factoryClass = STREAM_FACTORY; $this->factory = new $factoryClass(); } private function assertStream($stream, $content) { $this->assertInstanceOf(StreamInterface::class, $stream); $this->assertSame($content, (string) $stream); } public function testCreateStream() { $resource = tmpfile(); $stream = $this->factory->createStream($resource); $this->assertStream($stream, ''); } public function testCreateStreamWithContent() { $string = 'would you like some crumpets?'; $resource = tmpfile(); fwrite($resource, $string); $stream = $this->factory->createStream($resource); $this->assertStream($stream, $string); } public function testCreateStreamFromAString() { $string = 'would you like some crumpets?'; $stream = $this->factory->createStream($string); $this->assertStream($stream, $string); } }
<?php namespace Http\FactoryTest; use Interop\Http\Factory\StreamFactoryInterface; use PHPUnit_Framework_TestCase as TestCase; use Psr\Http\Message\StreamInterface; class StreamFactoryTest extends TestCase { /** @var StreamFactoryInterface */ private $factory; public function setUp() { $factoryClass = STREAM_FACTORY; $this->factory = new $factoryClass(); } private function assertStream($stream, $content) { $this->assertInstanceOf(StreamInterface::class, $stream); $this->assertSame($content, (string) $stream); } public function testCreateStream() { $resource = tmpfile(); $stream = $this->factory->createStream($resource); $this->assertStream($stream, ''); } public function testCreateStreamWithContent() { $string = 'would you like some crumpets?'; $resource = tmpfile(); fwrite($resource, $string); $stream = $this->factory->createStream($resource); $this->assertStream($stream, $string); } }
Change default example for allowed hosts
# Fill in this file and save as settings_local.py PROJECT_NAME = 'SuperTuxKart' PROJECT_URL = 'http://supertuxkart.net/' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True # Add the name/ip of the server that is running the stats server ALLOWED_HOSTS = ["addons.supertuxkart.net"] ADMINS = ( ('Your Name', 'you@example.com'), ) # Database # https://docs.djangoproject.com/en/1.6/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'stkstats', 'USER': 'stkstats_user', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306', } } # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '#################################################'
# Fill in this file and save as settings_local.py PROJECT_NAME = 'SuperTuxKart' PROJECT_URL = 'http://supertuxkart.net/' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True # Add the name/ip of the server that is running the stats server ALLOWED_HOSTS = ["api.stkaddons.net"] ADMINS = ( ('Your Name', 'you@example.com'), ) # Database # https://docs.djangoproject.com/en/1.6/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'stkstats', 'USER': 'stkstats_user', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306', } } # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '#################################################'
Rename boundaries -> value, on getSelectedTime
export const getSelectedTime = ( server_time, selected_time, market_open_time, ) => { const value = selected_time.isBefore(market_open_time) ? market_open_time.isBefore(server_time) ? server_time.add(5, 'minute') : market_open_time.add(5, 'minute') : selected_time; return value.format('HH:mm'); }; export const getBoundaries = ( server_time, market_open_time, market_close_time, ) => { const boundaries = { start: server_time.isBefore(market_open_time) ? market_open_time.add(5, 'minute') : server_time.add(5, 'minute'), end: market_close_time, }; return boundaries; };
export const getSelectedTime = ( server_time, selected_time, market_open_time, ) => { const boundaries = selected_time.isBefore(market_open_time) ? market_open_time.isBefore(server_time) ? server_time.add(5, 'minute') : market_open_time.add(5, 'minute') : selected_time; return boundaries.format('HH:mm'); }; export const getBoundaries = ( server_time, market_open_time, market_close_time, ) => { const boundaries = { start: server_time.isBefore(market_open_time) ? market_open_time.add(5, 'minute') : server_time.add(5, 'minute'), end: market_close_time, }; return boundaries; };
Rewrite JS reloading etc without jQuery
const handle = setInterval(updateTimestamps, 90000); function updateTimestamps() { let first = true; const stamps = document.querySelectorAll('.humantime'); stamps.forEach(stampItem => { fetch(`/humantime?stamp=${stampItem.dataset.stamp}&first=${first}`) .then(response => { if (response.status === 200) { response.json().then(data => { if (data.first && data.ago.match(/yesterday/i)) { console.log('Cancelling update') clearInterval(handle); // Stop asking after the top one is yesterday } stampItem.textContent = data.ago; }); } }); first = false; }); } const feeds = document.querySelector('#feeds'); const reload = document.querySelector('#reload'); feeds.addEventListener('change', function() { window.location = '/feed/' + this.value; }); reload.addEventListener('click', () => window.location.reload(true));
let handle = setInterval(updateTimestamps, 90000); function updateTimestamps() { let first = true; $(".humantime").each(function () { var $time = $(this); $.get('/humantime', { stamp: this.dataset.stamp, first: first }, function(data) { data = JSON.parse(data); if (data.first && data.ago.match(/yesterday/i)) { console.log('Cancelling update') clearInterval(handle); // Stop asking after the top one is yesterday } $time.text(data.ago) }); first = false; }); } $(function() { $("select#feeds").on('change', function () { window.location = '/feed/' + this.value; }); $("#reload").on('click', function () { window.location.reload(true); }); });
Add /op to spam-prevented commands
package org.c4k3.NoSpam; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerCommandPreprocessEvent; public class CommandListener implements Listener { public CommandListener(NoSpam plugin) { plugin.getServer().getPluginManager().registerEvents(this, plugin); } @EventHandler(priority=EventPriority.LOW, ignoreCancelled=false) public void onPlayerCommandPreprocessEvent(PlayerCommandPreprocessEvent event) { Player player = event.getPlayer(); String message = event.getMessage(); /* Important: The spaces afterwards are necessary. Otherwise we get something like this being activated on /world because of /w */ if (message.startsWith("/tell ") || message.startsWith("/me ") || message.startsWith("/msg ") || message.startsWith("/w ") || message.startsWith("/op ")) { boolean cancel = SpamHandler.isSpamming(player); // The Handler class checks if it's spam if ( cancel ) event.setCancelled(true); } } }
package org.c4k3.NoSpam; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerCommandPreprocessEvent; public class CommandListener implements Listener { public CommandListener(NoSpam plugin) { plugin.getServer().getPluginManager().registerEvents(this, plugin); } @EventHandler(priority=EventPriority.LOW, ignoreCancelled=false) public void onPlayerCommandPreprocessEvent(PlayerCommandPreprocessEvent event) { Player player = event.getPlayer(); String message = event.getMessage(); /* Important: The spaces afterwards are necessary. Otherwise we get something like this being activated on /world because of /w */ if ( message.startsWith("/tell ") || message.startsWith("/me ") || message.startsWith("/msg ") || message.startsWith("/w ") ) { boolean cancel = SpamHandler.isSpamming(player); // The Handler class checks if it's spam if ( cancel ) event.setCancelled(true); } } }
Check for "invalid date" case in JS.
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD // GO AFTER THE REQUIRES BELOW. // //= require jquery //= require bootstrap-sprockets //= require jquery_ujs //= require nicEdit //= require bootstrap-datepicker //= require_tree . $.fn.datepicker.defaults.format = "yyyy-mm-dd"; $(function() { $('.local-time').each(function(_) { var dd = new Date($(this).text()); if (!isNaN(dd.getTime())) { $(this).text(dd); } }); })
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD // GO AFTER THE REQUIRES BELOW. // //= require jquery //= require bootstrap-sprockets //= require jquery_ujs //= require nicEdit //= require bootstrap-datepicker //= require_tree . $.fn.datepicker.defaults.format = "yyyy-mm-dd"; $(function() { $('.local-time').each(function(_) { var dd = new Date($(this).text()); $(this).text(dd); }); })
Delete not need commented code
<?php namespace AppBundle\Listeners; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent; use AppBundle\Exceptions\NoResultException; use AppBundle\Exceptions\InvalidParameterException; class ExceptionListener { public function __construct() { } public function onKernelException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); switch (true) { case $exception instanceof NoResultException: $codeHttp = 404; break; case $exception instanceof InvalidParameterException: $codeHttp = 400; break; default: $codeHttp = 500; } $response = new JsonResponse(array($exception->getMessage()), $codeHttp); $event->setResponse($response); } }
<?php namespace AppBundle\Listeners; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent; use AppBundle\Exceptions\NoResultException; use AppBundle\Exceptions\InvalidParameterException; class ExceptionListener { public function __construct() { } public function onKernelException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); //$request = $event->getRequest(); switch (true) { case $exception instanceof NoResultException: $codeHttp = 404; break; case $exception instanceof InvalidParameterException: $codeHttp = 400; break; default: $codeHttp = 500; } $response = new JsonResponse(array($exception->getMessage()), $codeHttp); $event->setResponse($response); } }
Fix license header violations in yang-data-codec-gson Change-Id: Ia5f799e64b213f20230c2eb03ad572a1c51bd092 Signed-off-by: Thanh Ha <09ea4d3a79c8bee41a16519f6a431f6bc0fd8d6f@linuxfoundation.org>
/* * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.yangtools.yang.data.codec.gson; import com.google.gson.stream.JsonWriter; import java.io.IOException; final class JSONEmptyCodec implements JSONCodec<Object> { static final JSONEmptyCodec INSTANCE = new JSONEmptyCodec(); private JSONEmptyCodec() { } @Override public Object deserialize(final String input) { return null; } @Override public String serialize(final Object input) { return null; } @Override public boolean needQuotes() { return false; } @Override public void serializeToWriter(final JsonWriter writer, final Object value) throws IOException { writer.beginArray(); writer.value((String) null); writer.endArray(); } }
/* * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the terms of the Eclipse * Public License v1.0 which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.yangtools.yang.data.codec.gson; import com.google.gson.stream.JsonWriter; import java.io.IOException; final class JSONEmptyCodec implements JSONCodec<Object> { static final JSONEmptyCodec INSTANCE = new JSONEmptyCodec(); private JSONEmptyCodec() { } @Override public Object deserialize(final String input) { return null; } @Override public String serialize(final Object input) { return null; } @Override public boolean needQuotes() { return false; } @Override public void serializeToWriter(final JsonWriter writer, final Object value) throws IOException { writer.beginArray(); writer.value((String) null); writer.endArray(); } }
Add return type and strict thing
<?php // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. declare(strict_types=1); namespace Database\Factories; use App\Models\User; use App\Models\UserAccountHistory; use Illuminate\Database\Eloquent\Factories\Factory; class UserAccountHistoryFactory extends Factory { protected $model = UserAccountHistory::class; public function definition(): array { return [ 'reason' => fn () => $this->faker->bs(), // 5 minutes (300 seconds) times 2 to the nth power (as in the standard osu silence durations) 'period' => fn () => 300 * (2 ** rand(1, 10)), 'banner_id' => fn () => User::inRandomOrder()->first(), ]; } public function note() { return $this->state(['ban_status' => 0]); } public function restriction() { return $this->state(['ban_status' => 1]); } public function silence() { return $this->state(['ban_status' => 2]); } }
<?php // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. namespace Database\Factories; use App\Models\User; use App\Models\UserAccountHistory; use Illuminate\Database\Eloquent\Factories\Factory; class UserAccountHistoryFactory extends Factory { protected $model = UserAccountHistory::class; public function definition(): array { return [ 'reason' => fn () => $this->faker->bs(), // 5 minutes (300 seconds) times 2 to the nth power (as in the standard osu silence durations) 'period' => fn () => 300 * (2 ** rand(1, 10)), 'banner_id' => fn () => User::inRandomOrder()->first(), ]; } public function note() { return $this->state(['ban_status' => 0]); } public function restriction() { return $this->state(['ban_status' => 1]); } public function silence() { return $this->state(['ban_status' => 2]); } }
Fix remarkup "NOTE" block syntax Summary: Currently, HTML in NOTE blocks gets escaped, because the "rtrim()" applies to a PhutilSafeHTML object and implicitly converts it to (unsafe) string. Instead, trim first. Test Plan: Typed `NOTE: **x**` into remarkup, saw bold "x". Reviewers: btrahan, garoevans, vrana Reviewed By: btrahan CC: aran Differential Revision: https://secure.phabricator.com/D6379
<?php /** * @group markup */ final class PhutilRemarkupEngineRemarkupNoteBlockRule extends PhutilRemarkupEngineBlockRule { public function getMatchingLineCount(array $lines, $cursor) { $num_lines = 0; if (preg_match("/^NOTE: /", $lines[$cursor])) { $num_lines++; $cursor++; while(isset($lines[$cursor])) { if (trim($lines[$cursor])) { $num_lines++; $cursor++; continue; } break; } } return $num_lines; } public function markupText($text) { $text = $this->applyRules(rtrim($text)); if ($this->getEngine()->isTextMode()) { return $text; } return phutil_tag( 'div', array( 'class' => 'remarkup-note', ), $text); } }
<?php /** * @group markup */ final class PhutilRemarkupEngineRemarkupNoteBlockRule extends PhutilRemarkupEngineBlockRule { public function getMatchingLineCount(array $lines, $cursor) { $num_lines = 0; if (preg_match("/^NOTE: /", $lines[$cursor])) { $num_lines++; $cursor++; while(isset($lines[$cursor])) { if (trim($lines[$cursor])) { $num_lines++; $cursor++; continue; } break; } } return $num_lines; } public function markupText($text) { $text = rtrim($this->applyRules($text)); if ($this->getEngine()->isTextMode()) { return $text; } return hsprintf('<div class="remarkup-note">%s</div>', $text); } }
Change release tagging convention to vX.Y.Z
from distutils.core import setup with open('README.md') as f: long_description = f.read() setup( name = 'dont_argue', packages = ['dont_argue'], version = '0.1.1', description = 'Dead-simple command line argument parsing', long_description=long_description, author = 'Chris Penner', author_email = 'christopher.penner@gmail.com', url = 'https://github.com/ChrisPenner/dont-argue', download_url = 'https://github.com/ChrisPenner/dont-argue/releases/tag/v0.1.1', license = 'MIT', keywords = ['command line', 'argument', 'parsing', 'argparse'], classifiers = [ 'Development Status :: 3 - Alpha', 'Topic :: Software Development :: Libraries', # Pick your license as you wish (should match "license" above) 'License :: OSI Approved :: MIT License', # Specify the Python versions you support here. In particular, ensure # that you indicate whether you support Python 2, Python 3 or both. 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], )
from distutils.core import setup with open('README.md') as f: long_description = f.read() setup( name = 'dont_argue', packages = ['dont_argue'], version = '0.1.1', description = 'Dead-simple command line argument parsing', long_description=long_description, author = 'Chris Penner', author_email = 'christopher.penner@gmail.com', url = 'https://github.com/ChrisPenner/dont-argue', download_url = 'https://github.com/ChrisPenner/dont-argue/releases/tag/0.1.1', license = 'MIT', keywords = ['command line', 'argument', 'parsing', 'argparse'], classifiers = [ 'Development Status :: 3 - Alpha', 'Topic :: Software Development :: Libraries', # Pick your license as you wish (should match "license" above) 'License :: OSI Approved :: MIT License', # Specify the Python versions you support here. In particular, ensure # that you indicate whether you support Python 2, Python 3 or both. 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], )
Update tests to include render template function
package framework import ( "reflect" "testing" ) func Test_getMethods_OneMethod(t *testing.T) { testType := reflect.TypeOf(TestController{}) methods := getMethods(testType) expectedLen, actualLen := 2, len(methods) if expectedLen != actualLen { t.Errorf("Expected a count of %v but got %v", expectedLen, actualLen) return } expectedMethod := "Test" actualMethod, ok := methods[expectedMethod] if ok != true { t.Errorf("Expected a method of %v but got %v", expectedMethod, actualMethod) return } } func Test_getMethods_TwoMethods(t *testing.T) { testType := reflect.TypeOf(SecondTest{}) methods := getMethods(testType) expectedLen, actualLen := 3, len(methods) if expectedLen != actualLen { t.Errorf("Expected a count of %v but got %v", expectedLen, actualLen) return } expectedMethod := "TestOne" actualMethod, ok := methods[expectedMethod] if ok != true { t.Errorf("Expected a method of %v but got %v", expectedMethod, actualMethod) return } expectedMethod = "TestTwo" actualMethod, ok = methods[expectedMethod] if ok != true { t.Errorf("Expected a method of %v but got %v", expectedMethod, actualMethod) return } }
package framework import ( "reflect" "testing" ) func Test_getMethods_OneMethod(t *testing.T) { testType := reflect.TypeOf(TestController{}) methods := getMethods(testType) expectedLen, actualLen := 1, len(methods) if expectedLen != actualLen { t.Errorf("Expected a count of %v but got %v", expectedLen, actualLen) return } expectedMethod := "Test" actualMethod, ok := methods[expectedMethod] if ok != true { t.Errorf("Expected a method of %v but got %v", expectedMethod, actualMethod) return } } func Test_getMethods_TwoMethods(t *testing.T) { testType := reflect.TypeOf(SecondTest{}) methods := getMethods(testType) expectedLen, actualLen := 2, len(methods) if expectedLen != actualLen { t.Errorf("Expected a count of %v but got %v", expectedLen, actualLen) return } expectedMethod := "TestOne" actualMethod, ok := methods[expectedMethod] if ok != true { t.Errorf("Expected a method of %v but got %v", expectedMethod, actualMethod) return } expectedMethod = "TestTwo" actualMethod, ok = methods[expectedMethod] if ok != true { t.Errorf("Expected a method of %v but got %v", expectedMethod, actualMethod) return } }
Set scope correctly with bind
var fieldRegistry = require('kwf/frontend-form/field-registry'); var Field = require('kwf/frontend-form/field/field'); var kwfExtend = require('kwf/extend'); var TextArea = kwfExtend(Field, { initField: function() { this.el.select('textarea').each((function(input) { $(input).on('keypress', function() { this.el.trigger('kwf-form-change', this.getValue()); }, this); this._initPlaceholder(input); }).bind(this)); }, getFieldName: function() { return this.el.find('textarea').get(0).name; }, getValue: function() { return this.el.find('textarea').get(0).value; }, clearValue: function() { this.el.select('textarea').get(0).value = ''; }, clearValue: function(value) { this.el.select('textarea').get(0).value = value; } }); fieldRegistry.register('kwfFormFieldTextArea', TextArea); module.exports = TextArea;
var fieldRegistry = require('kwf/frontend-form/field-registry'); var Field = require('kwf/frontend-form/field/field'); var kwfExtend = require('kwf/extend'); var TextArea = kwfExtend(Field, { initField: function() { this.el.select('textarea').each(function(input) { $(input).on('keypress', function() { this.el.trigger('kwf-form-change', this.getValue()); }, this); this._initPlaceholder(input); }, this); }, getFieldName: function() { return this.el.find('textarea').get(0).name; }, getValue: function() { return this.el.find('textarea').get(0).value; }, clearValue: function() { this.el.select('textarea').get(0).value = ''; }, clearValue: function(value) { this.el.select('textarea').get(0).value = value; } }); fieldRegistry.register('kwfFormFieldTextArea', TextArea); module.exports = TextArea;
Add access token attrib to the User Model
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var ObjectId = Schema.ObjectId; var UserSchema = new Schema({ // basic name: { type: String }, loginname: { type: String }, std_id: { type: ObjectId }, psw: { type: String }, url: { type: String }, profile_image_url: { type: String }, location: { type: String }, signature: { type: String }, is_block: { type: String }, // social intercourse account weibo: { type: String }, renren: { type: String }, wechat: { type: String }, qq: { type: Number }, email: { type: String }, github: {type: String }, // account info score: { type: Number, default: 98 }, level: { type: String }, title: { type: String }, created_at: { type: Date, default: Date.now }, updated_at: { type: Date, default: Date.now }, access_token: { type: String } }); UserSchema.virtual().get(function() { }); UserSchema.index(); mongoose.model('User', UserSchema);
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var ObjectId = Schema.ObjectId; var UserSchema = new Schema({ // basic name: { type: String }, loginname: { type: String }, std_id: { type: ObjectId }, psw: { type: String }, url: { type: String }, profile_image_url: { type: String }, location: { type: String }, signature: { type: String }, is_block: { type: String }, // social intercourse account weibo: { type: String }, renren: { type: String }, wechat: { type: String }, qq: { type: Number }, email: { type: String }, github: {type: String }, // account info score: { type: Number, default: 98 }, level: { type: String }, title: { type: String }, created_at: { type: Date, default: Date.now }, updated_at: { type: Date, default: Date.now }, }); UserSchema.virtual().get(function() { }); UserSchema.index(); mongoose.model('User', UserSchema);
Make login form template work even if form is escaped
<?php $view->extend('DoctrineUserBundle::layout') ?> <?php if ($view->session->hasFlash('doctrine_user_session_new/error')): ?> <div class="doctrine_user_session_new_error">Bad username or password, please try again.</div> <?php endif; ?> <?php echo $form->getRawValue()->renderFormTag($view->router->generate('doctrine_user_session_create'), array('class' => 'doctrine_user_session_new')) ?> <div> <label for="doctrine_user_session_new_usernameOrEmail">Username or email:</label> <?php echo $form['usernameOrEmail']->getRawValue()->render(); ?> </div> <div> <label for="doctrine_user_session_new_password">Password:</label> <?php echo $form['password']->getRawValue()->render(); ?> </div> <div> <input type="submit" value="Log in" /> </div> </form>
<?php $view->extend('DoctrineUserBundle::layout') ?> <?php if ($view->session->hasFlash('doctrine_user_session_new/error')): ?> <div class="doctrine_user_session_new_error">Bad username or password, please try again.</div> <?php endif; ?> <?php echo $form->renderFormTag($view->router->generate('doctrine_user_session_create'), array('class' => 'doctrine_user_session_new')) ?> <div> <label for="doctrine_user_session_new_usernameOrEmail">Username or email:</label> <?php echo $form['usernameOrEmail']->render(); ?> </div> <div> <label for="doctrine_user_session_new_password">Password:</label> <?php echo $form['password']->render(); ?> </div> <div> <input type="submit" value="Log in" /> </div> </form>
Analytics: Add search string to page view As we want to see which advertising channels are most effective, we want to record the query parameters.
// analytics.js CircleBlvd.Services.analytics = function ($window, $location) { // Reference: // https://developers.google.com/analytics/devguides/collection/analyticsjs/pages var trackPage = function () { if ($window.ga) { var hash = $window.location.hash; var path; if (hash.length > 0) { path = $location.path(); } else { path = $window.location.pathname; } var search = $window.location.search; if (search) { path = path + search; } $window.ga('send', 'pageview', path); } }; var trackEvent = function (category, action) { if ($window.ga) { $window.ga('send', 'event', category, action); } }; var trackError = function (status) { if ($window.ga) { $window.ga('send', 'event', 'error', status); } }; return { trackPage: trackPage, trackEvent: trackEvent, trackError: trackError }; }; CircleBlvd.Services.analytics.$inject = ['$window', '$location'];
// analytics.js CircleBlvd.Services.analytics = function ($window, $location) { // Reference: // https://developers.google.com/analytics/devguides/collection/analyticsjs/pages var trackPage = function () { if ($window.ga) { var hash = $window.location.hash; var path; if (hash.length > 0) { path = $location.path(); } else { path = $window.location.pathname; } $window.ga('send', 'pageview', path); } }; var trackEvent = function (category, action) { if ($window.ga) { $window.ga('send', 'event', category, action); } }; var trackError = function (status) { if ($window.ga) { $window.ga('send', 'event', 'error', status); } }; return { trackPage: trackPage, trackEvent: trackEvent, trackError: trackError }; }; CircleBlvd.Services.analytics.$inject = ['$window', '$location'];
Remove redundant floatval call when casting to float
<?php /** * @see https://github.com/zendframework/zend-filter for the canonical source repository * @copyright Copyright (c) 2018 Zend Technologies USA Inc. (https://www.zend.com) * @license https://github.com/zendframework/zend-filter/blob/master/LICENSE.md New BSD License */ namespace Zend\Filter; class ToFloat extends AbstractFilter { /** * Defined by Zend\Filter\FilterInterface * * Returns (float) $value * * If the value provided is non-scalar, the value will remain unfiltered * * @param mixed $value * @return float|mixed */ public function filter($value) { if (! is_scalar($value)) { return $value; } return (float) $value; } }
<?php /** * @see https://github.com/zendframework/zend-filter for the canonical source repository * @copyright Copyright (c) 2018 Zend Technologies USA Inc. (https://www.zend.com) * @license https://github.com/zendframework/zend-filter/blob/master/LICENSE.md New BSD License */ namespace Zend\Filter; class ToFloat extends AbstractFilter { /** * Defined by Zend\Filter\FilterInterface * * Returns (float) $value * * If the value provided is non-scalar, the value will remain unfiltered * * @param mixed $value * @return float|mixed */ public function filter($value) { if (! is_scalar($value)) { return $value; } return (float) floatval($value); } }
Remove noisey console.log line inside smoke tests This was added for debugging at some point, but is making the test output harder to read now.
'use strict' const expect = require('chai').expect // Components const nunjucks = require('nunjucks') const components = require('../../lib/components') // Styles const paths = require('../../config/paths.json') const sass = require('node-sass') const expectComponentRenders = (name, input) => { let componentPath = components.templatePathFor(name) expect(() => { nunjucks.render(componentPath, input) }).to.not.throw() } describe('All components variants render without errors', () => { Object.keys(components.all).map(name => { describe(`${name}`, () => { let variants = components.getVariantsFor(name) for (let variant of variants) { it(`${variant.name}`, () => { expectComponentRenders(name, variant.context) }) } }) }) }) describe('Styles', () => { it('should compile', done => { sass.render({ file: paths.bundleScss + 'govuk-frontend.scss' }, error => { expect(error).to.equal(null) done() }) }) })
'use strict' const expect = require('chai').expect // Components const nunjucks = require('nunjucks') const components = require('../../lib/components') // Styles const paths = require('../../config/paths.json') const sass = require('node-sass') const expectComponentRenders = (name, input) => { let componentPath = components.templatePathFor(name) expect(() => { nunjucks.render(componentPath, input) }).to.not.throw() } describe('All components variants render without errors', () => { Object.keys(components.all).map(name => { describe(`${name}`, () => { let variants = components.getVariantsFor(name) for (let variant of variants) { it(`${variant.name}`, () => { console.log(variant.context) expectComponentRenders(name, variant.context) }) } }) }) }) describe('Styles', () => { it('should compile', done => { sass.render({ file: paths.bundleScss + 'govuk-frontend.scss' }, error => { expect(error).to.equal(null) done() }) }) })
Fix config name error for autocloud service
# -*- coding: utf-8 -*- import ConfigParser import os PROJECT_ROOT = os.path.abspath(os.path.dirname(__name__)) name = '/etc/autocloud/autocloud.cfg' if not os.path.exists(name): raise Exception('Please add a proper cofig file under /etc/autocloud/') config = ConfigParser.RawConfigParser() config.read(name) KOJI_SERVER_URL = config.get('autocloud', 'koji_server_url') BASE_KOJI_TASK_URL = config.get('autocloud', 'base_koji_task_url') HOST = config.get('autocloud', 'host') or '127.0.0.1' PORT = int(config.get('autocloud', 'port')) or 5000 DEBUG = config.getboolean('autocloud', 'debug') SQLALCHEMY_URI = config.get('sqlalchemy', 'uri') VIRTUALBOX = config.getboolean('autocloud', 'virtualbox')
# -*- coding: utf-8 -*- import ConfigParser import os PROJECT_ROOT = os.path.abspath(os.path.dirname(__name__)) name = '/etc/autocloud/autocloud.cfg' if not os.path.exists(name): raise Exception('Please add a proper cofig file under /etc/autocloud/') config.read(name) KOJI_SERVER_URL = config.get('autocloud', 'koji_server_url') BASE_KOJI_TASK_URL = config.get('autocloud', 'base_koji_task_url') HOST = config.get('autocloud', 'host') or '127.0.0.1' PORT = int(config.get('autocloud', 'port')) or 5000 DEBUG = config.getboolean('autocloud', 'debug') SQLALCHEMY_URI = config.get('sqlalchemy', 'uri') VIRTUALBOX = config.getboolean('autocloud', 'virtualbox')
Add a suitable license classifier.
from setuptools import setup, find_packages setup( name='vumi-wikipedia', version='dev', description='Vumi Wikipedia App', packages=find_packages(), install_requires=[ 'vumi > 0.3.1', 'BeautifulSoup', ], url='http://github.com/praekelt/vumi-wikipedia', license='BSD', long_description=open('README', 'r').read(), maintainer='Praekelt Foundation', maintainer_email='dev@praekelt.com', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: POSIX', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: System :: Networking', ], )
from setuptools import setup, find_packages setup( name='vumi-wikipedia', version='dev', description='Vumi Wikipedia App', packages=find_packages(), install_requires=[ 'vumi > 0.3.1', 'BeautifulSoup', ], url='http://github.com/praekelt/vumi-wikipedia', license='BSD', long_description=open('README', 'r').read(), maintainer='Praekelt Foundation', maintainer_email='dev@praekelt.com', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Operating System :: POSIX', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: System :: Networking', ], )
Add test for projection alias
package at.lingu.sqlcompose; import at.lingu.sqlcompose.projection.Projection; import at.lingu.sqlcompose.source.Table; import org.junit.Test; /** * Tests for select statements. * * @author Florian Fankhauser <flo@lingu.at> */ public class SelectTests extends BaseSqlTests { private Table users = new Table("users"); @Test public void testSelectAllFields() { Select select = new Select(users) .project(Projection.ALL); generateResult(select); assertSql("SELECT * FROM users"); assertNoParams(); } @Test public void testSelectFields() { Select select = new Select(users) .project( users.column("id"), users.column("last_name"), users.column("first_name")); generateResult(select); assertSql("SELECT id, last_name, first_name FROM users"); assertNoParams(); } @Test public void testSelectFieldsWithAlias() { Select select = new Select(users) .project( users.column("id").as("user_id"), users.column("last_name").as("l_name"), users.column("first_name").as("f_name")); generateResult(select); assertSql("SELECT id AS user_id, last_name AS l_name, " + "first_name AS f_name FROM users"); assertNoParams(); } }
package at.lingu.sqlcompose; import at.lingu.sqlcompose.projection.Projection; import at.lingu.sqlcompose.source.Table; import org.junit.Test; /** * Tests for select statements. * * @author Florian Fankhauser <flo@lingu.at> */ public class SelectTests extends BaseSqlTests { private Table users = new Table("users"); @Test public void testSelectAllFields() { Select select = new Select(users) .project(Projection.ALL); generateResult(select); assertSql("SELECT * FROM users"); assertNoParams(); } @Test public void testSelectFields() { Select select = new Select(users) .project( users.column("id"), users.column("last_name"), users.column("first_name")); generateResult(select); assertSql("SELECT id, last_name, first_name FROM users"); assertNoParams(); } }
Change LoginForm parameter for BooleanField
from flask_wtf import Form from wtforms import StringField, PasswordField, SubmitField, RadioField, validators, IntegerField, BooleanField from wtforms.validators import DataRequired, Email, Length class AddUserForm(Form): name = StringField('Name of User', validators=[DataRequired("Please enter the name of the newcomer.")]) username= StringField('Create a Username', validators=[DataRequired("Please enter a username.")]) role = RadioField('Role of User', choices=[('attendent','Room Attendant'),('supervisor','Supervisor')],validators=[DataRequired('Input Choice')]) password = PasswordField('Password', validators=[DataRequired("Please enter a password."), Length(min=6, message="Passwords must be 6 characters or more.")]) submit = SubmitField('Add User') class LoginForm(Form): username = StringField('Username', validators=[DataRequired("Please enter a username")]) password = PasswordField('Password', validators=[DataRequired('Please enter a password')]) remember = BooleanField() submit = SubmitField("Login") class RetrievalForm(Form): amount = StringField('Input the amount taken', validators=[validators.input_required()]) submit = SubmitField("Enter Quantity")
from flask_wtf import Form from wtforms import StringField, PasswordField, SubmitField, RadioField, validators, IntegerField, BooleanField from wtforms.validators import DataRequired, Email, Length class AddUserForm(Form): name = StringField('Name of User', validators=[DataRequired("Please enter the name of the newcomer.")]) username= StringField('Create a Username', validators=[DataRequired("Please enter a username.")]) role = RadioField('Role of User', choices=[('attendent','Room Attendant'),('supervisor','Supervisor')],validators=[DataRequired('Input Choice')]) password = PasswordField('Password', validators=[DataRequired("Please enter a password."), Length(min=6, message="Passwords must be 6 characters or more.")]) submit = SubmitField('Add User') class LoginForm(Form): username = StringField('Username', validators=[DataRequired("Please enter a usename")]) password = PasswordField('Password', validators=[DataRequired('Please enter a password')]) remember = BooleanField('Remember me') submit = SubmitField("Login") class RetrievalForm(Form): amount = StringField('Input the amount taken', validators=[validators.input_required()]) submit = SubmitField("Enter Quantity")
Fix MusicBrainz Track Mapper Maping
'use strict'; // Load dependencies const _ = require('lodash'); const utils = rootRequire('criteria/utils'); /** * Composes a MusicBrainz track from the MusicBrainz API. */ class MusicBrainzTrack { // Initializer constructor(data) { this.id = data.id; this.name = data.title; this.position = data.position; } // Compute Track Criteria Score criteriaScore(mixradio_name) { const criteria_track_name = utils.stringDistance(mixradio_name, this.name); const criteria_overall = criteria_track_name; return { criteria_overall, criteria_track_name }; } }; module.exports = MusicBrainzTrack; module.exports.JSONMediaMapper = (data) => { const trackMapper = (track) => { return new MusicBrainzTrack({ id: track.id, title: track.title, position: track.number }); }; const releaseTracks = _.reduce(data.media, (tracks, media) => { const mb_tracks = _.map(media.tracks, trackMapper); return tracks.concat(mb_tracks); }, []); return releaseTracks; };
'use strict'; // Load dependencies const _ = require('lodash'); const utils = rootRequire('criteria/utils'); /** * Composes a MusicBrainz track from the MusicBrainz API. */ class MusicBrainzTrack { // Initializer constructor(data) { this.id = data.id; this.name = data.title; this.position = data.position; } // Compute Track Criteria Score criteriaScore(mixradio_name) { const criteria_track_name = utils.stringDistance(mixradio_name, this.name); const criteria_overall = criteria_track_name; return { criteria_overall, criteria_track_name }; } }; module.exports = MusicBrainzTrack; module.exports.JSONMediaMapper = (data) => { const trackMapper = (track) => { return new MusicBrainzTrack({ id: track.id, name: track.title, position: track.number }); }; const releaseTracks = _.reduce(data.media, (tracks, media) => { const mb_tracks = _.map(media.tracks, trackMapper); return tracks.concat(mb_tracks); }, []); return releaseTracks; };
Include view-only key in WaterButler URLs.
var $ = require('jquery'); var $osf = require('osfHelpers'); var settings = require('settings'); function getCookie() { match = document.cookie.match(/osf=(.*?)(;|$)/); return match ? match[1] : null; } function getViewOnly() { return $osf.urlParams().view_only; } function buildUrl(metadata, path, provider, file) { path = path || '/'; var baseUrl = settings.WATERBUTLER_URL + (metadata ? 'data?': 'file?'); if (file) { path += file.name; } return baseUrl + $.param({ path: path, token: '', nid: nodeId, provider: provider, cookie: getCookie(), viewOnly: getViewOnly() }); } function buildFromTreebeard(metadata, item, file) { return buildUrl(metadata, item.data.path, item.data.provider, file); } module.exports = { buildFileUrlFromPath: buildUrl.bind(this, false), buildFileUrl: buildFromTreebeard.bind(this, false), buildMetadataUrlFromPath: buildUrl.bind(this, true), buildMetadataUrl: buildFromTreebeard.bind(this, true), };
var $ = require('jquery'); var settings = require('settings'); function getCookie() { match = document.cookie.match(/osf=(.*?)(;|$)/); return match ? match[1] : null; } function buildUrl(metadata, path, provider, file) { path = path || '/'; var baseUrl = settings.WATERBUTLER_URL + (metadata ? 'data?': 'file?'); if (file) { path += file.name; } return baseUrl + $.param({ path: path, token: '', nid: nodeId, provider: provider, cookie: getCookie() }); } function buildFromTreebeard(metadata, item, file) { return buildUrl(metadata, item.data.path, item.data.provider, file); } module.exports = { buildFileUrlFromPath: buildUrl.bind(this, false), buildFileUrl: buildFromTreebeard.bind(this, false), buildMetadataUrlFromPath: buildUrl.bind(this, true), buildMetadataUrl: buildFromTreebeard.bind(this, true), };
Add userstats emit to disconnect
/* Created by 'myth' on July 3. 2015 CognacTime is licenced under the MIT licence. */ var log = require('./logging') var util = require('../client/util') // Start by defining the container object function iowrapper (io) { this.connections = [] this.io = io io.on('connection', function (socket) { log.info('Client connected: ' + socket.id) io.emit('stats', { users: io.engine.clientsCount }) socket.on('message', function (data) { log.info('Received message: ' + data) }) socket.on('fetch', function (data) { log.info('Received query: ' + util.repr(data)) }) socket.on('disconnect', function () { log.info('Client disconnected: ' + socket.id) io.emit('stats', { users: io.engine.clientsCount }) }) }) } module.exports = iowrapper
/* Created by 'myth' on July 3. 2015 CognacTime is licenced under the MIT licence. */ var log = require('./logging') var util = require('../client/util') // Start by defining the container object function iowrapper (io) { this.connections = [] this.io = io io.on('connection', function (socket) { log.info('Client connected: ' + socket.id) io.emit('stats', { users: io.engine.clientsCount }) socket.on('message', function (data) { log.info('Received message: ' + data) }) socket.on('fetch', function (data) { log.info('Received query: ' + util.repr(data)) }) socket.on('disconnect', function () { log.info('Client disconnected: ' + socket.id) }) }) } module.exports = iowrapper
Adjust test file to match new env config options
import bookmarks import unittest class FlaskrTestCase(unittest.TestCase): def setUp(self): self.app = bookmarks.app.test_client() with bookmarks.app.app_context(): bookmarks.database.init_db() def tearDown(self): with bookmarks.app.app_context(): bookmarks.database.db_session.remove() bookmarks.database.Base.metadata.drop_all( bind=bookmarks.database.engine) def test_empty_db(self): rv = self.app.get('/') assert b'There aren\'t any bookmarks yet.' in rv.data if __name__ == '__main__': unittest.main()
import bookmarks import unittest class FlaskrTestCase(unittest.TestCase): def setUp(self): bookmarks.app.config['DATABASE_NAME'] = bookmarks.app.config['TEST_DATABASE_NAME'] bookmarks.app.testing = True self.app = bookmarks.app.test_client() with bookmarks.app.app_context(): bookmarks.database.init_db() # def tearDown(self): # os.close(self.db_fd) # os.unlink(bookmarks.app.config['DATABASE']) def test_empty_db(self): rv = self.app.get('/') assert b'There aren\'t any bookmarks yet.' in rv.data if __name__ == '__main__': unittest.main()
Add missing attributes in TPSProcessor. Signed-off-by: shanks <4508bc7244505cbe28c7ec6ff0c99c8246ca3de6@redhat.com>
# Copyright (C) 2017 Red Hat, Inc. # # fedmsg_meta_umb is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # fedmsg_meta_umb 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with fedmsg; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Authors: Gowrishankar Rajaiyan <grajaiya@redhat.com> from fedmsg.meta.base import BaseProcessor class TPSProcessor(BaseProcessor): topic_prefix_re = r'/topic/VirtualTopic\.eng' __name__ = 'tps' __description__ = 'package sanity testing of brew builds' __obj__ = 'Test Package Sanity' __docs__ = 'https://mojo.redhat.com/docs/DOC-0000000' __link__ = 'https://sometpslink.engineering.redhat.com' def title(self, msg, **config): return msg['topic'].split('.', 2)[-1] def packages(self, msg, **config): return set([msg['headers']['component'].rsplit('-', 2)[0]])
# Copyright (C) 2017 Red Hat, Inc. # # fedmsg_meta_umb is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # fedmsg_meta_umb 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with fedmsg; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Authors: Gowrishankar Rajaiyan <grajaiya@redhat.com> from fedmsg.meta.base import BaseProcessor class TPSProcessor(BaseProcessor): topic_prefix_re = r'/topic/VirtualTopic\.eng' __name__ = 'tps' def title(self, msg, **config): return msg['topic'].split('.', 2)[-1] def packages(self, msg, **config): return set([msg['headers']['component'].rsplit('-', 2)[0]])
Fix serialization issue for oxRegistration class
/* * oxTrust is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text. * * Copyright (c) 2014, Gluu */ /** * */ package org.gluu.oxtrust.model; import java.io.Serializable; import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; /** * @author "Oleksiy Tataryn" * */ @JsonIgnoreProperties(ignoreUnknown = true) public class RegistrationConfiguration implements Serializable { /** * */ private static final long serialVersionUID = -7310064771467874959L; /** * */ private List<String> additionalAttributes; private boolean isCaptchaDisabled; public List<String> getAdditionalAttributes() { return additionalAttributes; } public void setAdditionalAttributes(List<String> additionalAttributes) { this.additionalAttributes = additionalAttributes; } public boolean isCaptchaDisabled() { return isCaptchaDisabled; } public void setCaptchaDisabled(boolean captchaDisabled) { isCaptchaDisabled = captchaDisabled; } }
/* * oxTrust is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text. * * Copyright (c) 2014, Gluu */ /** * */ package org.gluu.oxtrust.model; import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; /** * @author "Oleksiy Tataryn" * */ @JsonIgnoreProperties(ignoreUnknown = true) public class RegistrationConfiguration { private List<String> additionalAttributes; private boolean isCaptchaDisabled; public List<String> getAdditionalAttributes() { return additionalAttributes; } public void setAdditionalAttributes(List<String> additionalAttributes) { this.additionalAttributes = additionalAttributes; } public boolean isCaptchaDisabled() { return isCaptchaDisabled; } public void setCaptchaDisabled(boolean captchaDisabled) { isCaptchaDisabled = captchaDisabled; } }
ENH: Add note to docstring of `figure` and `figsize`.
import matplotlib.pyplot as plt __all__ = ['figure', 'figsize'] def figure(aspect_ratio=1.3, scale=1, width=None, *args, **kwargs): """Return matplotlib figure window. Calculate figure height using `aspect_ratio` and *default* figure width. Parameters ---------- aspect_ratio : float Aspect ratio, width / height, of figure. scale : float Scale default size of the figure. width : float Figure width in inches. If None, default to rc parameters. See Also -------- figsize """ assert 'figsize' not in kwargs size = figsize(aspect_ratio=aspect_ratio, scale=scale, width=width) return plt.figure(figsize=size, *args, **kwargs) def figsize(aspect_ratio=1.3, scale=1, width=None): """Return figure size (width, height) in inches. Calculate figure height using `aspect_ratio` and *default* figure width. Parameters ---------- aspect_ratio : float Aspect ratio, width / height, of figure. scale : float Scale default size of the figure. width : float Figure width in inches. If None, default to rc parameters. """ if width is None: width, h = plt.rcParams['figure.figsize'] height = width / aspect_ratio size = (width * scale, height * scale) return size
import matplotlib.pyplot as plt __all__ = ['figure', 'figsize'] def figure(aspect_ratio=1.3, scale=1, width=None, *args, **kwargs): """Return matplotlib figure window. Parameters ---------- aspect_ratio : float Aspect ratio, width / height, of figure. scale : float Scale default size of the figure. width : float Figure width in inches. If None, default to rc parameters. See Also -------- figsize """ assert 'figsize' not in kwargs size = figsize(aspect_ratio=aspect_ratio, scale=scale, width=width) return plt.figure(figsize=size, *args, **kwargs) def figsize(aspect_ratio=1.3, scale=1, width=None): """Return figure size (width, height) in inches. Parameters ---------- aspect_ratio : float Aspect ratio, width / height, of figure. scale : float Scale default size of the figure. width : float Figure width in inches. If None, default to rc parameters. """ if width is None: width, h = plt.rcParams['figure.figsize'] height = width / aspect_ratio size = (width * scale, height * scale) return size
Switch to using require_http_methods decorator.
from decorator_plus import require_http_methods from django.shortcuts import ( get_object_or_404, redirect, render) from .forms import ExampleForm from .models import ExampleModel @require_http_methods(['GET']) def model_detail(request, *args, **kwargs): request_slug = kwargs.get('slug') example_obj = get_object_or_404( ExampleModel, slug=request_slug) return render( request, 'viewsapp/detail.html', {'object': example_obj}) @require_http_methods(['GET', 'POST']) def model_create(request, *args, **kwargs): if request.method == 'POST': form = ExampleForm(request.POST) if form.is_valid(): new_obj = form.save() return redirect(new_obj) else: form = ExampleForm() return render( request, 'viewsapp/form.html', {'form': form})
from decorator_plus import ( require_form_methods, require_safe_methods) from django.shortcuts import ( get_object_or_404, redirect, render) from .forms import ExampleForm from .models import ExampleModel @require_safe_methods def model_detail(request, *args, **kwargs): request_slug = kwargs.get('slug') example_obj = get_object_or_404( ExampleModel, slug=request_slug) return render( request, 'viewsapp/detail.html', {'object': example_obj}) @require_form_methods def model_create(request, *args, **kwargs): if request.method == 'POST': form = ExampleForm(request.POST) if form.is_valid(): new_obj = form.save() return redirect(new_obj) else: form = ExampleForm() return render( request, 'viewsapp/form.html', {'form': form})
Add delete test and truncate intg table when done.
<?php include_once(dirname(__FILE__).'/../../connector.php'); include_once(dirname(__FILE__).'/../../dataitem.php'); class Metrodb_Tests_Integration_Dataitem extends PHPUnit_Framework_TestCase { public function setUp() { Metrodb_Connector::setDsn('default', 'mysql://docker:mysql@192.168.2.65:3309/metrodb_test'); } public function test_save_new_dataitem() { $di = new Metrodb_Dataitem('foo', 'foo_bar'); $di->column1 = 'value_a'; $x = $di->save(); $this->assertFalse(!$x); $finder = new Metrodb_Dataitem('foo', 'foo_bar'); $finder->andWhere('column1', 'value_a'); $listAnswer = $finder->findAsArray(); $this->assertEquals('value_a', $listAnswer[0]['column1']); } public function test_delete_dataitem() { $di = new Metrodb_Dataitem('foo', 'foo_bar'); $di->column1 = 'value_a'; $x = $di->save(); $this->assertFalse(!$x); $di->delete(); $finder = new Metrodb_Dataitem('foo', 'foo_bar'); $finder->andWhere('column1', 'value_a'); $listAnswer = $finder->findAsArray(); $this->assertEquals(0, count($listAnswer)); } public function tearDown() { $db = Metrodb_Connector::getHandle('default'); $db->execute('TRUNCATE `foo`'); } }
<?php include_once(dirname(__FILE__).'/../../connector.php'); include_once(dirname(__FILE__).'/../../dataitem.php'); class Metrodb_Tests_Integration_Dataitem extends PHPUnit_Framework_TestCase { public function setUp() { Metrodb_Connector::setDsn('default', 'mysql://root:mysql@localhost/metrodb_test'); } public function test_save_new_dataitem() { $di = new Metrodb_Dataitem('foo', 'foo_bar'); $di->column1 = 'value_a'; $x = $di->save(); $this->assertFalse(!$x); $finder = new Metrodb_Dataitem('foo', 'foo_bar'); $finder->andWhere('column1', 'value_a'); $listAnswer = $finder->findAsArray(); $this->assertEquals('value_a', $listAnswer[0]['column1']); } }
Replace any kind of line break (LF, CRLF or CR) instead of relying on platform specific PHP_EOL
<?php namespace Codesleeve\AssetPipeline\Filters; use Assetic\Asset\AssetInterface; use Assetic\Filter\FilterInterface; class JST extends FilterHelper implements FilterInterface { public function __construct($basePath = '/app/assets/javascripts/') { $this->basePath = $basePath; } public function filterLoad(AssetInterface $asset) { // do nothing when asset is loaded } public function filterDump(AssetInterface $asset) { $relativePath = $this->getRelativePath($this->basePath, $asset->getSourceRoot() . '/'); $filename = pathinfo($asset->getSourcePath(), PATHINFO_FILENAME); $content = str_replace('"', '\\"', $asset->getContent()); $content = preg_replace("/[\r?\n]+/", "", $content); $jst = 'JST = (typeof JST === "undefined") ? JST = {} : JST;' . PHP_EOL; $jst .= 'JST["' . $relativePath . $filename . '"] = "'; $jst .= $content; $jst .= '";' . PHP_EOL; $asset->setContent($jst); } }
<?php namespace Codesleeve\AssetPipeline\Filters; use Assetic\Asset\AssetInterface; use Assetic\Filter\FilterInterface; class JST extends FilterHelper implements FilterInterface { public function __construct($basePath = '/app/assets/javascripts/') { $this->basePath = $basePath; } public function filterLoad(AssetInterface $asset) { // do nothing when asset is loaded } public function filterDump(AssetInterface $asset) { $relativePath = $this->getRelativePath($this->basePath, $asset->getSourceRoot() . '/'); $filename = pathinfo($asset->getSourcePath(), PATHINFO_FILENAME); $content = str_replace('"', '\\"', $asset->getContent()); $content = str_replace(PHP_EOL, "", $content); $jst = 'JST = (typeof JST === "undefined") ? JST = {} : JST;' . PHP_EOL; $jst .= 'JST["' . $relativePath . $filename . '"] = "'; $jst .= $content; $jst .= '";' . PHP_EOL; $asset->setContent($jst); } }
Fix redirect loops in HTTPS when canonical-base-uri is configured Once again, we're hit by RESTEASY-1099; this time when comparing the base URI with the expected "canonical base URI". When the requested URI had a query-string, the comparison failed and we tried to redirect to actually the exact same URI as result. Change-Id: If4ec9832f98b79ef6c3a9a8a9c2b0ca258b3debd
package oasis.web.authn; import java.io.IOException; import java.net.URI; import javax.annotation.Priority; import javax.inject.Inject; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.core.Response; import javax.ws.rs.ext.Provider; import oasis.urls.Urls; import oasis.web.resteasy.Resteasy1099; /** * Enforce the use of the {@link oasis.urls.Urls#canonicalBaseUri() canonical base URI} * for cookie-based authentication. */ @User @Provider @Priority(0) public class UserCanonicalBaseUriFilter implements ContainerRequestFilter { @Inject Urls urls; @Override public void filter(ContainerRequestContext requestContext) throws IOException { if (!urls.canonicalBaseUri().isPresent()) { return; // nothing to do } if (Resteasy1099.getBaseUri(requestContext.getUriInfo()).equals(urls.canonicalBaseUri().get())) { return; // we're already on the canonical base URI } URI relativeUri = Resteasy1099.getBaseUri(requestContext.getUriInfo()).relativize(requestContext.getUriInfo().getRequestUri()); URI canonicalUri = urls.canonicalBaseUri().get().resolve(relativeUri); requestContext.abortWith(Response.status(Response.Status.MOVED_PERMANENTLY) .location(canonicalUri) .build()); } }
package oasis.web.authn; import java.io.IOException; import java.net.URI; import javax.annotation.Priority; import javax.inject.Inject; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.core.Response; import javax.ws.rs.ext.Provider; import oasis.urls.Urls; import oasis.web.resteasy.Resteasy1099; /** * Enforce the use of the {@link oasis.urls.Urls#canonicalBaseUri() canonical base URI} * for cookie-based authentication. */ @User @Provider @Priority(0) public class UserCanonicalBaseUriFilter implements ContainerRequestFilter { @Inject Urls urls; @Override public void filter(ContainerRequestContext requestContext) throws IOException { if (!urls.canonicalBaseUri().isPresent()) { return; // nothing to do } if (requestContext.getUriInfo().getBaseUri().equals(urls.canonicalBaseUri().get())) { return; // we're already on the canonical base URI } URI relativeUri = Resteasy1099.getBaseUri(requestContext.getUriInfo()).relativize(requestContext.getUriInfo().getRequestUri()); URI canonicalUri = urls.canonicalBaseUri().get().resolve(relativeUri); requestContext.abortWith(Response.status(Response.Status.MOVED_PERMANENTLY) .location(canonicalUri) .build()); } }
Make it possible to switch targets
(function(document, housewarming){ var playground = document.getElementById('playground'); playground.width = document.body.clientWidth; playground.height = document.body.clientHeight; var options = { distance: 20, couple: { x: 3*playground.width/4, y: playground.height/2, src: 'image/robin-marloes-small.jpg' }, background: { color: 'rgba(0,0,0,0.1)'}, house: { x: playground.width/4, y: playground.height/2, size: 40, color: 'green', featuresColor: 'brown' } }; var game = new housewarming.Game(options); new housewarming.View(game, playground, options); var target = 'couple'; function mousemoveHandler(event){ game[target].placeAt(event.x, event.y); } game.on('finished', function(){ document.body.removeEventListener('mousemove', mousemoveHandler); var p = document.createElement('p'); p.innerHTML = 'Congratulations'; p.setAttribute('class', 'winning'); document.body.appendChild(p); }); var go = document.getElementById('go'); go.addEventListener('click', function(){ document.body.removeChild(go); document.body.addEventListener('mousemove', mousemoveHandler); }); })(document, housewarming);
(function(document, housewarming){ var playground = document.getElementById('playground'); playground.width = document.body.clientWidth; playground.height = document.body.clientHeight; var options = { distance: 20, couple: { x: 3*playground.width/4, y: playground.height/2, src: 'image/robin-marloes-small.jpg' }, background: { color: 'rgba(0,0,0,0.1)'}, house: { x: playground.width/4, y: playground.height/2, size: 40, color: 'green', featuresColor: 'brown' } }; var game = new housewarming.Game(options); new housewarming.View(game, playground, options); function mousemoveHandler(event){ game.couple.placeAt(event.x, event.y); } game.on('finished', function(){ document.body.removeEventListener('mousemove', mousemoveHandler); var p = document.createElement('p'); p.innerHTML = 'Congratulations'; p.setAttribute('class', 'winning'); document.body.appendChild(p); }); var go = document.getElementById('go'); go.addEventListener('click', function(){ document.body.removeChild(go); document.body.addEventListener('mousemove', mousemoveHandler); }); })(document, housewarming);
Resolve erro squid:S1132 no Sonar
package br.gov.servicos.foundation.http; import lombok.experimental.FieldDefaults; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import static java.util.Arrays.stream; import static java.util.Optional.ofNullable; import static lombok.AccessLevel.PRIVATE; @Component @FieldDefaults(level = PRIVATE, makeFinal = true) class Cookies { HttpServletRequest httpServletRequest; @Autowired Cookies(HttpServletRequest httpServletRequest) { this.httpServletRequest = httpServletRequest; } public boolean isOn(String nome) { return stream(ofNullable(httpServletRequest.getCookies()).orElse(new Cookie[0])) .filter(c -> nome.equals(c.getName())) .filter(c -> "on".equals(c.getValue())) .findAny().isPresent(); } }
package br.gov.servicos.foundation.http; import lombok.experimental.FieldDefaults; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import static java.util.Arrays.stream; import static java.util.Optional.ofNullable; import static lombok.AccessLevel.PRIVATE; @Component @FieldDefaults(level = PRIVATE, makeFinal = true) class Cookies { HttpServletRequest httpServletRequest; @Autowired Cookies(HttpServletRequest httpServletRequest) { this.httpServletRequest = httpServletRequest; } public boolean isOn(String nome) { return stream(ofNullable(httpServletRequest.getCookies()).orElse(new Cookie[0])) .filter(c -> c.getName().equals(nome)) .filter(c -> c.getValue().equals("on")) .findAny().isPresent(); } }
Fix download and upload on local commander
<?php /* * This file is part of the Yodler package. * * (c) aes3xs <aes3xs@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Aes3xs\Yodler\Commander; use Aes3xs\Yodler\Common\ProcessFactory; use Symfony\Component\Filesystem\Filesystem; class LocalCommander implements CommanderInterface { const TIMEOUT = 300; protected $filesystem; protected $processFactory; public function __construct(Filesystem $filesystem, ProcessFactory $processFactory) { $this->filesystem = $filesystem; $this->processFactory = $processFactory; } /** * {@inheritdoc} */ public function exec($command) { $process = $this->processFactory->create($command); $process->setTimeout(self::TIMEOUT); $process->setIdleTimeout(self::TIMEOUT); $process->mustRun(); return $process->getOutput(); } /** * {@inheritdoc} */ public function send($local, $remote) { $this->filesystem->copy($local, $remote, true); } /** * {@inheritdoc} */ public function recv($remote, $local) { $this->filesystem->copy($remote, $local, true); } }
<?php /* * This file is part of the Yodler package. * * (c) aes3xs <aes3xs@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Aes3xs\Yodler\Commander; use Aes3xs\Yodler\Common\ProcessFactory; use Symfony\Component\Filesystem\Filesystem; class LocalCommander implements CommanderInterface { const TIMEOUT = 300; protected $filesystem; protected $processFactory; public function __construct(Filesystem $filesystem, ProcessFactory $processFactory) { $this->filesystem = $filesystem; $this->processFactory = $processFactory; } /** * {@inheritdoc} */ public function exec($command) { $process = $this->processFactory->create($command); $process->setTimeout(self::TIMEOUT); $process->setIdleTimeout(self::TIMEOUT); $process->mustRun(); return $process->getOutput(); } /** * {@inheritdoc} */ public function send($local, $remote) { $this->filesystem->copy($local, $remote); } /** * {@inheritdoc} */ public function recv($remote, $local) { $this->filesystem->copy($remote, $local); } }
Allow matching of email in the details
<?php class SV_ContactUsThread_XenForo_Model_SpamPrevention extends XFCP_SV_ContactUsThread_XenForo_Model_SpamPrevention { public function getUserLogsByIpOrEmail($ip, $email, $days, $limit = 5) { $ip = XenForo_Helper_Ip::convertIpStringToBinary($ip); $date = XenForo_Application::$time - ($days * 86400); return $this->fetchAllKeyed( $this->limitQueryResults( "SELECT log.*, user.* FROM xf_spam_trigger_log AS log LEFT JOIN xf_user AS user ON (log.user_id = user.user_id) WHERE log.content_type = 'user' AND log.log_date > ? AND (log.ip_address = ? OR user.email = ? OR log.details like ?) ORDER BY log.log_date DESC", $limit ), 'trigger_log_id', array($date, $ip, $email, '%'.$email.'%') ); } }
<?php class SV_ContactUsThread_XenForo_Model_SpamPrevention extends XFCP_SV_ContactUsThread_XenForo_Model_SpamPrevention { public function getUserLogsByIpOrEmail($ip, $email, $days, $limit = 5) { $ip = XenForo_Helper_Ip::convertIpStringToBinary($ip); $date = XenForo_Application::$time - ($days * 86400); return $this->fetchAllKeyed( $this->limitQueryResults( "SELECT log.*, user.* FROM xf_spam_trigger_log AS log LEFT JOIN xf_user AS user ON (log.user_id = user.user_id) WHERE log.content_type = 'user' AND log.log_date > ? AND (log.ip_address = ? OR user.email = ?) ORDER BY log.log_date DESC", $limit ), 'trigger_log_id', array($date, $ip, $email) ); } }
Set focus on the dropdown for category popover
<section id="main"> <section> <h3><?= t('Change category for the task "%s"', $values['title']) ?></h3> <form method="post" action="<?= $this->url->href('board', 'updateCategory', array('task_id' => $values['id'], 'project_id' => $values['project_id'])) ?>"> <?= $this->form->csrf() ?> <?= $this->form->hidden('id', $values) ?> <?= $this->form->hidden('project_id', $values) ?> <?= $this->form->label(t('Category'), 'category_id') ?> <?= $this->form->select('category_id', $categories_list, $values, array(), array('autofocus')) ?><br/> <div class="form-actions"> <input type="submit" value="<?= t('Save') ?>" class="btn btn-blue"/> <?= t('or') ?> <?= $this->url->link(t('cancel'), 'board', 'show', array('project_id' => $project['id']), false, 'close-popover') ?> </div> </form> </section> </section>
<section id="main"> <section> <h3><?= t('Change category for the task "%s"', $values['title']) ?></h3> <form method="post" action="<?= $this->url->href('board', 'updateCategory', array('task_id' => $values['id'], 'project_id' => $values['project_id'])) ?>"> <?= $this->form->csrf() ?> <?= $this->form->hidden('id', $values) ?> <?= $this->form->hidden('project_id', $values) ?> <?= $this->form->label(t('Category'), 'category_id') ?> <?= $this->form->select('category_id', $categories_list, $values) ?><br/> <div class="form-actions"> <input type="submit" value="<?= t('Save') ?>" class="btn btn-blue"/> <?= t('or') ?> <?= $this->url->link(t('cancel'), 'board', 'show', array('project_id' => $project['id']), false, 'close-popover') ?> </div> </form> </section> </section>
Handle 'id' as primary key with PostgreSQL
<?php defined('SYSPATH') or die('No direct access allowed.'); $dbpath = getenv('DBPATH'); $dbhost = getenv('DBHOST'); $dbname = getenv('DBNAME'); $dbuser = getenv('DBUSER'); $dbpass = getenv('DBPASS'); return array( 'mysql' => array( 'type' => 'pdo', 'connection' => array( 'dsn' => "mysql:host=$dbhost;dbname=$dbname", 'username' => $dbuser, 'password' => $dbpass, ), 'charset' => 'utf8', ), 'pgsql' => array( 'type' => 'postgresql', 'connection' => array( 'hostname' => $dbhost, 'username' => $dbuser, 'password' => $dbpass, 'database' => $dbname, ), 'primary_key' => 'id', 'charset' => 'utf8', ), 'sqlite' => array( 'type' => 'pdo', 'connection' => array( 'dsn' => "sqlite:$dbpath", ), ), );
<?php defined('SYSPATH') or die('No direct access allowed.'); $dbpath = getenv('DBPATH'); $dbhost = getenv('DBHOST'); $dbname = getenv('DBNAME'); $dbuser = getenv('DBUSER'); $dbpass = getenv('DBPASS'); return array( 'mysql' => array( 'type' => 'pdo', 'connection' => array( 'dsn' => "mysql:host=$dbhost;dbname=$dbname", 'username' => $dbuser, 'password' => $dbpass, ), 'charset' => 'utf8', ), 'pgsql' => array( 'type' => 'postgresql', 'connection' => array( 'hostname' => $dbhost, 'username' => $dbuser, 'password' => $dbpass, 'database' => $dbname, ), 'charset' => 'utf8', ), 'sqlite' => array( 'type' => 'pdo', 'connection' => array( 'dsn' => "sqlite:$dbpath", ), ), );
Remove square brackets around log level in log ouput
import config import logging import logging.handlers # ######### Set up logging ########## # log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG) logger = logging.getLogger('bb_log') logger.setLevel(logging.DEBUG) # create file handler which logs even debug messages tfh = logging.handlers.TimedRotatingFileHandler(str.format('{0}/app.log', config.log_directory), when='midnight', delay=False, encoding=None, backupCount=7) tfh.setLevel(logging.DEBUG) # create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # create formatter and add it to the handlers formatterch = logging.Formatter('%(asctime)s %(levelname)s %(message)s') formattertfh = logging.Formatter('%(asctime)s %(levelname)s [%(name)s] %(message)s') ch.setFormatter(formatterch) tfh.setFormatter(formattertfh) # add the handlers to logger logger.addHandler(ch) logger.addHandler(tfh)
import config import logging import logging.handlers # ######### Set up logging ########## # log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG) logger = logging.getLogger('bb_log') logger.setLevel(logging.DEBUG) # create file handler which logs even debug messages tfh = logging.handlers.TimedRotatingFileHandler(str.format('{0}/app.log', config.log_directory), when='midnight', delay=False, encoding=None, backupCount=7) tfh.setLevel(logging.DEBUG) # create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # create formatter and add it to the handlers formatterch = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s') formattertfh = logging.Formatter('%(asctime)s [%(levelname)s] [%(name)s] %(message)s') ch.setFormatter(formatterch) tfh.setFormatter(formattertfh) # add the handlers to logger logger.addHandler(ch) logger.addHandler(tfh)
Add skeleton for enqueuing scripts
<?php class Scrivener { private static $_instance; /** * Setup singleton Scrivener instance * * @since 0.1.0 * @uses add_filter, add_action * @return void */ private function __construct() { add_filter( 'preview_post_link', array( $this, 'filter_preview_post_link' ) ); add_action( 'admin_enqueue_scripts', array( $this, 'action_admin_enqueue_scripts' ) ); } /** * Enqueue admin scripts for plugin * * @param string $hook * @since 0.1.0 * @uses wp_enqueue_script * @return void */ public function action_admin_enqueue_scripts( $hook ) { if ( 'post.php' != $hook && 'post-new.php' != $hook ) return; //wp_enqueue_script(); } /** * Filter preview post link * * @param string $link * @since 0.1.0 * @uses admin_url * @return string */ public function filter_preview_post_link( $link ) { global $post; return admin_url( 'admin-post.php?action=weiverp&p=' . $post->ID ); } /** * Initialize class and return an instance of it * * @since 0.1.0 * @return Scrivener */ public function init() { if ( ! isset( self::$_instance ) ) { self::$_instance = new Scrivener; } return self::$_instance; } } Scrivener::init();
<?php class Scrivener { private static $_instance; /** * Setup singleton Scrivener instance * * @since 0.1.0 * @uses add_filter * @return void */ private function __construct() { add_filter( 'preview_post_link', array( $this, 'filter_preview_post_link' ) ); } /** * Filter preview post link * * @param string $link * @since 0.1.0 * @uses admin_url * @return string */ public function filter_preview_post_link( $link ) { global $post; return admin_url( 'admin-post.php?action=weiverp&p=' . $post->ID ); } /** * Initialize class and return an instance of it * * @since 0.1.0 * @return Scrivener */ public function init() { if ( ! isset( self::$_instance ) ) { self::$_instance = new Scrivener; } return self::$_instance; } } Scrivener::init();
Use inline source map for dev mode
var _ = require('lodash'); var path = require('path'); var webpack = require('webpack'); var getWebpackConfig = require('./webpack.config.js'); var devConfig = _.assign(getWebpackConfig(), { devtool: 'inline-source-map', output: { path: path.join(__dirname, '/app/'), // Specify complete path to force // chrome/FF load the images publicPath: 'http://localhost:3000/app/', filename: '[name].js' } }); _.keysIn(devConfig.entry).forEach(function(key) { var currentValue = devConfig.entry[key]; devConfig.entry[key] = currentValue.concat( 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server' ); }); devConfig.module.loaders.forEach(function(loaderDef) { if (loaderDef.test.toString().indexOf('.js') > 0) { loaderDef.loader = 'react-hot!' + loaderDef.loader; } }); devConfig.plugins = devConfig.plugins.concat( new webpack.DefinePlugin({ DEBUG: true }), new webpack.NoErrorsPlugin() ); module.exports = devConfig;
var _ = require('lodash'); var path = require('path'); var webpack = require('webpack'); var getWebpackConfig = require('./webpack.config.js'); var devConfig = _.assign(getWebpackConfig(), { devtool: 'eval', output: { path: path.join(__dirname, '/app/'), // Specify complete path to force // chrome/FF load the images publicPath: 'http://localhost:3000/app/', filename: '[name].js' } }); _.keysIn(devConfig.entry).forEach(function(key) { var currentValue = devConfig.entry[key]; devConfig.entry[key] = currentValue.concat( 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server' ); }); devConfig.module.loaders.forEach(function(loaderDef) { if (loaderDef.test.toString().indexOf('.js') > 0) { loaderDef.loader = 'react-hot!' + loaderDef.loader; } }); devConfig.plugins = devConfig.plugins.concat( new webpack.DefinePlugin({ DEBUG: true }), new webpack.NoErrorsPlugin() ); module.exports = devConfig;
Use config to build paths
/** * Copyright (c) 2013-2015 Memba Sarl. All rights reserved. * Sources at https://github.com/Memba */ /* jshint node: true, expr: true */ /* globals describe: false, before: false, it: false */ 'use strict'; var request = require('supertest'), util= require('util'), //We cannot define app like this because the server is already running //app = request('../../../webapp/server'); config = require('../../../webapp/config'), app = config.get('uris:webapp:root'); describe('routes/sitemapRoute', function() { it('it should return an english sitemap', function(done) { request(app) .get(util.format(config.get('uris:webapp:sitemap'), 'en')) .expect(200) .expect('Content-Type', /xml/) .end(done); }); it('it should return a french sitemap', function(done) { request(app) .get(util.format(config.get('uris:webapp:sitemap'), 'fr')) .expect(200) .expect('Content-Type', /xml/) .end(done); }); });
/** * Copyright (c) 2013-2015 Memba Sarl. All rights reserved. * Sources at https://github.com/Memba */ /* jshint node: true, expr: true */ /* globals describe: false, before: false, it: false */ 'use strict'; var request = require('supertest'), //We cannot define app like this because the server is already running //app = request('../../../webapp/server'); config = require('../../../webapp/config'), app = config.get('uris:webapp:root'); describe('routes/sitemapRoute', function() { it('it should return an english sitemap', function(done) { request(app) .get('/en/sitemap.xml') .expect(200) .expect('Content-Type', /xml/) .end(done); }); it('it should return a french sitemap', function(done) { request(app) .get('/fr/sitemap.xml') .expect(200) .expect('Content-Type', /xml/) .end(done); }); });
Fix the order of parameters for assert.equals()
var assert = require('assert'); var seeds = require('../seeds'); var Feature = require('../feature'); describe('Feature', function () { before(function (done) { seeds(done); }); describe('schema', function () { it('successfully creates a valid document'); it('fails at creating an invalid document'); }); describe('.search()', function () { it('performs an empty search, returning all commands', function (done) { Feature.search('', function (docs) { assert.equal(docs.length, 7); done(); }); }); it('performs a case-insensitive search for a command', function (done) { Feature.search('git ADD', function (docs) { assert.equal(docs.length, 1); var doc = docs[0]; assert.equal(doc.name, 'add files'); assert.deepEqual(doc.examples, { Git: 'git add', Mercurial: 'hg add', Subversion: 'svn add' }); done(); }); }); it('discards extra hidden fields created by MongoDB'); it('performs a search for a command that does not exist', function (done) { Feature.search('git yolo', function (docs) { assert.equal(docs.length, 0); done(); }); }); }); });
var assert = require('assert'); var seeds = require('../seeds'); var Feature = require('../feature'); describe('Feature', function () { before(function (done) { seeds(done); }); describe('schema', function () { it('successfully creates a valid document'); it('fails at creating an invalid document'); }); describe('.search()', function () { it('performs an empty search, returning all commands', function (done) { Feature.search('', function (docs) { assert.equal(7, docs.length); done(); }); }); it('performs a case-insensitive search for a command', function (done) { Feature.search('git ADD', function (docs) { assert.equal(1, docs.length); var doc = docs[0]; assert.equal('add files', doc.name); assert.deepEqual({ Git: 'git add', Mercurial: 'hg add', Subversion: 'svn add' }, doc.examples); done(); }); }); it('discards extra hidden fields created by MongoDB'); it('performs a search for a command that does not exist', function (done) { Feature.search('git yolo', function (docs) { assert.equal(0, docs.length); done(); }); }); }); });
Use the JUnit reporter on Circle
import {createRunner} from 'atom-mocha-test-runner'; import chai from 'chai'; import chaiAsPromised from 'chai-as-promised'; import path from 'path'; import until from 'test-until'; chai.use(chaiAsPromised); global.assert = chai.assert; global.stress = function(count, ...args) { const [description, ...rest] = args; for (let i = 0; i < count; i++) { it.only(`${description} #${i}`, ...rest); } }; // Give tests that rely on filesystem event delivery lots of breathing room. until.setDefaultTimeout(parseInt(process.env.UNTIL_TIMEOUT || '3000', 10)); module.exports = createRunner({ htmlTitle: `GitHub Package Tests - pid ${process.pid}`, reporter: process.env.MOCHA_REPORTER || 'spec', overrideTestPaths: [/spec$/, /test/], }, mocha => { mocha.timeout(parseInt(process.env.MOCHA_TIMEOUT || '5000', 10)); if (process.env.APPVEYOR_API_URL) { mocha.reporter(require('mocha-appveyor-reporter')); } if (process.env.CIRCLECI === 'true') { mocha.reporter(require('mocha-junit-reporter'), { mochaFile: path.join(process.env.CIRCLE_TEST_REPORTS, 'mocha', 'test-results.xml'), }); } });
import {createRunner} from 'atom-mocha-test-runner'; import chai from 'chai'; import chaiAsPromised from 'chai-as-promised'; import until from 'test-until'; chai.use(chaiAsPromised); global.assert = chai.assert; global.stress = function(count, ...args) { const [description, ...rest] = args; for (let i = 0; i < count; i++) { it.only(`${description} #${i}`, ...rest); } }; // Give tests that rely on filesystem event delivery lots of breathing room. until.setDefaultTimeout(parseInt(process.env.UNTIL_TIMEOUT || '3000', 10)); module.exports = createRunner({ htmlTitle: `GitHub Package Tests - pid ${process.pid}`, reporter: process.env.MOCHA_REPORTER || 'spec', overrideTestPaths: [/spec$/, /test/], }, mocha => { mocha.timeout(parseInt(process.env.MOCHA_TIMEOUT || '5000', 10)); if (process.env.APPVEYOR_API_URL) { mocha.reporter(require('mocha-appveyor-reporter')); } });
Make realtim fco bucket names match format of others
""" Add capped collections for real time data """ import logging log = logging.getLogger(__name__) def up(db): capped_collections = [ "fco_pay_legalisation_post_realtime", "fco_pay_legalisation_drop_off_realtime", "fco_pay_register_birth_abroad_realtime", "fco_pay_register_death_abroad_realtime", "fco_pay_foreign_marriage_certificates_realtime", "fco_deposit_foreign_marriage_realtime", "govuk_realtime", "licensing_realtime", ] for collection_name in capped_collections: db.create_collection(name=collection_name, capped=True, size=5040) log.info("created capped collection: %s" % collection_name)
""" Add capped collections for real time data """ import logging log = logging.getLogger(__name__) def up(db): capped_collections = [ "fco_realtime_pay_legalisation_post", "fco_realtime_pay_legalisation_drop_off", "fco_realtime_pay_register_birth_abroad", "fco_realtime_pay_register_death_abroad", "fco_realtime_pay_foreign_marriage_certificates", "fco_realtime_deposit_foreign_marriage", "govuk_realtime", "licensing_realtime", ] for collection_name in capped_collections: db.create_collection(name=collection_name, capped=True, size=5040) log.info("created capped collection: %s" % collection_name)
[Tests] Disable the Packagist root enquiry test due to upstream breakage
<?php namespace Bolt\Tests\Composer\Action; use Bolt\Composer\Action\ShowPackage; use Bolt\Tests\BoltUnitTest; /** * Class to test src/Composer/Action/ShowPackage. * * @author Ross Riley <riley.ross@gmail.com> */ class ShowPackageTest extends ActionUnitTest { public function testAvailable() { $app = $this->getApp(); $result = $app['extend.action']['show']->execute('available', 'gawain/clippy', '~2.0'); $this->assertArrayHasKey('gawain/clippy', $result); } /** * This test has been disabled at 2015-07-18 due to problems with Travis & composer * * @see https://github.com/bolt/bolt/issues/3829 */ // public function testRootEnquiry() // { // $app = $this->getApp(); // $result = $app['extend.action']['show']->execute('available', 'bolt/bolt', '~2.0', true); // $this->assertArrayHasKey('bolt/bolt', $result); // } }
<?php namespace Bolt\Tests\Composer\Action; use Bolt\Composer\Action\ShowPackage; use Bolt\Tests\BoltUnitTest; /** * Class to test src/Composer/Action/ShowPackage. * * @author Ross Riley <riley.ross@gmail.com> */ class ShowPackageTest extends ActionUnitTest { public function testAvailable() { $app = $this->getApp(); $result = $app['extend.action']['show']->execute('available', 'gawain/clippy', '~2.0'); $this->assertArrayHasKey('gawain/clippy', $result); } public function testRootEnquiry() { $app = $this->getApp(); $result = $app['extend.action']['show']->execute('available', 'bolt/bolt', '~2.0', true); $this->assertArrayHasKey('bolt/bolt', $result); } }
Fix indentation error in LongOnly.__ne__() Also follow Python porting best practice [__use feature detection instead of version detection__](https://docs.python.org/3/howto/pyporting.html#use-feature-detection-instead-of-version-detection).
# coding:utf-8 from __future__ import absolute_import, division, print_function, unicode_literals unicode = type("") class BytesOnly(bytes): def __new__(cls, s): if isinstance(s, unicode): s = s.encode() return bytes.__new__(BytesOnly, s) def __eq__(self, o): return isinstance(o, bytes) and bytes.__eq__(self, o) def __ne__(self, o): return not self == o class UnicodeOnly(unicode): def __eq__(self, o): return isinstance(o, unicode) and unicode.__eq__(self, o) def __ne__(self, o): return not self == o try: class LongOnly(long): # Python 2 def __eq__(self, o): return isinstance(o, long) and long.__cmp__(self, o) == 0 def __ne__(self, o): return not self == o except NameError: # Python 3 LongOnly = int
# coding:utf-8 from __future__ import absolute_import, division, print_function, unicode_literals import sys unicode = type("") class BytesOnly(bytes): def __new__(cls, s): if isinstance(s, unicode): s = s.encode() return bytes.__new__(BytesOnly, s) def __eq__(self, o): return isinstance(o, bytes) and bytes.__eq__(self, o) def __ne__(self, o): return not self == o class UnicodeOnly(unicode): def __eq__(self, o): return isinstance(o, unicode) and unicode.__eq__(self, o) def __ne__(self, o): return not self == o if sys.version_info >= (3,): LongOnly = int else: class LongOnly(long): def __eq__(self, o): return isinstance(o, long) and long.__cmp__(self, o) == 0 def __ne__(self, o): return not self == o
Remove self-touching tets first to reduce collision load.
import igraph def packing_graph(tets, vx, vy, vz, independent = 0): N = len(tets) for i in range(N-1, independent-1, -1): for s in tets[i].get_symetry(vx, vy, vz, include_self=False): if tets[i].collision(s): del tets[i] break N = len(tets) g = igraph.Graph() g.add_vertices(N) for i in range(N): for j in range(max(i, independent),N): for s in tets[j].get_symetry(vx, vy, vz, include_self=(i != j)): if tets[i].collision(s): g.add_edge(i,j) break return g
import igraph def packing_graph(tets, vx, vy, vz, independent = 0): N = len(tets) g = igraph.Graph() g.add_vertices(N) for i in range(N): for j in range(max(i, independent),N): for s in tets[j].get_symetry(vx, vy, vz, include_self=(i != j)): if tets[i].collision(s): g.add_edge(i,j) break edges = g.get_edgelist() for i in range(N, -1, -1): if (i,i) in edges: g.delete_vertices(g.vs[i]) del tets[i] return g
Increase the time delta from 120 to 240 milli secs to decide the failure. Change-Id: Ic51da36d79d4cd4ccac342d7242e56a23e21c07f
from fabfile.config import * @task @roles('all') def get_all_time(): date = run("DATE=$( sudo date ); DATEMILLISEC=$( sudo date +%s ); echo $DATE; echo $DATEMILLISEC") return tuple(date.split('\r\n')) @task @parallel @roles('build') def verify_time_all(): result = execute('get_all_time') all_time = [] for dates in result.values(): try: (date, date_in_millisec) = dates all_time.append(int(date_in_millisec)) except ValueError: print "ERROR: %s" % dates all_time.sort() if (all_time[-1] - all_time[0]) > 240: raise RuntimeError("Time not synced in the nodes," " Please sync and proceed:\n %s %s %s" % (result, all_time[-1], all_time[0])) else: print "Time synced in the nodes, Proceeding to install/provision."
from fabfile.config import * @task @roles('all') def get_all_time(): date = run("DATE=$( sudo date ); DATEMILLISEC=$( sudo date +%s ); echo $DATE; echo $DATEMILLISEC") return tuple(date.split('\r\n')) @task @roles('build') def verify_time_all(): result = execute('get_all_time') print result all_time = [int(date_in_millisec) for date, date_in_millisec in result.values()] all_time.sort() if (all_time[-1] - all_time[0]) > 120: raise RuntimeError("Time not synced in the nodes, Please sync and proceed:\n %s" % result) else: print "Time synced in the nodes, Proceeding to install/provision."
Add args parameter to parse_args for manually specifying args
import argparse import sys class TerseHelpFormatter(argparse.HelpFormatter): def _format_action_invocation(self, action): if not action.option_strings or action.nargs == 0: super()._format_action_invocation(action) default = self._get_default_metavar_for_optional(action) args_string = self._format_args(action, default) return '{} {}'.format(', '.join(action.option_strings), args_string) output_formats = ('text', 'wiki', 'json') def parse_args(args=None): parser = argparse.ArgumentParser(formatter_class=TerseHelpFormatter) parser.add_argument('files', metavar='FILE', nargs='+', help='ROMs, discs, etc.') parser.add_argument('-x', '--extract', action='store_true', help='extract files from disc data tracks') parser.add_argument('-f', '--format', action='store', default='text', choices=output_formats, metavar='FORMAT', help='use output format: text (default), wiki, json', dest='output_format') parser.add_argument('--skip-sector-errors', action='store_true', help='skip sector error checks') # TODO temporary current_module = sys.modules[__name__] parser.parse_args(namespace=current_module, args=args)
import argparse import sys class TerseHelpFormatter(argparse.HelpFormatter): def _format_action_invocation(self, action): if not action.option_strings or action.nargs == 0: super()._format_action_invocation(action) default = self._get_default_metavar_for_optional(action) args_string = self._format_args(action, default) return '{} {}'.format(', '.join(action.option_strings), args_string) output_formats = ('text', 'wiki', 'json') def parse_args(): parser = argparse.ArgumentParser(formatter_class=TerseHelpFormatter) parser.add_argument('files', metavar='FILE', nargs='+', help='ROMs, discs, etc.') parser.add_argument('-x', '--extract', action='store_true', help='extract files from disc data tracks') parser.add_argument('-f', '--format', action='store', default='text', choices=output_formats, metavar='FORMAT', help='use output format: text (default), wiki, json', dest='output_format') parser.add_argument('--skip-sector-errors', action='store_true', help='skip sector error checks') # TODO temporary current_module = sys.modules[__name__] parser.parse_args(namespace=current_module)
Stop starting Sauce Connect automatically
module.exports = function(config) { config.set({ frameworks: ['mocha'], browsers: ['Firefox', 'PhantomJS'], files: ['build/test.js'] }); if (process.env.CI) { var customLaunchers = { 'SauceLabs_Firefox': { base: 'SauceLabs', browserName: 'firefox' }, 'SauceLabs_Chrome': { base: 'SauceLabs', browserName: 'chrome' } }; config.set({ browsers: Object.keys(customLaunchers), reporters: ['progress', 'saucelabs'], captureTimeout: 120000, sauceLabs: { startConnect: false, testName: 'Loud', tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER }, customLaunchers: customLaunchers }); } };
module.exports = function(config) { config.set({ frameworks: ['mocha'], browsers: ['Firefox', 'PhantomJS'], files: ['build/test.js'] }); if (process.env.CI) { var customLaunchers = { 'SauceLabs_Firefox': { base: 'SauceLabs', browserName: 'firefox' }, 'SauceLabs_Chrome': { base: 'SauceLabs', browserName: 'chrome' } }; config.set({ browsers: Object.keys(customLaunchers), reporters: ['progress', 'saucelabs'], captureTimeout: 120000, sauceLabs: { testName: 'Loud', tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER }, customLaunchers: customLaunchers }); } };
Make 404 page show <h1>404</h1>
'use strict'; var bodyParser = require('body-parser'); var express = require('express'); var app = express(); var Config = require('./config/index'); //var SessionConfig = require('./config/session'); /* Requires mongo and isn't used yet. */ var NunjucksEnv = require('./config/nunjucks')(app); var server = app.listen(Config.SERVER_PORT, Config.SERVER_ADDRESS, function () { var host = server.address().address; var port = server.address().port; console.log('Developers\' Guild Website listening at http://%s:%s in ' + '%s mode.', host, port, Config.NODE_ENV); }); var io = require('socket.io')(server); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); //app.use(SessionConfig); /* Requires mongo and isn't used yet. */ app.use(express.static('public')); var routerIndex = require('./routes'); // Use the routers app.use(routerIndex); require('./events')(io); // Handle 404 Error app.use(function(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.send('<h1>404</h1>'); res.end(); });
'use strict'; var bodyParser = require('body-parser'); var express = require('express'); var app = express(); var Config = require('./config/index'); //var SessionConfig = require('./config/session'); /* Requires mongo and isn't used yet. */ var NunjucksEnv = require('./config/nunjucks')(app); var server = app.listen(Config.SERVER_PORT, Config.SERVER_ADDRESS, function () { var host = server.address().address; var port = server.address().port; console.log('Developers\' Guild Website listening at http://%s:%s in ' + '%s mode.', host, port, Config.NODE_ENV); }); var io = require('socket.io')(server); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); //app.use(SessionConfig); /* Requires mongo and isn't used yet. */ app.use(express.static('public')); var routerIndex = require('./routes'); // Use the routers app.use(routerIndex); require('./events')(io); // Handle 404 Error app.use(function(req, res) { res.redirect('/'); });
Apply same fix as in 77a463b50a Signed-off-by: Teodor-Dumitru Ene <2853baffc346a14b7885b2637a7ab7a41c2198d9@gmail.com>
from setuptools import setup, find_namespace_packages setup( name="pptrees", version="0.0.2", description="Parallel Prefix tree generation library", url="https://github.com/tdene/synth_opt_adders", author="tdene", author_email="teodord.ene@gmail.com", license="Apache 2.0", classifiers=[ "Development Status :: 3 - Alpha", "Topic :: System :: Hardware", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python :: 3", ], keywords=["hardware adders prefix"], package_dir={"": "src"}, packages=find_namespace_packages(where="src"), package_data={"pptrees": ["mappings/*.v"]}, long_description=open("README.md").read(), python_requires=">=3.7.*", install_requires=["networkx", "pydot", "graphviz"], )
from setuptools import setup setup( name="pptrees", version="0.0.2", description="Parallel Prefix tree generation library", url="https://github.com/tdene/synth_opt_adders", author="tdene", author_email="teodord.ene@gmail.com", license="Apache 2.0", classifiers=[ "Development Status :: 3 - Alpha", "Topic :: System :: Hardware", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python :: 3", ], keywords=["hardware adders prefix"], package_dir={"": "src"}, packages=["pptrees"], package_data={"pptrees": ["mappings/*.v"]}, long_description=open("README.md").read(), python_requires=">=3.7.*", install_requires=["networkx", "pydot", "graphviz"], )
Fix calling process.exit with "ok" exit code We have a helper to log an error message to the console and exit the process. It looks like the only place we use this helper is when we try and fail to [initialize the driver](https://github.com/tgriesser/knex/blob/5a94bc9b178d399e23a80ff396a0fc7ec01ecc9b/src/client.js#L159). Unfortunately, when we call `process.exit()` without an exit code, it [exits with a `0` exit code](https://nodejs.org/api/process.html#process_process_exit_code) -- which means success. This is especially a problem when running tests in a CI environment, as it results in a false positive: tests not only do not pass, but they probably didn't even run.
var _ = require('lodash') var chalk = require('chalk') var helpers = { // Pick off the attributes from only the current layer of the object. skim: function(data) { return _.map(data, function(obj) { return _.pick(obj, _.keys(obj)); }); }, // Check if the first argument is an array, otherwise // uses all arguments as an array. normalizeArr: function() { var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } if (Array.isArray(args[0])) { return args[0]; } return args; }, error: function(msg) { console.log(chalk.red('Knex:Error ' + msg)) }, // Used to signify deprecated functionality. deprecate: function(method, alternate) { helpers.warn(method + ' is deprecated, please use ' + alternate); }, // Used to warn about incorrect use, without error'ing warn: function(msg) { console.log(chalk.yellow("Knex:warning - " + msg)) }, exit: function(msg) { console.log(chalk.red(msg)) process.exit(1) } }; module.exports = helpers;
var _ = require('lodash') var chalk = require('chalk') var helpers = { // Pick off the attributes from only the current layer of the object. skim: function(data) { return _.map(data, function(obj) { return _.pick(obj, _.keys(obj)); }); }, // Check if the first argument is an array, otherwise // uses all arguments as an array. normalizeArr: function() { var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } if (Array.isArray(args[0])) { return args[0]; } return args; }, error: function(msg) { console.log(chalk.red('Knex:Error ' + msg)) }, // Used to signify deprecated functionality. deprecate: function(method, alternate) { helpers.warn(method + ' is deprecated, please use ' + alternate); }, // Used to warn about incorrect use, without error'ing warn: function(msg) { console.log(chalk.yellow("Knex:warning - " + msg)) }, exit: function(msg) { console.log(chalk.red(msg)) process.exit() } }; module.exports = helpers;
Bring auth-exception-bubbling fix to master I'm concerned that this try-catch that got removed on develop (6f7ccb7d0c28da416831fcaac27e0a4e5d242bee) is impeding debugging issues people are having on master as well, because Auth exceptions show up through the middleware there as `user_not_found`. This could be the root cause of #393 & #397 for example.
<?php namespace Tymon\JWTAuth\Providers\Auth; use Illuminate\Auth\AuthManager; class IlluminateAuthAdapter implements AuthInterface { /** * @var \Illuminate\Auth\AuthManager */ protected $auth; /** * @param \Illuminate\Auth\AuthManager $auth */ public function __construct(AuthManager $auth) { $this->auth = $auth; } /** * Check a user's credentials * * @param array $credentials * @return bool */ public function byCredentials(array $credentials = []) { return $this->auth->once($credentials); } /** * Authenticate a user via the id * * @param mixed $id * @return bool */ public function byId($id) { return $this->auth->onceUsingId($id); } /** * Get the currently authenticated user * * @return mixed */ public function user() { return $this->auth->user(); } }
<?php namespace Tymon\JWTAuth\Providers\Auth; use Exception; use Illuminate\Auth\AuthManager; class IlluminateAuthAdapter implements AuthInterface { /** * @var \Illuminate\Auth\AuthManager */ protected $auth; /** * @param \Illuminate\Auth\AuthManager $auth */ public function __construct(AuthManager $auth) { $this->auth = $auth; } /** * Check a user's credentials * * @param array $credentials * @return bool */ public function byCredentials(array $credentials = []) { return $this->auth->once($credentials); } /** * Authenticate a user via the id * * @param mixed $id * @return bool */ public function byId($id) { try { return $this->auth->onceUsingId($id); } catch (Exception $e) { return false; } } /** * Get the currently authenticated user * * @return mixed */ public function user() { return $this->auth->user(); } }
Add redis cloud, will it work?
var redis = require('redis'), redisCon = module.exports = {}; // redisCon.subClient = redis.createClient(); // redisCon.pubClient = redis.createClient(); redisCon.subClient = redis.createClient(10310, "pub-redis-10310.us-east-1-4.1.ec2.garantiadata.com"); redisCon.subClient.auth("8BnAVVcUwskP", function(){ console.log("subClient Connected!"); }); redisCon.pubClient = redis.createClient(10310, "pub-redis-10310.us-east-1-4.1.ec2.garantiadata.com"); redisCon.pubClient.auth("8BnAVVcUwskP", function(){ console.log("pubClient Connected!"); }); redisCon.subClient.psubscribe('__keyevent@0__:expired'); redisCon.register = function(input){ redisCon.pubClient.set(input, 'randomestring', 'EX', 900, redis.print); analytics.track({ userId: 'null', containerId: input, event: 'start', time: new Date() }); console.log('redis register'); }; redisCon.stopCallback = function(cb){ redisCon.subClient.on('pmessage', function(pattern, channel, expiredKey){ console.log('key expired: ', expiredKey); analytics.track({ userId: 'null', containerId: expiredKey, event: 'stop', time: new Date() }); console.log('redis stop'); cb(expiredKey); }); };
var redis = require('redis'), redisCon = module.exports = {}; redisCon.subClient = redis.createClient(); redisCon.pubClient = redis.createClient(); redisCon.subClient.psubscribe('__keyevent@0__:expired'); redisCon.register = function(input){ redisCon.pubClient.set(input, 'randomestring', 'EX', 900, redis.print); analytics.track({ userId: 'null', containerId: input, event: 'start', time: new Date() }); console.log('redis register'); }; redisCon.stopCallback = function(cb){ redisCon.subClient.on('pmessage', function(pattern, channel, expiredKey){ console.log('key expired: ', expiredKey); analytics.track({ userId: 'null', containerId: expiredKey, event: 'stop', time: new Date() }); console.log('redis stop'); cb(expiredKey); }); };
Fix color function to support rgba on IE9 and up
/* =============================================================================================== Unify Project Homepage: unify-project.org License: MIT + Apache (V2) Copyright: 2012, Sebastian Fastner, Mainz, Germany, http://unify-training.com =============================================================================================== */ (function() { var rgba = function(red,green,blue,alpha) { return "rgba(" + red + "," + green + "," + blue + "," + alpha + ")"; }; var rgb = function(red,green,blue) { return "rgb(" + red + "," + green + "," + blue + ")"; }; var colorFnt; if (core.Env.getValue("engine") == "trident") { var version = /MSIE.(\d+)/.exec(navigator.userAgent); if (version[1] && parseInt(version[1],10) < 9) { colorFnt = rgb; } else { colorFnt = rgba; } } else { colorFnt = rgba; } /** * Creates browser specific gradients */ core.Module('unify.bom.Color', { /* ---------------------------------------------------------------------------- STATICS ---------------------------------------------------------------------------- */ /** * Creates a browser specific color code based upon @red {Integer}, @green {Integer}, * @blue {Integer} and @alpha {Float}, ignoring alpha on IE<9 */ rgba: colorFnt }); })();
/* =============================================================================================== Unify Project Homepage: unify-project.org License: MIT + Apache (V2) Copyright: 2012, Sebastian Fastner, Mainz, Germany, http://unify-training.com =============================================================================================== */ /** * Creates browser specific gradients */ core.Module('unify.bom.Color', { /* ---------------------------------------------------------------------------- STATICS ---------------------------------------------------------------------------- */ /** * Creates a browser specific color code based upon @red {Integer}, @green {Integer}, * @blue {Integer} and @alpha {Float}, ignoring alpha on IE<9 */ rgba: function(red,green,blue,alpha) { if (core.Env.getValue("engine") == "trident") { return "rgb(" + red + "," + green + "," + blue + ")"; } else { return "rgba(" + red + "," + green + "," + blue + "," + alpha + ")"; } } });
Check if apc is enabled during test setup
<?php namespace Nsautoload\Tests; use Nsautoload\Nsautoload; use Symfony\Component\ClassLoader\ApcClassLoader; require_once __DIR__.'/AutoloadTest.php'; class CacheTest extends \PHPUnit_Framework_TestCase { public function setUp() { if (!class_exists('Symfony\Component\ClassLoader\ApcClassLoader')) { $this->markTestSkipped('Class loader not found'); } if (!extension_loaded('apc')) { $this->markTestSkipped('APC not enabled'); } apc_clear_cache('user'); } /** * @dataProvider getLoaderTests */ public function testFindFile($className, $location) { $loader = new ApcClassLoader(md5(__DIR__), new Nsautoload()); $file = $loader->findFile($className); $this->assertSame(realpath($file), realpath($location)); } public function getLoaderTests() { return AutoloadTest::getLoaderTests(); } }
<?php namespace Nsautoload\Tests; use Nsautoload\Nsautoload; use Symfony\Component\ClassLoader\ApcClassLoader; require_once __DIR__.'/AutoloadTest.php'; class CacheTest extends \PHPUnit_Framework_TestCase { public function setUp() { if (!class_exists('Symfony\Component\ClassLoader\ApcClassLoader')) { $this->markTestSkipped('Class loader not found'); } } /** * @dataProvider getLoaderTests */ public function testFindFile($className, $location) { $loader = new ApcClassLoader(md5(__DIR__), new Nsautoload()); $file = $loader->findFile($className); $this->assertSame(realpath($file), realpath($location)); } public function getLoaderTests() { return AutoloadTest::getLoaderTests(); } }
[WebUI] Implement state fetching on load. TODO: Find out what actual RasPi returns for the states. Signed-off-by: Juri Berlanda <5bfdca9e82c53adb0603ce7083f4ba4f2da5cacf@hotmail.com>
SCENT_STATUS_URL = "/status"; SCENT_ON_VALUE = "HIGH"; console.log("Start"); var socket = io.connect('http://' + document.domain + ':' + location.port + '/scent'); socket.on('connect', function(msg) { console.log('[INFO] Socket connected.'); }); function activate(scent) { console.log('Activating scent: ' + scent); socket.emit('activate', scent); } function deactivate(scent) { console.log('Deactivating scent: ' + scent); socket.emit('deactivate', scent); } function handleClick(cb) { if (cb.checked) activate(cb.id); else deactivate(cb.id); } function applyState(data) { $.each(data, function(key, val) { var cb =$('#scentCheckboxes').find('#' + key); cb.prop('checked', val == SCENT_ON_VALUE); cb.prop('disabled', false); }); } function fetchState() { $.ajax({ url: SCENT_STATUS_URL, success: applyState }); } var scentModel = { availableScents: [0, 1, 2, 3, 4, 5] }; ko.applyBindings(scentModel); fetchState();
console.log("Start"); var socket = io.connect('http://' + document.domain + ':' + location.port + '/scent'); socket.on('connect', function(msg) { console.log('[INFO] Socket connected.'); }); function activate(scent) { console.log('Activating scent: ' + scent); socket.emit('activate', scent); } function deactivate(scent) { console.log('Deactivating scent: ' + scent); socket.emit('deactivate', scent); } function handleClick(cb) { if (cb.checked) activate(cb.id); else deactivate(cb.id); } var scentModel = { availableScents: [0, 1, 2, 3, 4, 5] }; ko.applyBindings(scentModel);
Allow re-use of a port a la SO_REUSEADDRESS
#!/usr/bin/python """ Simple TCP server that sends back the IP address and port from which it sees you connect. Useful when used with `telnet` for network debugging. Currently only IPv4. """ import SocketServer VERBOSE = False class TCPHandler(SocketServer.BaseRequestHandler): """ Handles each request be sending the client's IP address and port, then closing the connection. """ def handle(self): # self.request is the TCP socket connected to the client address = self.client_address[0] + ":" + str(self.client_address[1]) if VERBOSE: print "Request from: " + address self.request.sendall(address + "\n") def main(): import optparse global VERBOSE parser = optparse.OptionParser() parser.add_option("-p", "--port", type="int", default=9999, help="port to listen on") parser.add_option("-v", "--verbose", action="store_true") options = parser.parse_args()[0] port = options.port VERBOSE = options.verbose SocketServer.TCPServer.allow_reuse_address = True server = SocketServer.TCPServer(("0.0.0.0", port), TCPHandler) print "Listening on port %d" % port # Activate the server; this will keep running until you # interrupt the program with Ctrl-C server.serve_forever() if __name__ == "__main__": main()
#!/usr/bin/python """ Simple TCP server that sends back the IP address and port from which it sees you connect. Useful when used with `telnet` for network debugging. Currently only IPv4. """ import SocketServer VERBOSE = False class TCPHandler(SocketServer.BaseRequestHandler): """ Handles each request be sending the client's IP address and port, then closing the connection. """ def handle(self): # self.request is the TCP socket connected to the client address = self.client_address[0] + ":" + str(self.client_address[1]) if VERBOSE: print "Request from: " + address self.request.sendall(address + "\n") def main(): import optparse global VERBOSE parser = optparse.OptionParser() parser.add_option("-p", "--port", type="int", default=9999, help="port to listen on") parser.add_option("-v", "--verbose", action="store_true") options = parser.parse_args()[0] port = options.port VERBOSE = options.verbose server = SocketServer.TCPServer(("0.0.0.0", port), TCPHandler) print "Listening on port %d" % port # Activate the server; this will keep running until you # interrupt the program with Ctrl-C server.serve_forever() if __name__ == "__main__": main()
Add LINCENSE to included files.
"""\ Grip ---- Render local readme files before sending off to Github. Grip is easy to set up `````````````````````` :: $ pip install grip $ cd myproject $ grip * Running on http://localhost:5000/ Links ````` * `Website <http://github.com/joeyespo/grip/>`_ """ from setuptools import setup, find_packages import grip as package setup( name=package.__name__, author='Joe Esposito', author_email='joe@joeyespo.com', url='http://github.com/joeyespo/grip', license='MIT', version=package.__version__, description=package.__description__, long_description=__doc__, platforms='any', packages=find_packages(), package_data={package.__name__: ['LICENSE', 'static/*', 'templates/*']}, entry_points={'console_scripts': ['grip = grip.command:main']}, install_requires=[ 'flask>=0.9', 'jinja2>=2.6', 'requests>=0.14', ], )
"""\ Grip ---- Render local readme files before sending off to Github. Grip is easy to set up `````````````````````` :: $ pip install grip $ cd myproject $ grip * Running on http://localhost:5000/ Links ````` * `Website <http://github.com/joeyespo/grip/>`_ """ from setuptools import setup, find_packages import grip as package setup( name=package.__name__, author='Joe Esposito', author_email='joe@joeyespo.com', url='http://github.com/joeyespo/grip', license='MIT', version=package.__version__, description=package.__description__, long_description=__doc__, platforms='any', packages=find_packages(), package_data={package.__name__: ['static/*', 'templates/*']}, entry_points={'console_scripts': ['grip = grip.command:main']}, install_requires=[ 'flask>=0.9', 'jinja2>=2.6', 'requests>=0.14', ], )
Use numbers, not strings, for stats summaries.
'use strict'; const Stats = require('fast-stats').Stats; function percentileName(percentile) { if (percentile === 0) { return 'min'; } else if (percentile === 100) { return 'max'; } else if (percentile === 50) { return 'median'; } return `p${String(percentile).replace('.', '_')}`; } class Statistics { constructor() { this.stats = new Stats(); } add(value) { this.stats.push(value); return this; } summarize(options) { options = options || {}; const percentiles = options.percentiles || [0, 10, 50, 90, 99, 100]; const decimals = options.decimals || 0; const data = {}; const self = this; percentiles.forEach(p => { const name = percentileName(p); data[name] = Number(self.stats.percentile(p).toFixed(decimals)); }); return data; } } module.exports = { Statistics, };
'use strict'; const Stats = require('fast-stats').Stats; function percentileName(percentile) { if (percentile === 0) { return 'min'; } else if (percentile === 100) { return 'max'; } else if (percentile === 50) { return 'median'; } return `p${String(percentile).replace('.', '_')}`; } class Statistics { constructor() { this.stats = new Stats(); } add(value) { this.stats.push(value); return this; } summarize(options) { options = options || {}; const percentiles = options.percentiles || [0, 10, 50, 90, 99, 100]; const decimals = options.decimals || 0; const data = {}; const self = this; percentiles.forEach(p => { const name = percentileName(p); data[name] = self.stats.percentile(p).toFixed(decimals); }); return data; } } module.exports = { Statistics, };
Web: Change lastPlayedSong to lastPlayedSongUri in Soapy API.
<?php use Base\Playlist as BasePlaylist; /** * Skeleton subclass for representing a row from the 'playlist' table. * * * * You should add additional methods to this class to meet the * application requirements. This class will only be generated as * long as it does not already exist in the output directory. * */ class Playlist extends BasePlaylist { public function getDataForJson() { return [ 'soapyPlaylistId' => $this->getId(), 'uri' => $this->getUri(), 'lastPlayedSongUri' => $this->getLastPlayedSong(), ]; } public function getOwnerUsername() { $playlist_uri_expl = explode(':', $this->getUri()); return $playlist_uri_expl[2]; } public function getSpotifyId() { $playlist_uri_expl = explode(':', $this->getUri()); return $playlist_uri_expl[4]; } }
<?php use Base\Playlist as BasePlaylist; /** * Skeleton subclass for representing a row from the 'playlist' table. * * * * You should add additional methods to this class to meet the * application requirements. This class will only be generated as * long as it does not already exist in the output directory. * */ class Playlist extends BasePlaylist { public function getDataForJson() { return [ 'soapyPlaylistId' => $this->getId(), 'uri' => $this->getUri(), 'lastPlayedSong' => $this->getLastPlayedSong(), ]; } public function getOwnerUsername() { $playlist_uri_expl = explode(':', $this->getUri()); return $playlist_uri_expl[2]; } public function getSpotifyId() { $playlist_uri_expl = explode(':', $this->getUri()); return $playlist_uri_expl[4]; } }
Fix syntax error in test
require('../test')("Last insert id", function (conn, t) { if (conn.adapter == 'postgres') { t.skip("Last insert ID not supported by postgres") return t.end() } t.plan(2) conn.query("DROP TABLE last_insert_id_test", function (err) {}) if (conn.adapter == 'sqlite3') conn.query("CREATE TABLE last_insert_id_test (id integer primary key autoincrement, a int)") else if (conn.adapter == 'mysql') conn.query("CREATE TABLE last_insert_id_test (id integer primary key auto_increment, a int)") conn.query('INSERT INTO last_insert_id_test (a) VALUES (123)', function (err, res) { if (err) throw err t.equal(res.lastInsertId, 1) conn.query('INSERT INTO last_insert_id_test (a) VALUES (456)', function (err, res) { if (err) throw err t.equal(res.lastInsertId, 2) }) }) })
require('../test')("Last insert id", function (conn, t) { if (conn.adapter == 'postgres') { t.skip("Last insert ID not supported by postgres") return t.end() } t.plan(2) conn.query("DROP TABLE last_insert_id_test", function (err) {}) if (conn.adapter == 'sqlite3') conn.query("CREATE TABLE last_insert_id_test (id integer primary key autoincrement, a int)") else if (conn.adapter == 'mysql') conn.query("CREATE TABLE last_insert_id_test (id integer primary key auto_increment, a int)") conn.query('INSERT INTO last_insert_id_test (a) VALUES (123)', function (err, res) { if (err) throw err t.equal(res.lastInsertId, 1) conn.query('INSERT INTO last_insert_id_test (a) VALUES (456)', function (err, res) { if (err) throw err t.equal(res.lastInsertId, 2) }) }) }
Fix bug with displaying/comparing null values in traces.
package orc.trace.values; import java.io.IOException; import java.io.Serializable; import java.io.Writer; import xtc.util.Utilities; /** * Constant (not just immutable, but atomic) value, * such as a String, Number, Boolean, Character, or null. * @author quark */ public class ConstantValue extends AbstractValue { public final Serializable constant; public ConstantValue(final Serializable constant) { super(); this.constant = constant; } public void prettyPrint(Writer out, int indent) throws IOException { out.write(orc.runtime.values.Value.write(constant)); } public boolean equals(final Object that) { if (that == null) return false; if (!(that instanceof ConstantValue)) return false; final ConstantValue cv = (ConstantValue)that; if (cv.constant == null) return constant == null; return cv.constant.equals(constant); } }
package orc.trace.values; import java.io.IOException; import java.io.Serializable; import java.io.Writer; import xtc.util.Utilities; /** * Constant (not just immutable, but atomic) value, * such as a String, Number, Boolean, or Character. * @author quark */ public class ConstantValue extends AbstractValue { public final Serializable constant; public ConstantValue(final Serializable constant) { super(); this.constant = constant; } public void prettyPrint(Writer out, int indent) throws IOException { if (constant instanceof String) { out.write('"' + Utilities.escape((String)constant, Utilities.JAVA_ESCAPES) + '"'); } else out.write(constant.toString()); } public boolean equals(Object that) { return that instanceof ConstantValue && ((ConstantValue)that).constant.equals(constant); } }
Add tests for ValueError and TypeError
import sys from socket import htonl, inet_ntoa from struct import pack import pytest from arpreq import arpreq def test_localhost(): assert arpreq('127.0.0.1') == '00:00:00:00:00:00' def decode_address(value): return inet_ntoa(pack(">I", htonl(int(value, base=16)))) def decode_flags(value): return int(value, base=16) def get_default_gateway(): with open("/proc/net/route") as f: next(f) for line in f: fields = line.strip().split() destination = decode_address(fields[1]) mask = decode_address(fields[7]) gateway = decode_address(fields[2]) flags = decode_flags(fields[3]) if destination == '0.0.0.0' and mask == '0.0.0.0' and flags & 0x2: return gateway return None def test_default_gateway(): gateway = get_default_gateway() if not gateway: pytest.skip("No default gateway present.") assert arpreq(gateway) is not None def test_illegal_argument(): with pytest.raises(ValueError): arpreq("Foobar") def test_illegal_type(): with pytest.raises(TypeError): arpreq(42)
import sys from socket import htonl, inet_ntoa from struct import pack import pytest from arpreq import arpreq def test_localhost(): assert arpreq('127.0.0.1') == '00:00:00:00:00:00' def decode_address(value): return inet_ntoa(pack(">I", htonl(int(value, base=16)))) def decode_flags(value): return int(value, base=16) def get_default_gateway(): with open("/proc/net/route") as f: next(f) for line in f: fields = line.strip().split() destination = decode_address(fields[1]) mask = decode_address(fields[7]) gateway = decode_address(fields[2]) flags = decode_flags(fields[3]) if destination == '0.0.0.0' and mask == '0.0.0.0' and flags & 0x2: return gateway return None def test_default_gateway(): gateway = get_default_gateway() if not gateway: pytest.skip("No default gateway present.") assert arpreq(gateway) is not None
Fix testcase to match reg shuffle fix
/* * https://github.com/svaarala/duktape/issues/111 */ /*--- { "custom": true } ---*/ /*=== 65531 Error Error Error ===*/ function test(n) { var res = []; var i; var fn; res.push('(function func() { '); for (i = 0; i < n; i++) { res.push(' var arg' + i + ' = ' + i + ';'); } res.push(' return arg' + (i - 1) + ';'); res.push('})'); res = res.join('\n'); fn = eval(res); return fn(); } try { print(test(65535 - 3)); // should work, -3 for shuffle regs } catch (e) { print(e.name); } try { print(test(65536 - 3)); // should be rejected with internal error now } catch (e) { print(e.name); } try { print(test(262143 - 3)); // should be rejected with internal error now } catch (e) { print(e.name); } try { print(test(262144 - 3)); // should be rejected with internal error now } catch (e) { print(e.name); }
/* * https://github.com/svaarala/duktape/issues/111 */ /*--- { "custom": true } ---*/ /*=== 65534 Error Error Error ===*/ function test(n) { var res = []; var i; var fn; res.push('(function func() { '); for (i = 0; i < n; i++) { res.push(' var arg' + i + ' = ' + i + ';'); } res.push(' return arg' + (i - 1) + ';'); res.push('})'); res = res.join('\n'); fn = eval(res); return fn(); } try { print(test(65535)); // should work } catch (e) { print(e.name); } try { print(test(65536)); // should be rejected with internal error now } catch (e) { print(e.name); } try { print(test(262143)); // should be rejected with internal error now } catch (e) { print(e.name); } try { print(test(262144)); // should be rejected with internal error now } catch (e) { print(e.name); }
Add routes to both client and server, in case they're needed
Package.describe({ summary: "Make signin and signout their own pages with routes." }); Package.on_use(function(api) { api.use([ 'deps', 'service-configuration', 'accounts-base', 'underscore', 'templating', 'handlebars', 'spark', 'session', 'coffeescript', 'less'] , 'client'); api.imply('accounts-base', ['client', 'server']); api.add_files([ 'sign-in/signIn.html', 'sign-in/signIn.coffee', 'sign-up/signUp.html', 'sign-up/signUp.coffee', 'forgot-password/forgotPassword.html', 'forgot-password/forgotPassword.coffee', 'shared/social.html', 'shared/social.coffee', 'shared/error.html', 'shared/error.coffee', 'shared/accountButtons.html', 'shared/accountButtons.coffee', 'entry.less', 'helper.js'] , 'client'); api.use([ 'deps', 'service-configuration', 'accounts-password', 'accounts-base', 'underscore', 'coffeescript'] , 'server'); api.export('AccountsEntry', 'server'); api.add_files('entry.coffee', 'server'); api.use('iron-router', ['client', 'server']); api.add_files('router.coffee', ['client', 'server']); });
Package.describe({ summary: "Make signin and signout their own pages with routes." }); Package.on_use(function(api) { api.use([ 'deps', 'service-configuration', 'accounts-base', 'underscore', 'templating', 'handlebars', 'spark', 'session', 'coffeescript', 'iron-router', 'less'] , 'client'); api.imply('accounts-base', ['client', 'server']); api.add_files([ 'router.coffee', 'sign-in/signIn.html', 'sign-in/signIn.coffee', 'sign-up/signUp.html', 'sign-up/signUp.coffee', 'forgot-password/forgotPassword.html', 'forgot-password/forgotPassword.coffee', 'shared/social.html', 'shared/social.coffee', 'shared/error.html', 'shared/error.coffee', 'shared/accountButtons.html', 'shared/accountButtons.coffee', 'entry.less', 'helper.js'] , 'client'); api.use([ 'deps', 'service-configuration', 'accounts-password', 'accounts-base', 'underscore', 'coffeescript'] , 'server'); api.export('AccountsEntry', 'server'); api.add_files('entry.coffee', 'server'); });
Add time to peek command.
package io.arkeus.fatebot.commands.impl; import org.jibble.pircbot.Colors; import io.arkeus.fatebot.commands.Command; import io.arkeus.fatebot.commands.CommandException; import io.arkeus.fatebot.handlers.TrapHandler; import io.arkeus.fatebot.util.MessageBuilder; import io.arkeus.fatebot.util.TimeUtils; public class PeekCommand extends Command { private static final MessageBuilder mb = new MessageBuilder(); public PeekCommand() { super(0); } @Override protected void run() throws CommandException { if (!bot.isAdministrator(sender)) { return; } final TrapHandler handler = (TrapHandler) bot.getHandler("trap"); final String trap = handler.getTrap(); if (trap == null) { bot.sendNotice(sender, "No trap card is set."); return; } final String trapper = handler.getTrapper(); mb.clear(); mb.appendBrackets("Trap", trap, Colors.BLUE).append(" "); mb.appendBrackets("Trapper", trapper, Colors.BROWN).append(" "); mb.appendBrackets("Time", TimeUtils.getDurationFromMillis(handler.getTrapTime()) + " ago", Colors.DARK_BLUE); bot.sendNotice(sender, mb.toString()); } }
package io.arkeus.fatebot.commands.impl; import org.jibble.pircbot.Colors; import io.arkeus.fatebot.commands.Command; import io.arkeus.fatebot.commands.CommandException; import io.arkeus.fatebot.handlers.TrapHandler; import io.arkeus.fatebot.util.MessageBuilder; public class PeekCommand extends Command { private static final MessageBuilder mb = new MessageBuilder(); public PeekCommand() { super(0); } @Override protected void run() throws CommandException { if (!bot.isAdministrator(sender)) { return; } final TrapHandler handler = (TrapHandler) bot.getHandler("trap"); final String trap = handler.getTrap(); if (trap == null) { bot.sendNotice(sender, "No trap card is set."); return; } final String trapper = handler.getTrapper(); mb.clear(); mb.appendBrackets("Trap", trap, Colors.BLUE).append(" "); mb.appendBrackets("Trapper", trapper, Colors.BROWN); bot.sendNotice(sender, mb.toString()); } }
Enable quick deploys in fabric
import os from fabric.api import * LOCAL_ROOT = os.path.dirname(os.path.realpath(__file__)) LOCAL_VIRTUALENV = '~/.virtualenv/tomo' TOMO_HOST = 'www.projekt-tomo.si' env.hosts = [TOMO_HOST] # MAIN TASKS @task def test(): with lcd(LOCAL_ROOT), activate_virtualenv(): with lcd('web'): local('./manage.py test') @task def deploy(): with cd('/home/gregor/docker/'): sudo('docker-compose pull') sudo('docker-compose up -d') migrate() @task def quick_deploy(): tomo_docker('bash -c "cd projekt-tomo && git pull"') migrate() manage('collectstatic --noinput') tomo_docker('uwsgi --reload /tmp/project-master.pid') @task def migrate(): manage('migrate') @task def ls(): manage('help') # AUXILLIARY FUNCTIONS def activate_virtualenv(): return prefix('source {}/bin/activate'.format(LOCAL_VIRTUALENV)) def manage(command): tomo_docker('python3 projekt-tomo/web/manage.py {}'.format(command)) def tomo_docker(command): sudo('docker exec docker_tomo_1 {}'.format(command))
import os from fabric.api import * LOCAL_ROOT = os.path.dirname(os.path.realpath(__file__)) LOCAL_VIRTUALENV = '~/.virtualenv/tomo' TOMO_HOST = 'www.projekt-tomo.si' env.hosts = [TOMO_HOST] # MAIN TASKS @task def test(): with lcd(LOCAL_ROOT), activate_virtualenv(): with lcd('web'): local('./manage.py test') @task def deploy(): with cd('/home/gregor/docker/'): sudo('docker-compose pull') sudo('docker-compose up -d') migrate() @task def migrate(): manage('migrate') @task def ls(): manage('help') # AUXILLIARY FUNCTIONS def activate_virtualenv(): return prefix('source {}/bin/activate'.format(LOCAL_VIRTUALENV)) def manage(command): tomo_docker('python3 projekt-tomo/web/manage.py {}'.format(command)) def tomo_docker(command): sudo('docker exec docker_tomo_1 {}'.format(command))
Set the default number of items to 12 because it fits more nicely on the email
from games import models DEFAULT_COUNT = 12 def get_unpublished_installers(count=DEFAULT_COUNT): return models.Installer.objects.filter(published=False).order_by('?')[:count] def get_unpublished_screenshots(count=DEFAULT_COUNT): return models.Screenshot.objects.filter(published=False).order_by('?')[:count] def get_unreviewed_game_submissions(count=DEFAULT_COUNT): return models.GameSubmission.objects.filter(accepted_at__isnull=True).order_by('?')[:count] def get_installer_issues(count=DEFAULT_COUNT): return models.InstallerIssue.objects.all().order_by('?')[:count] def get_mod_mail_content(): return { 'installers': get_unpublished_installers(), 'screenshots': get_unpublished_screenshots(), 'submissions': get_unreviewed_game_submissions(), 'issues': get_installer_issues() }
from games import models def get_unpublished_installers(count=10): return models.Installer.objects.filter(published=False).order_by('?')[:count] def get_unpublished_screenshots(count=10): return models.Screenshot.objects.filter(published=False).order_by('?')[:count] def get_unreviewed_game_submissions(count=10): return models.GameSubmission.objects.filter(accepted_at__isnull=True).order_by('?')[:count] def get_installer_issues(count=10): return models.InstallerIssue.objects.all().order_by('?')[:count] def get_mod_mail_content(): return { 'installers': get_unpublished_installers(), 'screenshots': get_unpublished_screenshots(), 'submissions': get_unreviewed_game_submissions(), 'issues': get_installer_issues() }
Increase `Created` column width to accommodate timezone ID
/* * Copyright 2016 Crown Copyright * * 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 stroom.data.client.presenter; public final class ColumnSizeConstants { public static final int CHECKBOX_COL = 16; public static final int ICON_COL = 23; public static final int SMALL_COL = 70; public static final int MEDIUM_COL = 100; public static final int BIG_COL = 400; public static final int DATE_COL = 200; private ColumnSizeConstants() { // Constants. } }
/* * Copyright 2016 Crown Copyright * * 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 stroom.data.client.presenter; public final class ColumnSizeConstants { public static final int CHECKBOX_COL = 16; public static final int ICON_COL = 23; public static final int SMALL_COL = 70; public static final int MEDIUM_COL = 100; public static final int BIG_COL = 400; public static final int DATE_COL = 160; private ColumnSizeConstants() { // Constants. } }
Use apache.common.lang3 for OS determination.
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jena.base; import org.apache.commons.lang3.SystemUtils; public class Sys { /** Is this windows? */ public static final boolean isWindows = SystemUtils.IS_OS_WINDOWS; /** Is this MacOS? */ public static final boolean isMacOS = SystemUtils.IS_OS_MAC; }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jena.base; import java.io.File ; public class Sys { /** Is this windows? */ public static final boolean isWindows = (File.pathSeparatorChar == ';') ; }
Refactor SPARQL update patcher with promises. This improves reuse for future parsers.
// Performs an application/sparql-update patch on a graph module.exports = patch const $rdf = require('rdflib') const debug = require('../../debug').handlers const error = require('../../http-error') // Patches the given graph function patch (targetKB, targetURI, patchText) { const patchKB = $rdf.graph() const target = patchKB.sym(targetURI) // Must parse relative to document's base address but patch doc should get diff URI // @@@ beware the triples from the patch ending up in the same place const patchURI = targetURI return parsePatchDocument(patchURI, patchText, patchKB) .then(patchObject => applyPatch(patchObject, target, targetKB)) } // Parses the given SPARQL UPDATE document function parsePatchDocument (patchURI, patchText, patchKB) { debug('PATCH -- Parsing patch...') return new Promise((resolve, reject) => { try { resolve($rdf.sparqlUpdateParser(patchText, patchKB, patchURI)) } catch (err) { reject(error(400, 'Patch format syntax error:\n' + err + '\n')) } }) } // Applies the patch to the target graph function applyPatch (patchObject, target, targetKB) { return new Promise((resolve, reject) => targetKB.applyPatch(patchObject, target, (err) => { if (err) { const message = err.message || err // returns string at the moment debug('PATCH FAILED. Returning 409. Message: \'' + message + '\'') return reject(error(409, 'Error when applying the patch')) } resolve(targetKB) }) ) }
// Performs an application/sparql-update patch on a graph module.exports = patch const $rdf = require('rdflib') const debug = require('../../debug').handlers const error = require('../../http-error') // Patches the given graph function patch (targetKB, targetURI, patchText) { return new Promise((resolve, reject) => { // Parse the patch document debug('PATCH -- Parsing patch...') const patchURI = targetURI // @@@ beware the triples from the patch ending up in the same place const patchKB = $rdf.graph() var patchObject try { // Must parse relative to document's base address but patch doc should get diff URI patchObject = $rdf.sparqlUpdateParser(patchText, patchKB, patchURI) } catch (e) { return reject(error(400, 'Patch format syntax error:\n' + e + '\n')) } debug('PATCH -- reading target file ...') // Apply the patch to the target graph var target = patchKB.sym(targetURI) targetKB.applyPatch(patchObject, target, function (err) { if (err) { var message = err.message || err // returns string at the moment debug('PATCH FAILED. Returning 409. Message: \'' + message + '\'') return reject(error(409, 'Error when applying the patch')) } resolve(targetKB) }) }) }
Bump min width to 300
import React, { PropTypes } from 'react'; export function getDefaultStyle(props) { let { left, right, bottom, top } = props; if (typeof left === 'undefined' && typeof right === 'undefined') { right = true; } if (typeof top === 'undefined' && typeof bottom === 'undefined') { bottom = true; } return { position: 'fixed', zIndex: 10000, fontSize: 17, overflow: 'hidden', opacity: 1, color: 'white', left: left ? 0 : undefined, right: right ? 0 : undefined, top: top ? 0 : undefined, bottom: bottom ? 0 : undefined, maxHeight: (bottom && top) ? '100%' : '20%', maxWidth: (left && right) ? '100%' : '20%', minWidth: 300, wordWrap: 'break-word', boxSizing: 'border-box' }; } export default class DebugPanel { static propTypes = { left: PropTypes.bool, right: PropTypes.bool, bottom: PropTypes.bool, top: PropTypes.bool, getStyle: PropTypes.func.isRequired }; static defaultProps = { getStyle: getDefaultStyle }; render() { return ( <div style={{...this.props.getStyle(this.props), ...this.props.style}}> {this.props.children} </div> ); } }
import React, { PropTypes } from 'react'; export function getDefaultStyle(props) { let { left, right, bottom, top } = props; if (typeof left === 'undefined' && typeof right === 'undefined') { right = true; } if (typeof top === 'undefined' && typeof bottom === 'undefined') { bottom = true; } return { position: 'fixed', zIndex: 10000, fontSize: 17, overflow: 'hidden', opacity: 1, color: 'white', left: left ? 0 : undefined, right: right ? 0 : undefined, top: top ? 0 : undefined, bottom: bottom ? 0 : undefined, maxHeight: (bottom && top) ? '100%' : '20%', maxWidth: (left && right) ? '100%' : '20%', minWidth: 260, wordWrap: 'break-word', boxSizing: 'border-box' }; } export default class DebugPanel { static propTypes = { left: PropTypes.bool, right: PropTypes.bool, bottom: PropTypes.bool, top: PropTypes.bool, getStyle: PropTypes.func.isRequired }; static defaultProps = { getStyle: getDefaultStyle }; render() { return ( <div style={{...this.props.getStyle(this.props), ...this.props.style}}> {this.props.children} </div> ); } }
Use native sort + treat empty data
import { validateAssessmentItem } from '../../utils'; export function getNodeAssessmentItems(state) { return function(contentNodeId) { if (!state.assessmentItemsMap[contentNodeId]) { return []; } const items = Object.values(state.assessmentItemsMap[contentNodeId]); return items.sort((item1, item2) => (item1.order > item2.order ? 1 : -1)); }; } export function getNodeAssessmentItemErrors(state) { return function(contentNodeId) { return getNodeAssessmentItems(state)(contentNodeId).map(validateAssessmentItem); }; } export function getInvalidNodeAssessmentItemsCount(state) { return function(contentNodeId) { return getNodeAssessmentItemErrors(state)(contentNodeId).filter(arr => arr.length).length; }; } export function getAssessmentItemsAreValid(state) { return function(contentNodeId) { return getInvalidNodeAssessmentItemsCount(state)(contentNodeId) === 0; }; }
import sortBy from 'lodash/sortBy'; import { validateAssessmentItem } from '../../utils'; function sorted(items) { return sortBy(items, ['order']); } export function getNodeAssessmentItems(state) { return function(contentNodeId) { return sorted(Object.values(state.assessmentItemsMap[contentNodeId])); }; } export function getNodeAssessmentItemErrors(state) { return function(contentNodeId) { return getNodeAssessmentItems(state)(contentNodeId).map(validateAssessmentItem); }; } export function getInvalidNodeAssessmentItemsCount(state) { return function(contentNodeId) { return getNodeAssessmentItemErrors(state)(contentNodeId).filter(arr => arr.length).length; }; } export function getAssessmentItemsAreValid(state) { return function(contentNodeId) { return getInvalidNodeAssessmentItemsCount(state)(contentNodeId) === 0; }; }
Put cutline map in 26915
#!/usr/bin/env python from osgeo import ogr from osgeo import osr from glob import glob import os.path driver = ogr.GetDriverByName("ESRI Shapefile") ds = driver.CreateDataSource("summary-maps/cutline-map.shp") srs = osr.SpatialReference() srs.ImportFromEPSG(26915) cutline_srs = osr.SpatialReference() cutline_srs.ImportFromEPSG(4326) coord_trans = osr.CoordinateTransformation(cutline_srs, srs) layer = ds.CreateLayer("tiles", srs, ogr.wkbPolygon) field_name = ogr.FieldDefn("Name", ogr.OFTString) field_name.SetWidth(16) layer.CreateField(field_name) for fn in glob("cutlines/*.json"): tile_id = os.path.splitext(os.path.basename(fn))[0] cutline_ds = ogr.Open(fn) cutline_layer = cutline_ds.GetLayerByIndex(0) cutline_feature = cutline_layer.GetNextFeature() while cutline_feature: poly = cutline_feature.GetGeometryRef().Clone() poly.Transform(coord_trans) feature = ogr.Feature(layer.GetLayerDefn()) feature.SetField("Name", tile_id) feature.SetGeometry(poly) layer.CreateFeature(feature) feature.Destroy() cutline_feature = cutline_layer.GetNextFeature() ds.Destroy()
#!/usr/bin/env python from osgeo import ogr from osgeo import osr from glob import glob import os.path driver = ogr.GetDriverByName("ESRI Shapefile") ds = driver.CreateDataSource("summary-maps/cutline-map.shp") srs = osr.SpatialReference() srs.ImportFromEPSG(4326) layer = ds.CreateLayer("tiles", srs, ogr.wkbPolygon) field_name = ogr.FieldDefn("Name", ogr.OFTString) field_name.SetWidth(16) layer.CreateField(field_name) for fn in glob("cutlines/*.json"): tile_id = os.path.splitext(os.path.basename(fn))[0] cutline_ds = ogr.Open(fn) cutline_layer = cutline_ds.GetLayerByIndex(0) cutline_feature = cutline_layer.GetNextFeature() while cutline_feature: poly = cutline_feature.GetGeometryRef().Clone() feature = ogr.Feature(layer.GetLayerDefn()) feature.SetField("Name", tile_id) feature.SetGeometry(poly) layer.CreateFeature(feature) feature.Destroy() cutline_feature = cutline_layer.GetNextFeature() ds.Destroy()
Test guarded access to `stats` in `fs.statSync()` wrapper Adds extra test that’s left over from an attempted alternative to 14aaa19ecfba000.
'use strict'; var test = require('tap').test var util = require('util') var fs = require('fs') // mock fs.statSync to return signed uids/gids var realStatSync = fs.statSync fs.statSync = function(path) { var stats = realStatSync.call(fs, path) stats.uid = -2 stats.gid = -2 return stats } var gfs = require('../graceful-fs.js') test('graceful fs uses same stats constructor as fs', function (t) { t.equal(gfs.Stats, fs.Stats, 'should reference the same constructor') if (!process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH) { t.equal(fs.statSync(__filename).uid, -2) t.equal(fs.statSync(__filename).gid, -2) } t.equal(gfs.statSync(__filename).uid, 0xfffffffe) t.equal(gfs.statSync(__filename).gid, 0xfffffffe) t.end() }) test('does not throw when async stat fails', function (t) { gfs.stat(__filename + ' this does not exist', function (er, stats) { t.ok(er) t.notOk(stats) t.end() }) }) test('does not throw when async stat fails', function (t) { t.throws(function() { gfs.statSync(__filename + ' this does not exist') }, /ENOENT/) t.end() })
'use strict'; var test = require('tap').test var util = require('util') var fs = require('fs') // mock fs.statSync to return signed uids/gids var realStatSync = fs.statSync fs.statSync = function(path) { var stats = realStatSync.call(fs, path) stats.uid = -2 stats.gid = -2 return stats } var gfs = require('../graceful-fs.js') test('graceful fs uses same stats constructor as fs', function (t) { t.equal(gfs.Stats, fs.Stats, 'should reference the same constructor') if (!process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH) { t.equal(fs.statSync(__filename).uid, -2) t.equal(fs.statSync(__filename).gid, -2) } t.equal(gfs.statSync(__filename).uid, 0xfffffffe) t.equal(gfs.statSync(__filename).gid, 0xfffffffe) t.end() }) test('does not throw when async stat fails', function (t) { fs.stat(__filename + ' this does not exist', function (er, stats) { t.ok(er) t.notOk(stats) t.end() }) })
Refactor code for search in rotated sorted array
/** * @param {number[]} nums * @param {number} target * @return {number} */ const search = function (nums, target) { return searchHelper(nums, target, 0, nums.length - 1); }; function searchHelper(nums, target, begin, end) { if (begin > end) { return -1; } let mid = begin + end >> 1; let midVal = nums[mid]; if (midVal === target) { return mid; } if (target < midVal && target >= nums[begin] || target < midVal && target < nums[begin] && midVal < nums[begin] || target > midVal && target >= nums[begin] && midVal < nums[begin]) { return searchHelper(nums, target, begin, mid - 1); } return searchHelper(nums, target, mid + 1, end); } module.exports = search;
/** * @param {number[]} numbers * @param {number} target * @return {number} */ const search = function (numbers, target) { if (!numbers || numbers.length === 0) { return -1; } return searchHelper(numbers, 0, numbers.length - 1, target); }; function searchHelper(numbers, left, right, target) { if (left > right) { return -1; } let middle = left + right >> 1; if (target === numbers[middle]) { return middle; } if ((numbers[left] < numbers[middle] && target < numbers[middle] && target >= numbers[left]) || (numbers[left] > numbers[middle] && target > numbers[right]) || (numbers[left] > numbers[middle] && target < numbers[middle])) { return searchHelper(numbers, left, middle - 1, target); } // numbers[left] < numbers[middle] && target < numbers[left] // numbers[left] < numbers[middle] && target > numbers[middle] // numbers[left] > numbers[middle] && target > numbers[middle] && target <= numbers[right] return searchHelper(numbers, middle + 1, right, target); } module.exports = search;
Fix big from bayeslite to bdbcontrib.
from bdbcontrib.api import barplot from bdbcontrib.api import cardinality from bdbcontrib.api import draw_crosscat from bdbcontrib.api import estimate_log_likelihood from bdbcontrib.api import heatmap from bdbcontrib.api import histogram from bdbcontrib.api import mi_hist from bdbcontrib.api import nullify from bdbcontrib.api import pairplot from bdbcontrib.api import plot_crosscat_chain_diagnostics """Main bdbcontrib API. The bdbcontrib module servers a sandbox for experimental and semi-stable features that are not yet ready for integreation to the bayeslite repository. """ __all__ = [ 'barplot', 'cardinality', 'draw_crosscat', 'estimate_log_likelihood', 'heatmap', 'histogram', 'mi_hist', 'nullify', 'pairplot', 'plot_crosscat_chain_diagnostics' ]
from bayeslite.api import barplot from bayeslite.api import cardinality from bayeslite.api import draw_crosscat from bayeslite.api import estimate_log_likelihood from bayeslite.api import heatmap from bayeslite.api import histogram from bayeslite.api import mi_hist from bayeslite.api import nullify from bayeslite.api import pairplot from bayeslite.api import plot_crosscat_chain_diagnostics """Main bdbcontrib API. The bdbcontrib module servers a sandbox for experimental and semi-stable features that are not yet ready for integreation to the bayeslite repository. """ __all__ = [ 'barplot', 'cardinality', 'draw_crosscat', 'estimate_log_likelihood', 'heatmap', 'histogram', 'mi_hist', 'nullify', 'pairplot', 'plot_crosscat_chain_diagnostics' ]
Fix argument coercion in `query` to use `queryBuilder` if present.
import Orbit from '../main'; import { assert } from '../lib/assert'; import { extend } from '../lib/objects'; import Query from '../query'; import Source from '../source'; export default { /** Mixes the `Queryable` interface into a source @method extend @param {Object} source - Source to extend @returns {Object} Extended source */ extend(source) { if (source._queryable === undefined) { assert('Queryable interface can only be applied to a Source', source instanceof Source); extend(source, this.interface); } return source; }, interface: { _queryable: true, query(queryOrExpression) { const query = Query.from(queryOrExpression, this.queryBuilder); return this.series('beforeQuery', query) .then(() => { const result = this._query(query); return Orbit.Promise.resolve(result); }) .then((result) => { return this.settle('query', query, result) .then(() => result); }) .catch((error) => { return this.settle('queryFail', query, error) .then(() => { throw error; }); }); } } };
import Orbit from '../main'; import { assert } from '../lib/assert'; import { extend } from '../lib/objects'; import Query from '../query'; import Source from '../source'; export default { /** Mixes the `Queryable` interface into a source @method extend @param {Object} source - Source to extend @returns {Object} Extended source */ extend(source) { if (source._queryable === undefined) { assert('Queryable interface can only be applied to a Source', source instanceof Source); extend(source, this.interface); } return source; }, interface: { _queryable: true, query(queryOrExpression) { const query = Query.from(queryOrExpression); return this.series('beforeQuery', query) .then(() => { const result = this._query(query); return Orbit.Promise.resolve(result); }) .then((result) => { return this.settle('query', query, result) .then(() => result); }) .catch((error) => { return this.settle('queryFail', query, error) .then(() => { throw error; }); }); } } };
Add mouse input to tap input
function TapInput(element, tapRegions) { this.element = typeof element !== 'undefined' ? element : document; this.tapRegions = Array.isArray(tapRegions) ? tapRegions : []; this.upCount = 0; this.listeners = { touchStart: this.tap.bind(this), mouseDown: this.tap.bind(this) }; } TapInput.prototype.add = function(tapRegion) { this.tapRegions.push(tapRegion); }; TapInput.prototype.listen = function() { this.element.addEventListener('touchstart', this.listeners.touchStart); this.element.addEventListener('mousedown', this.listeners.mouseDown); }; TapInput.prototype.tap = function(event) { event.preventDefault(); var isTouchEvent = event.type === 'touchstart'; var x = isTouchEvent ? event.touches[0].clientX : event.clientX; var y = isTouchEvent ? event.touches[0].clientY : event.clientY; for(var i = 0; i < this.tapRegions.length; i += 1) { var tapRegion = this.tapRegions[i]; if(tapRegion.boundingBox.isPointWithin(x, y) && typeof tapRegion.onTap === 'function') { tapRegion.onTap(x, y); } } }; TapInput.prototype.detach = function() { this.element.removeEventListener('touchstart', this.listeners.touchStart); this.element.removeEventListener('mousedown', this.listeners.mouseDown); };
function TapInput(element, tapRegions) { this.element = typeof element !== 'undefined' ? element : document; this.tapRegions = Array.isArray(tapRegions) ? tapRegions : []; this.upCount = 0; this.listeners = { touchStart: this.tap.bind(this) }; } TapInput.prototype.add = function(tapRegion) { this.tapRegions.push(tapRegion); }; TapInput.prototype.listen = function() { this.element.addEventListener('touchstart', this.listeners.touchStart); }; TapInput.prototype.tap = function(event) { event.preventDefault(); var x = event.touches[0].clientX; var y = event.touches[0].clientY; for(var i = 0; i < this.tapRegions.length; i += 1) { var tapRegion = this.tapRegions[i]; if(tapRegion.boundingBox.isPointWithin(x, y) && typeof tapRegion.onTap === 'function') { tapRegion.onTap(x, y); } } }; TapInput.prototype.detach = function() { this.element.removeEventListener('touchstart', this.listeners.touchStart); };
Add divider lines between functions.
'use strict'; const Rx = require('rx'); require('isomorphic-fetch'); //------------------------------------------------------------------------------ const rxResponse = function (promiseResponse) { this._promiseResponse = promiseResponse; this.status = promiseResponse.status; this.ok = promiseResponse.ok; this.statusText = promiseResponse.statusText; this.headers = promiseResponse.headers; this.url = promiseResponse.url; return this; }; //------------------------------------------------------------------------------ /* Disabled for now as I'm not sure what the use case is. Send me a PR with test coverage if you need these. :-) rxResponse.prototype.blob = function () { return Rx.Observable.fromPromise(this._promiseResponse.blob()); }; rxResponse.prototype.arrayBuffer = function () { return Rx.Observable.fromPromise(this._promiseResponse.arrayBuffer()); }; rxResponse.prototype.formData = function () { return Rx.Observable.fromPromise(this._promiseResponse.formData()); }; */ //------------------------------------------------------------------------------ rxResponse.prototype.text = function () { return Rx.Observable.fromPromise(this._promiseResponse.text()); }; //------------------------------------------------------------------------------ rxResponse.prototype.json = function () { return Rx.Observable.fromPromise(this._promiseResponse.json()); }; //------------------------------------------------------------------------------ module.exports = function (url, options) { return Rx.Observable.fromPromise(fetch(url, options)) .map((promiseResponse) => new rxResponse(promiseResponse)); };
'use strict'; const Rx = require('rx'); require('isomorphic-fetch'); const rxResponse = function (promiseResponse) { this._promiseResponse = promiseResponse; this.status = promiseResponse.status; this.ok = promiseResponse.ok; this.statusText = promiseResponse.statusText; this.headers = promiseResponse.headers; this.url = promiseResponse.url; return this; }; /* Disabled for now as I'm not sure what the use case is. Send me a PR with test coverage if you need these. :-) rxResponse.prototype.blob = function () { return Rx.Observable.fromPromise(this._promiseResponse.blob()); }; rxResponse.prototype.arrayBuffer = function () { return Rx.Observable.fromPromise(this._promiseResponse.arrayBuffer()); }; rxResponse.prototype.formData = function () { return Rx.Observable.fromPromise(this._promiseResponse.formData()); }; */ rxResponse.prototype.text = function () { return Rx.Observable.fromPromise(this._promiseResponse.text()); }; rxResponse.prototype.json = function () { return Rx.Observable.fromPromise(this._promiseResponse.json()); }; module.exports = function (url, options) { return Rx.Observable.fromPromise(fetch(url, options)) .map((promiseResponse) => new rxResponse(promiseResponse)); };
Update SUPPORTS_TRANSACTIONS attribute to what is expected by Django 1.2. Patch contributed by Felix Leong. Thanks. Fixes Issue #162. git-svn-id: 7c59d995a3d63779dc3f8cdf6830411bfeeaa67b@109 d4307497-c249-0410-99bd-594fbd7e173e
#!/usr/bin/python2.4 # # Copyright 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging from django.conf import settings from django.db.backends.creation import BaseDatabaseCreation class DatabaseCreation(BaseDatabaseCreation): def create_test_db(self, *args, **kw): """Destroys the test datastore. A new store will be recreated on demand""" # Only needed for Django 1.1, deprecated @ 1.2. settings.DATABASE_SUPPORTS_TRANSACTIONS = False self.connection.settings_dict['SUPPORTS_TRANSACTIONS'] = False self.destroy_test_db() self.connection.use_test_datastore = True self.connection.flush() def destroy_test_db(self, *args, **kw): """Destroys the test datastore files.""" from appengine_django.db.base import destroy_datastore from appengine_django.db.base import get_test_datastore_paths destroy_datastore(*get_test_datastore_paths()) logging.debug("Destroyed test datastore")
#!/usr/bin/python2.4 # # Copyright 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging from django.conf import settings from django.db.backends.creation import BaseDatabaseCreation class DatabaseCreation(BaseDatabaseCreation): def create_test_db(self, *args, **kw): """Destroys the test datastore. A new store will be recreated on demand""" settings.DATABASE_SUPPORTS_TRANSACTIONS = False self.destroy_test_db() self.connection.use_test_datastore = True self.connection.flush() def destroy_test_db(self, *args, **kw): """Destroys the test datastore files.""" from appengine_django.db.base import destroy_datastore from appengine_django.db.base import get_test_datastore_paths destroy_datastore(*get_test_datastore_paths()) logging.debug("Destroyed test datastore")
Remove new lines in if-statement
'use strict'; // MODULES // var pow = require( '@stdlib/math/base/special/pow' ); // MAIN // /** * Returns the variance of an arcsine distribution. * * @param {number} a - minimum support * @param {number} b - maximum support * @returns {number} variance * * @example * var v = variance( 0.0, 1.0 ); * // returns ~0.125 * @example * var v = variance( 4.0, 12.0 ); * // returns 8.0 * @example * var v = variance( -4.0, 4.0 ); * // returns 8.0 * @example * var v = variance( 1.0, -0.1 ); * // returns NaN * @example * var v = variance( -0.1, 1.0 ); * // returns NaN * @example * var v = variance( 2.0, NaN ); * // returns NaN * @example * var v = variance( NaN, 2.0 ); * // returns NaN */ function variance( a, b ) { if ( a >= b ) { return NaN; } return (1.0/8.0) * pow( b-a, 2.0 ); } // end FUNCTION variance() // EXPORTS // module.exports = variance;
'use strict'; // MODULES // var pow = require( '@stdlib/math/base/special/pow' ); // MAIN // /** * Returns the variance of an arcsine distribution. * * @param {number} a - minimum support * @param {number} b - maximum support * @returns {number} variance * * @example * var v = variance( 0.0, 1.0 ); * // returns ~0.125 * @example * var v = variance( 4.0, 12.0 ); * // returns 8.0 * @example * var v = variance( -4.0, 4.0 ); * // returns 8.0 * @example * var v = variance( 1.0, -0.1 ); * // returns NaN * @example * var v = variance( -0.1, 1.0 ); * // returns NaN * @example * var v = variance( 2.0, NaN ); * // returns NaN * @example * var v = variance( NaN, 2.0 ); * // returns NaN */ function variance( a, b ) { if ( a >= b ) { return NaN; } return (1.0/8.0) * pow( b-a, 2.0 ); } // end FUNCTION variance() // EXPORTS // module.exports = variance;
Add various classifications for pypi
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from setuptools import setup version = '1.1' setup(name='treeherder-client', version=version, description="Python library to submit data to treeherder-service", long_description="""\ """, classifiers=[ 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ], keywords='', author='Mozilla Automation and Testing Team', author_email='tools@lists.mozilla.org', url='https://github.com/mozilla/treeherder-client', license='MPL', packages=['thclient'], zip_safe=False, install_requires=['oauth2'], test_suite='thclient.tests', tests_require=["mock"], )
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from setuptools import setup version = '1.1' setup(name='treeherder-client', version=version, description="Python library to submit data to treeherder-service", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='Mozilla Automation and Testing Team', author_email='tools@lists.mozilla.org', url='https://github.com/mozilla/treeherder-client', license='MPL', packages=['thclient'], zip_safe=False, install_requires=['oauth2'], test_suite='thclient.tests', tests_require=["mock"], )
Fix an assertion due to a related view rename
<?php namespace Tests\Feature; use Tests\TestCase; use Illuminate\Foundation\Testing\WithoutMiddleware; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; use App; class LoginTest extends TestCase { use DatabaseMigrations; public function testBasicTest() { $this->get('/')->assertRedirect('/login'); $this->get('/', [ 'X-Requested-With' => 'XMLHttpRequest' ]) ->assertStatus(401); } public function testLoginForm() { $response = $this->get('/login'); $response->assertViewIs('auth.login'); $response->assertStatus(200); } public function testLoggedIn() { $user = factory(App\User::class)->create(); $response = $this->actingAs($user)->get('/'); $response->assertViewIs('dashboard'); $response->assertStatus(200); } public function testLogout() { $user = factory(App\User::class)->create(); $this->actingAs($user)->post('/logout')->assertRedirect('/'); } }
<?php namespace Tests\Feature; use Tests\TestCase; use Illuminate\Foundation\Testing\WithoutMiddleware; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; use App; class LoginTest extends TestCase { use DatabaseMigrations; public function testBasicTest() { $this->get('/')->assertRedirect('/login'); $this->get('/', [ 'X-Requested-With' => 'XMLHttpRequest' ]) ->assertStatus(401); } public function testLoginForm() { $response = $this->get('/login'); $response->assertViewIs('auth.login'); $response->assertStatus(200); } public function testLoggedIn() { $user = factory(App\User::class)->create(); $response = $this->actingAs($user)->get('/'); $response->assertViewIs('home'); $response->assertStatus(200); } public function testLogout() { $user = factory(App\User::class)->create(); $this->actingAs($user)->post('/logout')->assertRedirect('/'); } }
Fix gamestates not being shuffled anymore in tests
<?php namespace lucidtaz\minimax\tests\tictactoe; /** * TicTacToe state that gives the possible decisions in a random order * * This is to rule out any tests that accidentally succeed because of * coincidence. * * Note that this approach uses inheritance rather than applying the arguably * more sensible Decorator pattern. The reason for this is that the code * (currently, perhaps it will be solved) it not really strict with regards to * typing, and will call methods on the TicTacToe GameState class that are not * defined in the GameState interface, such as makeMove(). Until such issues are * resolved by an interface redesign, we must resort to inheritance. * * Furthermore, a decorated object may lose its decoration when passing out * references of itself to other code. This makes the pattern more hassle than * it's worth. */ class ShuffledDecisionsGameState extends GameState { public function getPossibleMoves(): array { $moves = parent::getPossibleMoves(); shuffle($moves); return $moves; } }
<?php namespace lucidtaz\minimax\tests\tictactoe; /** * TicTacToe state that gives the possible decisions in a random order * * This is to rule out any tests that accidentally succeed because of * coincidence. * * Note that this approach uses inheritance rather than applying the arguably * more sensible Decorator pattern. The reason for this is that the code * (currently, perhaps it will be solved) it not really strict with regards to * typing, and will call methods on the TicTacToe GameState class that are not * defined in the GameState interface, such as makeMove(). Until such issues are * resolved by an interface redesign, we must resort to inheritance. * * Furthermore, a decorated object may lose its decoration when passing out * references of itself to other code. This makes the pattern more hassle than * it's worth. */ class ShuffledDecisionsGameState extends GameState { public function getDecisions(): array { $decisions = parent::getDecisions(); shuffle($decisions); return $decisions; } }
Fix for non-strict token check
<?php /* |-------------------------------------------------------------------------- | Authentication Filters |-------------------------------------------------------------------------- | | The following filters are used to verify that the user of the current | session is logged into this application. The "basic" filter easily | integrates HTTP Basic authentication for quick, simple checking. | */ Route::filter('sentry_check', function() { if (!Sentry::check()) return Redirect::to('/'); }); Route::filter('project_check', function($route) { $user = Sentry::getUser(); $project_id = $route->getParameter('project_id'); $project = Project::where('user_id', $user->id)->where('id', $project_id)->first(); if(null === $project) { return Redirect::to('404'); } }); /* |-------------------------------------------------------------------------- | CSRF Protection Filter |-------------------------------------------------------------------------- | | The CSRF filter is responsible for protecting your application against | cross-site request forgery attacks. If this special token in a user | session does not match the one given in this request, we'll bail. | */ Route::filter('csrf', function() { if (Session::token() !== Input::get('_token')) { throw new Illuminate\Session\TokenMismatchException; } });
<?php /* |-------------------------------------------------------------------------- | Authentication Filters |-------------------------------------------------------------------------- | | The following filters are used to verify that the user of the current | session is logged into this application. The "basic" filter easily | integrates HTTP Basic authentication for quick, simple checking. | */ Route::filter('sentry_check', function() { if (!Sentry::check()) return Redirect::to('/'); }); Route::filter('project_check', function($route) { $user = Sentry::getUser(); $project_id = $route->getParameter('project_id'); $project = Project::where('user_id', $user->id)->where('id', $project_id)->first(); if(null === $project) { return Redirect::to('404'); } }); /* |-------------------------------------------------------------------------- | CSRF Protection Filter |-------------------------------------------------------------------------- | | The CSRF filter is responsible for protecting your application against | cross-site request forgery attacks. If this special token in a user | session does not match the one given in this request, we'll bail. | */ Route::filter('csrf', function() { if (Session::token() != Input::get('_token')) { throw new Illuminate\Session\TokenMismatchException; } });