text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Correct the type of exception thrown when bad geometry data passed to the constructor
package fgis.server.support.geojson; import java.util.Map; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.json.JsonValue; import org.geolatte.geom.Envelope; import org.geolatte.geom.Geometry; import org.geolatte.geom.GeometryCollection; import org.geolatte.geom.crs.CrsId; public final class GjGeometry extends GjElement { @Nonnull private final Geometry _geometry; @SuppressWarnings( "ConstantConditions" ) public GjGeometry( @Nonnull final Geometry geometry, @Nullable final CrsId crsId, @Nullable final Envelope bbox, @Nullable final Map<String, JsonValue> additionalProperties ) { super( crsId, bbox, additionalProperties ); if ( null == geometry ) { throw new IllegalArgumentException( "geometry is null" ); } if ( geometry instanceof GeometryCollection ) { throw new IllegalArgumentException( "geometry is a GeometryCollection" ); } _geometry = geometry; } @Nonnull public Geometry getGeometry() { return _geometry; } @Override protected boolean isPropertyAllowed( final String name ) { return super.isPropertyAllowed( name ) && !( "coordinates".equals( name ) ); } }
package fgis.server.support.geojson; import java.util.Map; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.json.JsonValue; import org.geolatte.geom.Envelope; import org.geolatte.geom.Geometry; import org.geolatte.geom.GeometryCollection; import org.geolatte.geom.crs.CrsId; public final class GjGeometry extends GjElement { @Nonnull private final Geometry _geometry; @SuppressWarnings( "ConstantConditions" ) public GjGeometry( @Nonnull final Geometry geometry, @Nullable final CrsId crsId, @Nullable final Envelope bbox, @Nullable final Map<String, JsonValue> additionalProperties ) { super( crsId, bbox, additionalProperties ); if ( null == geometry ) { throw new IllegalArgumentException( "geometry is null" ); } if ( geometry instanceof GeometryCollection ) { throw new IllegalStateException( "geometry is a GeometryCollection" ); } _geometry = geometry; } @Nonnull public Geometry getGeometry() { return _geometry; } @Override protected boolean isPropertyAllowed( final String name ) { return super.isPropertyAllowed( name ) && !( "coordinates".equals( name ) ); } }
Move the error to the left of the field
<form action="<?php echo url_for('account/login') ?>" method="POST"> <?php echo $form['_csrf_token']; ?> <div id="password_field"> <?php echo $form['password']->renderError() ?> <?php echo $form['password']->renderLabel() ?>: <?php echo $form['password'] ?> </div> <div id="remember_field"> <?php echo $form['remember_me']->renderError() ?> <?php echo $form['remember_me'] ?> <?php echo $form['remember_me']->renderLabel(null, array('id' => 'remember_label')) ?> </div> <div class="links"> <?php echo link_to('Change',"account/password"); ?> &middot; <?php echo link_to('I forget',"http://limecast.com/tracker/reset-password"); ?> </div> <input type="submit" class="submit" value="Sign in" /> </form>
<form action="<?php echo url_for('account/login') ?>" method="POST"> <div id="password_field"> <?php echo $form['password']->renderLabel() ?>: <?php echo $form['_csrf_token']; ?> <?php echo $form['password'] ?> <?php echo $form['password']->renderError() ?> </div> <div id="remember_field"> <?php echo $form['remember_me'] ?> <?php echo $form['remember_me']->renderLabel(null, array('id' => 'remember_label')) ?> <?php echo $form['remember_me']->renderError() ?> </div> <div class="links"> <?php echo link_to('Change',"account/password"); ?> &middot; <?php echo link_to('I forget',"http://limecast.com/tracker/reset-password"); ?> </div> <input type="submit" class="submit" value="Sign in" /> </form>
Make Reset button a warning button.
<?php /** * @file * template.php */ /** * Implements hook_preprocess_HOOK(). */ function bootstrap_serchilo_preprocess_block(&$vars) { switch ($vars['block_html_id']) { case 'block-serchilo-namespaces': // Put a well around namespaces block. $vars['classes_array'][] = 'well'; $vars['classes_array'][] = 'well-sm'; break; } } /** * Implements hook_preprocess_HOOK(). */ function bootstrap_serchilo_preprocess_button(&$vars) { switch ($vars['element']['#id']) { case 'edit-submit-shortcuts': // Make Go button a primary button. $vars['element']['#attributes']['class'][] = 'btn-primary'; break; case 'edit-reset': // Make Reset button a warning button. $vars['element']['#attributes']['class'][] = 'btn-warning'; break; } }
<?php /** * @file * template.php */ /** * Implements hook_preprocess_HOOK(). */ function bootstrap_serchilo_preprocess_block(&$vars) { switch ($vars['block_html_id']) { case 'block-serchilo-namespaces': // Put a well around namespaces block. $vars['classes_array'][] = 'well'; $vars['classes_array'][] = 'well-sm'; break; } } /** * Implements hook_preprocess_HOOK(). */ function bootstrap_serchilo_preprocess_button(&$vars) { switch ($vars['element']['#id']) { case 'edit-submit-shortcuts': // Make Go button a primary button. $vars['element']['#attributes']['class'][] = 'btn-primary'; break; } }
Fix logical operator when testing for architecture.
module.exports = Register; function Register(pluginPath) { electron = require('electron') const app = electron.app const isWindows = process.platform === 'win32'; const isMac = process.platform === 'darwin'; var ppapiPath = ''; if (isWindows) { if (process.arch === 'x64') ppapiPath = __dirname + '\\..\\bin\\x64\\PepperPlugin.dll'; else ppapiPath = __dirname + '\\..\\bin\\Win32\\PepperPlugin.dll'; } if (isMac) { if (process.arch === 'x64') ppapiPath = __dirname + '/../bin/mac/libPepperPlugin.so'; else ppapiPath = __dirname + '/../bin/mac/libPepperPlugin.so'; } if (pluginPath) { if (isWindows) { ppapiPath = pluginPath + '\\PepperPlugin.dll'; } if (isMac) { ppapiPath = pluginPath + '\\libPepperPlugin.so'; } } //console.log('PPAPI path ' + ppapiPath + ';application/electron-dotnet'); app.commandLine.appendSwitch('register-pepper-plugins', ppapiPath + ';application/electron-dotnet'); }
module.exports = Register; function Register(pluginPath) { electron = require('electron') const app = electron.app const isWindows = process.platform === 'win32'; const isMac = process.platform === 'darwin'; var ppapiPath = ''; if (isWindows) { if (process.arch = 'x64') ppapiPath = __dirname + '\\..\\bin\\x64\\PepperPlugin.dll'; else ppapiPath = __dirname + '\\..\\bin\\Win32\\PepperPlugin.dll'; } if (isMac) { if (process.arch = 'x64') ppapiPath = __dirname + '/../bin/mac/libPepperPlugin.so'; else ppapiPath = __dirname + '/../bin/mac/libPepperPlugin.so'; } if (pluginPath) { if (isWindows) { ppapiPath = pluginPath + '\\PepperPlugin.dll'; } if (isMac) { ppapiPath = pluginPath + '\\libPepperPlugin.so'; } } //console.log('PPAPI path ' + ppapiPath + ';application/electron-dotnet'); app.commandLine.appendSwitch('register-pepper-plugins', ppapiPath + ';application/electron-dotnet'); }
Add Repeater Test to Core Suite
package jpower.core.test; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ AlphabetTest.class, ConditionTest.class, ConfigurationTest.class, FactoryTest.class, InternalTest.class, IOUtilsTest.class, LoadTest.class, MultiMapTest.class, PowerLoaderTest.class, RandomTest.class, ThreadUtilsTest.class, ByteUtilsTest.class, WorkerTest.class, GenericSnifferTest.class, OperatingSystemTest.class, CallUtilsTest.class, ServiceTest.class, WrapperTest.class, RepeaterTest.class }) public class CoreTestSuite { }
package jpower.core.test; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ AlphabetTest.class, ConditionTest.class, ConfigurationTest.class, FactoryTest.class, InternalTest.class, IOUtilsTest.class, LoadTest.class, MultiMapTest.class, PowerLoaderTest.class, RandomTest.class, ThreadUtilsTest.class, ByteUtilsTest.class, WorkerTest.class, GenericSnifferTest.class, OperatingSystemTest.class, CallUtilsTest.class, ServiceTest.class, WrapperTest.class }) public class CoreTestSuite { }
Update to include typing, cleanup docstrings and code
# -*- encoding: utf-8 -*- """ The pamqp.body module contains the Body class which is used when unmarshaling body frames. When dealing with content frames, the message body will be returned from the library as an instance of the body class. """ import typing class ContentBody: """ContentBody carries the value for an AMQP message body frame""" def __init__(self, value: typing.Optional[bytes] = None): """Create a new instance of a ContentBody object""" self.value = value def __len__(self) -> int: """Return the length of the content body value""" return len(self.value) if self.value else 0 def marshal(self) -> bytes: """Return the marshaled content body. This method is here for API compatibility, there is no special marshaling for the payload in a content frame. """ return self.value def unmarshal(self, data: bytes) -> typing.NoReturn: """Apply the data to the object. This method is here for API compatibility, there is no special unmarhsaling for the payload in a content frame. """ self.value = data
# -*- encoding: utf-8 -*- """ The pamqp.body module contains the Body class which is used when unmarshaling body frames. When dealing with content frames, the message body will be returned from the library as an instance of the body class. """ class ContentBody(object): """ContentBody carries the value for an AMQP message body frame""" name = 'ContentBody' def __init__(self, value=None): """Create a new instance of a ContentBody object, passing in the value of the message body :param str|unicode|bytes value: The content body """ self.value = value def __len__(self): """Return the length of the content body value :rtype: int """ return len(self.value) def marshal(self): """Return the marshaled content body. This method is here for API compatibility, there is no special marhsaling for the payload in a content frame. :rtype: str|unicode|bytes """ return self.value def unmarshal(self, data): """Apply the data to the object. This method is here for API compatibility, there is no special unmarhsaling for the payload in a content frame. :rtype: str|unicode|bytes """ self.value = data
Set GLib prgname and application name This makes Mopidy properly show up in pulseaudio as "Mopidy" instead of "python*"
from __future__ import absolute_import, print_function, unicode_literals import sys import textwrap try: import gi gi.require_version('Gst', '1.0') from gi.repository import GLib, GObject, Gst except ImportError: print(textwrap.dedent(""" ERROR: A GObject Python package was not found. Mopidy requires GStreamer to work. GStreamer is a C library with a number of dependencies itself, and cannot be installed with the regular Python tools like pip. Please see http://docs.mopidy.com/en/latest/installation/ for instructions on how to install the required dependencies. """)) raise else: Gst.init([]) gi.require_version('GstPbutils', '1.0') from gi.repository import GstPbutils GLib.set_prgname('mopidy') GLib.set_application_name('Mopidy') REQUIRED_GST_VERSION = (1, 2, 3) if Gst.version() < REQUIRED_GST_VERSION: sys.exit( 'ERROR: Mopidy requires GStreamer >= %s, but found %s.' % ( '.'.join(map(str, REQUIRED_GST_VERSION)), Gst.version_string())) __all__ = [ 'GLib', 'GObject', 'Gst', 'GstPbutils', 'gi', ]
from __future__ import absolute_import, print_function, unicode_literals import sys import textwrap try: import gi gi.require_version('Gst', '1.0') from gi.repository import GLib, GObject, Gst except ImportError: print(textwrap.dedent(""" ERROR: A GObject Python package was not found. Mopidy requires GStreamer to work. GStreamer is a C library with a number of dependencies itself, and cannot be installed with the regular Python tools like pip. Please see http://docs.mopidy.com/en/latest/installation/ for instructions on how to install the required dependencies. """)) raise else: Gst.init([]) gi.require_version('GstPbutils', '1.0') from gi.repository import GstPbutils REQUIRED_GST_VERSION = (1, 2, 3) if Gst.version() < REQUIRED_GST_VERSION: sys.exit( 'ERROR: Mopidy requires GStreamer >= %s, but found %s.' % ( '.'.join(map(str, REQUIRED_GST_VERSION)), Gst.version_string())) __all__ = [ 'GLib', 'GObject', 'Gst', 'GstPbutils', 'gi', ]
Use the existing default name.
from django.db import models from django.contrib.auth.models import User from util.session import get_or_generate_session_name from util.session import DEFAULT_SESSION_NAME_PREFIX class Session(models.Model): name = models.CharField(max_length=255) user = models.ForeignKey(User, blank=True, null=True) started_at = models.DateTimeField('started at', auto_now_add=True) # On Python 3: def __str__(self): def __unicode__(self): return self.name def save(self, *args, **kwargs): existing_session_names = Session.objects.filter(name__startswith=DEFAULT_SESSION_NAME_PREFIX, user=self.user).only('name') self.name = get_or_generate_session_name(self.name, existing_session_names) super(Session, self).save(*args, **kwargs) # Call the "real" save() method. class Spec(models.Model): code = models.TextField() session = models.ForeignKey(Session) author = models.ForeignKey(User, verbose_name='The author of this last update.') tests_passed = models.NullBooleanField(default=False) saved_at = models.DateTimeField(auto_now_add=True) class Meta: get_latest_by = 'saved_at'
from django.db import models from django.contrib.auth.models import User from util.session import get_or_generate_session_name class Session(models.Model): name = models.CharField(max_length=255) user = models.ForeignKey(User, blank=True, null=True) started_at = models.DateTimeField('started at', auto_now_add=True) # On Python 3: def __str__(self): def __unicode__(self): return self.name def save(self, *args, **kwargs): existing_session_names = Session.objects.filter(name__startswith=self.UNTITLED_PREFIX, user=self.user).only('name') self.name = get_or_generate_session_name(self.name, existing_session_names) super(Session, self).save(*args, **kwargs) # Call the "real" save() method. class Spec(models.Model): code = models.TextField() session = models.ForeignKey(Session) author = models.ForeignKey(User, verbose_name='The author of this last update.') tests_passed = models.NullBooleanField(default=False) saved_at = models.DateTimeField(auto_now_add=True) class Meta: get_latest_by = 'saved_at'
Add basic support for MSYS, CYGWIN, and MINGW
# -*- coding: utf-8 -*- import os import sys import ctypes import platform if platform.system().startswith(('Windows', 'MSYS', 'CYGWIN', 'MINGW')): libbase = os.path.join(os.path.dirname(__file__), 'cppinterface', 'lib') lib32 = os.path.join(libbase, 'intel32') lib64 = os.path.join(libbase, 'amd64') from glob import glob try: if ctypes.sizeof(ctypes.c_voidp) == 4: dllfile = glob(lib32 + '/*.dll')[0] else: dllfile = glob(lib64 + '/*.dll')[0] ctypes.CDLL(dllfile) except: pass sys.path.append(os.path.join(os.path.dirname(__file__), 'cppinterface')) from amplpython import * from amplpython import _READTABLE, _WRITETABLE
# -*- coding: utf-8 -*- import os import sys import ctypes import platform if platform.system() == 'Windows': libbase = os.path.join(os.path.dirname(__file__), 'cppinterface', 'lib') lib32 = os.path.join(libbase, 'intel32') lib64 = os.path.join(libbase, 'amd64') from glob import glob try: if ctypes.sizeof(ctypes.c_voidp) == 4: dllfile = glob(lib32 + '/*.dll')[0] else: dllfile = glob(lib64 + '/*.dll')[0] ctypes.CDLL(dllfile) except: pass sys.path.append(os.path.join(os.path.dirname(__file__), 'cppinterface')) from amplpython import * from amplpython import _READTABLE, _WRITETABLE
Fix can_access allowing admin all possible boards
var authcommon = require('../authcommon'), common = require('../common'), config = require('../config'), db = require('../db'); exports.can_access = function (ident, board) { if (board == 'graveyard' && is_admin_ident(ident)) return true; return db.is_board(board); }; function is_mod_ident(ident) { return ident && (ident.auth === 'Admin' || ident.auth === 'Moderator'); } exports.is_mod_ident = is_mod_ident; function is_admin_ident(ident) { return ident && ident.auth === 'Admin'; } exports.is_admin_ident = is_admin_ident; function denote_priv(header, data) { if (data.priv) header.push(' (priv)'); return header; } exports.augment_oneesama = function (oneeSama, ident) { if (is_mod_ident(ident)) oneeSama.hook('header', authcommon.ip_mnemonic); if (is_admin_ident(ident)) oneeSama.hook('header', denote_priv); };
var authcommon = require('../authcommon'), common = require('../common'), config = require('../config'), db = require('../db'); exports.can_access = function (ident, board) { if (is_admin_ident(ident)) return true; // including graveyard return db.is_board(board); }; function is_mod_ident(ident) { return ident && (ident.auth === 'Admin' || ident.auth === 'Moderator'); } exports.is_mod_ident = is_mod_ident; function is_admin_ident(ident) { return ident && ident.auth === 'Admin'; } exports.is_admin_ident = is_admin_ident; function denote_priv(header, data) { if (data.priv) header.push(' (priv)'); return header; } exports.augment_oneesama = function (oneeSama, ident) { if (is_mod_ident(ident)) oneeSama.hook('header', authcommon.ip_mnemonic); if (is_admin_ident(ident)) oneeSama.hook('header', denote_priv); };
Correct usage of PHP shorttag. git-svn-id: d0e296eae3c99886147898d36662a67893ae90b2@3651 653ae4dd-d31e-0410-96ef-6bf7bf53c507
<div<?php echo isset( $class ) ? " class=\"$class\"" : ''; ?><?php echo isset( $id ) ? " id=\"$id\"" : ''; ?>> <label<?php if ( isset( $label_title ) ) { ?> title="<?php echo $label_title; ?>"<?php } else { echo ( isset( $title ) ? " title=\"$title\"" : '' ); } ?> for="<?php echo $field; ?>"><?php echo $this->caption; ?></label> <input<?php if ( isset( $control_title ) ) { ?> title="<?php echo $control_title; ?>"<?php } else { echo ( isset( $title ) ? " title=\"$title\"" : '' ); } ?> type="text" id="<?php echo $field; ?>" name="<?php echo $field; ?>" value="<?php echo htmlspecialchars( $value ); ?>"> <?php $control->errors_out( '<li>%s</li>', '<ul class="error">%s</ul>' ); ?> </div>
<div<?php echo isset( $class ) ? " class=\"$class\"" : ''; ?><? echo isset( $id ) ? " id=\"$id\"" : ''; ?>> <label<?php if ( isset( $label_title ) ) { ?> title="<?php echo $label_title; ?>"<?php } else { echo ( isset( $title ) ? " title=\"$title\"" : '' ); } ?> for="<?php echo $field; ?>"><?php echo $this->caption; ?></label> <input<?php if ( isset( $control_title ) ) { ?> title="<?php echo $control_title; ?>"<?php } else { echo ( isset( $title ) ? " title=\"$title\"" : '' ); } ?> type="text" id="<?php echo $field; ?>" name="<?php echo $field; ?>" value="<?php echo htmlspecialchars( $value ); ?>"> <?php $control->errors_out( '<li>%s</li>', '<ul class="error">%s</ul>' ); ?> </div>
Fix plugin not taking into account opening of unsaved buffers and some refactoring
import sublime_plugin from editorconfig import get_properties, EditorConfigError LINE_ENDINGS = { 'lf': 'Unix', 'crlf': 'Windows', 'cr': 'CR' } class EditorConfig(sublime_plugin.EventListener): def on_load(self, view): path = view.file_name() if not path: return try: config = get_properties(path) except EditorConfigError: print 'Error occurred while getting EditorConfig properties' else: if config: settings = view.settings() window = view.window() end_of_line = config.get('end_of_line') indent_style = config.get('indent_style') indent_size = config.get('indent_size') # Indent type if indent_style == 'tab': window.run_command('unexpand_tabs', {'set_translate_tabs': False}) if indent_style == 'space': window.run_command('expand_tabs', {'set_translate_tabs': True}) # Indent size if indent_size: settings.set('tab_size', int(indent_size)) # EOL if end_of_line: view.set_line_endings(LINE_ENDINGS[end_of_line])
import sublime_plugin from editorconfig import get_properties, EditorConfigError LINE_ENDINGS = { 'lf': 'Unix', 'crlf': 'Windows', 'cr': 'CR' } class EditorConfig(sublime_plugin.EventListener): def on_load(self, view): try: config = get_properties(view.file_name()) except EditorConfigError: print 'Error occurred while getting EditorConfig properties' else: if config: settings = view.settings() # EOL view.set_line_endings(LINE_ENDINGS[config['end_of_line']]) # Indent type settings.set('translate_tabs_to_spaces', config['indent_style'] == 'space') # Indent size settings.set('tab_size', int(config['indent_size'])) else: print 'There seems to be an error with your .editorconfig file'
Support for floating admin controls
<?=form_open_multipart()?> <p> <strong>1. CSV File</strong> </p> <p> This should be a *.csv file which contains 3 columns: old URL, new URL, type of redirect (301 or 302). </p> <p> <input type="file" name="upload" style="border: 1px solid #CCC;padding: 1rem; width: 100%;margin-bottom: 1rem"> </p> <p> <strong>2. Action</strong> </p> <p> Define how to process the redirects. </p> <p> <select name="action" class="select2"> <option value="APPEND">Append - add new items in the CSV to the database</option> <option value="REPLACE">Replace - replace the items in the database with those in the CSV</option> <option value="REMOVE">Remove - remove items in the CSV from the database</option> </select> </p> <hr> <div class="admin-floating-controls"> <button type="submit" class="btn btn-primary"> Save Changes </button> </div> <?=form_close()?>
<?=form_open_multipart()?> <p> <strong>1. CSV File</strong> </p> <p> This should be a *.csv file which contains 3 columns: old URL, new URL, type of redirect (301 or 302). </p> <p> <input type="file" name="upload" style="border: 1px solid #CCC;padding: 1rem; width: 100%;margin-bottom: 1rem"> </p> <p> <strong>2. Action</strong> </p> <p> Define how to process the redirects. </p> <p> <select name="action" class="select2"> <option value="APPEND">Append - add new items in the CSV to the database</option> <option value="REPLACE">Replace - replace the items in the database with those in the CSV</option> <option value="REMOVE">Remove - remove items in the CSV from the database</option> </select> </p> <hr> <p> <button type="submit" class="btn btn-primary"> Upload </button> </p> <?=form_close()?>
Move register on /user/ url
angular.module('mewpipe') .config(function(toastrConfig,$resourceProvider,$authProvider,$httpProvider,Config){ /** * Toastr */ angular.extend(toastrConfig, { positionClass : 'toast-bottom-right', closeButton : true, }); /** * Resource Provider */ $resourceProvider.defaults.stripTrailingSlashes = false; /** * HTTP Provider */ $httpProvider.interceptors.push('errorsInterceptor'); $httpProvider.interceptors.push('tokenInterceptor'); /** * Auth Provider */ $authProvider.loginOnSignup = false; $authProvider.baseUrl = Config.server.url + ':' + Config.server.port + '/api'; $authProvider.loginUrl = '/login/'; $authProvider.signupUrl = '/user/'; $authProvider.loginRoute = '/login'; $authProvider.signupRoute = '/register'; $authProvider.unlinkUrl = '/logout'; $authProvider.unlinkMethod = 'post'; $authProvider.facebook({ url : '/facebook', clientId : '950692341649325' }); });
angular.module('mewpipe') .config(function(toastrConfig,$resourceProvider,$authProvider,$httpProvider,Config){ /** * Toastr */ angular.extend(toastrConfig, { positionClass : 'toast-bottom-right', closeButton : true, }); /** * Resource Provider */ $resourceProvider.defaults.stripTrailingSlashes = false; /** * HTTP Provider */ $httpProvider.interceptors.push('errorsInterceptor'); $httpProvider.interceptors.push('tokenInterceptor'); /** * Auth Provider */ $authProvider.baseUrl = Config.server.url + ':' + Config.server.port + '/api'; $authProvider.loginUrl = '/login/'; $authProvider.signupUrl = '/register/'; $authProvider.loginRoute = '/login'; $authProvider.signupRoute = '/register'; $authProvider.unlinkUrl = '/logout'; $authProvider.unlinkMethod = 'post'; $authProvider.facebook({ url : '/facebook', clientId : '950692341649325' }); });
Use success helper, because we can!
<?php namespace Studio\Console; use Studio\Package; use Studio\Config\Config; use Studio\Shell\Shell; use Symfony\Component\Console\Input\InputArgument; class LoadCommand extends BaseCommand { protected $config; public function __construct(Config $config) { parent::__construct(); $this->config = $config; } protected function configure() { $this ->setName('load') ->setDescription('Load a package to be managed with Studio') ->addArgument( 'path', InputArgument::REQUIRED, 'The path where the package files are located' ); } protected function fire() { $package = Package::fromFolder($this->input->getArgument('path')); $this->config->addPackage($package); $this->output->success('Package loaded successfully.'); } }
<?php namespace Studio\Console; use Studio\Package; use Studio\Config\Config; use Studio\Shell\Shell; use Symfony\Component\Console\Input\InputArgument; class LoadCommand extends BaseCommand { protected $config; public function __construct(Config $config) { parent::__construct(); $this->config = $config; } protected function configure() { $this ->setName('load') ->setDescription('Load a package to be managed with Studio') ->addArgument( 'path', InputArgument::REQUIRED, 'The path where the package files are located' ); } protected function fire() { $package = Package::fromFolder($this->input->getArgument('path')); $this->config->addPackage($package); $this->output->note('Package loaded successfully.'); } }
public: Make code class sort oder deterministic
package ch.difty.scipamato.public_.persistence.codeclass; import static ch.difty.scipamato.public_.db.tables.CodeClass.CODE_CLASS; import java.util.List; import org.jooq.DSLContext; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Repository; import ch.difty.scipamato.common.TranslationUtils; import ch.difty.scipamato.public_.entity.CodeClass; @Repository @CacheConfig(cacheNames = "codeClasses") public class JooqCodeClassRepo implements CodeClassRepository { private final DSLContext dslContext; public JooqCodeClassRepo(final DSLContext dslContext) { this.dslContext = dslContext; } @Override @Cacheable public List<CodeClass> find(final String languageCode) { final String lang = TranslationUtils.trimLanguageCode(languageCode); return dslContext .select(CODE_CLASS.CODE_CLASS_ID, CODE_CLASS.LANG_CODE, CODE_CLASS.NAME, CODE_CLASS.DESCRIPTION, CODE_CLASS.CREATED, CODE_CLASS.LAST_MODIFIED, CODE_CLASS.VERSION) .from(CODE_CLASS) .where(CODE_CLASS.LANG_CODE.eq(lang)) .orderBy(CODE_CLASS.CODE_CLASS_ID) .fetchInto(CodeClass.class); } }
package ch.difty.scipamato.public_.persistence.codeclass; import static ch.difty.scipamato.public_.db.tables.CodeClass.CODE_CLASS; import java.util.List; import org.jooq.DSLContext; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Repository; import ch.difty.scipamato.common.TranslationUtils; import ch.difty.scipamato.public_.entity.CodeClass; @Repository @CacheConfig(cacheNames = "codeClasses") public class JooqCodeClassRepo implements CodeClassRepository { private final DSLContext dslContext; public JooqCodeClassRepo(final DSLContext dslContext) { this.dslContext = dslContext; } @Override @Cacheable public List<CodeClass> find(final String languageCode) { final String lang = TranslationUtils.trimLanguageCode(languageCode); return dslContext .select(CODE_CLASS.CODE_CLASS_ID, CODE_CLASS.LANG_CODE, CODE_CLASS.NAME, CODE_CLASS.DESCRIPTION, CODE_CLASS.CREATED, CODE_CLASS.LAST_MODIFIED, CODE_CLASS.VERSION) .from(CODE_CLASS) .where(CODE_CLASS.LANG_CODE.eq(lang)) .fetchInto(CodeClass.class); } }
Update css and markup styles to suit new animation
import React from 'react'; import PropTypes from 'prop-types'; import shortid from 'shortid'; import styled, { keyframes } from 'styled-components'; const stagger = keyframes` to { opacity: 1; transform: translateY(0%); } `; const Segments = styled.div` font-family: 'Playfair Display', serif; font-size: 38px; line-height: 1.25; `; const Segment = styled.span` display: inline-block; overflow-y: hidden; span { animation-name: ${stagger}; animation-fill-mode: forwards; display: inline-block; opacity: 0; transform: translateY(100%); white-space: pre-wrap; } `; const MotionTypography = props => { const styles = index => ({ animationDuration: `${props.animationDuration}ms`, animationDelay: `${props.animationDelay * index}s`, }); return ( <Segments> {[...props.title].map((segment, index) => ( <Segment key={shortid.generate()} style={styles(index)}> <span style={styles(index)}>{segment}</span> </Segment> ))} </Segments> ); }; MotionTypography.propTypes = { animationDelay: PropTypes.number, animationDuration: PropTypes.number, title: PropTypes.string, }; MotionTypography.defaultProps = { animationDelay: 0.025, animationDuration: 100, title: '', }; export default MotionTypography;
import React from 'react'; import PropTypes from 'prop-types'; import shortid from 'shortid'; import styled, { keyframes } from 'styled-components'; const stagger = keyframes` to { opacity: 1; transform: translateY(0%); } `; const Segments = styled.div` font-family: 'Playfair Display', serif; font-size: 38px; overflow-y: hidden; line-height: 1.25; `; const Segment = styled.span` animation-duration: ${props => `${props.animationDuration}ms`}; animation-name: ${stagger}; animation-fill-mode: forwards; display: inline-block; opacity: 0; transform: translateY(100%); white-space: pre-wrap; `; const MotionTypography = props => ( <Segments> {[...props.title].map((segment, index) => ( <Segment key={shortid.generate()} animationDuration={props.animationDuration} style={{ animationDelay: `${props.animationDelay * index}s`, }} > {segment} </Segment> ))} </Segments> ); MotionTypography.propTypes = { animationDelay: PropTypes.number, animationDuration: PropTypes.number, title: PropTypes.string, }; MotionTypography.defaultProps = { animationDelay: 0.025, animationDuration: 100, title: '', }; export default MotionTypography;
Remove unused dependencies from toolbar component
'use strict'; /** * @module opa */ (function(app) { /** * Manages opaToolbar component. * * @class OpaToolbarController * @constructor * @param {Object} $mdMedia AngularJS Material service to evaluate media queries */ function OpaToolbarController($mdMedia) { var ctrl = this; Object.defineProperties(ctrl, { /** * AngularJS Material $mdMedia service. * * @property $mdMedia * @type Object * @final */ $mdMedia: { value: $mdMedia } }); } app.controller('OpaToolbarController', OpaToolbarController); OpaToolbarController.$inject = ['$mdMedia']; })(angular.module('opa'));
'use strict'; /** * @module opa */ (function(app) { /** * Manages opaToolbar component. * * @class OpaToolbarController * @constructor * @param {Object} $scope opa-toolbar isolated scope * @param {Object} $window JQLite element of the window * @param {Object} $mdMedia AngularJS Material service to evaluate media queries * @param {Object} $mdSidenav AngularJS Material service to manipulate sidenav directives * @param {Object} opaUserFactory User factory to manage authenticated user */ function OpaToolbarController($scope, $window, $mdMedia, $mdSidenav, opaUserFactory) { var ctrl = this; Object.defineProperties(ctrl, { /** * AngularJS Material $mdMedia service. * * @property $mdMedia * @type Object * @final */ $mdMedia: { value: $mdMedia } }); } app.controller('OpaToolbarController', OpaToolbarController); OpaToolbarController.$inject = ['$scope', '$window', '$mdMedia', '$mdSidenav', 'opaUserFactory']; })(angular.module('opa'));
Set to broadcast val over a socket Set to broadcast val over a socket every second.
'use strict'; const express = require('express'); const socketIO = require('socket.io'); const path = require('path'); const PORT = process.env.PORT || 3000; const INDEX = path.join(__dirname, 'index.html'); var val = 42 const server = express() .use((req, res) => res.sendFile(INDEX) ) .listen(PORT, () => console.log(`Listening on ${ PORT }`)); const io = socketIO(server); io.on('connection', function(socket){ console.log('a user connected'); socket.on('disconnect', function(){ console.log('user disconnected'); }); socket.on('chat message', function(msg){ console.log('message: ' + msg); }); socket.on('incrementor', function(msg){ if (val != msg) { console.log('Incrementor: ' + msg); val = msg; } }); }); setInterval(() => io.emit('time', val), 1000);
'use strict'; const express = require('express'); const socketIO = require('socket.io'); const path = require('path'); const PORT = process.env.PORT || 3000; const INDEX = path.join(__dirname, 'index.html'); const server = express() .use((req, res) => res.sendFile(INDEX) ) .listen(PORT, () => console.log(`Listening on ${ PORT }`)); const io = socketIO(server); io.on('connection', function(socket){ console.log('a user connected'); socket.on('disconnect', function(){ console.log('user disconnected'); }); socket.on('chat message', function(msg){ console.log('message: ' + msg); }); socket.on('incrementor', function(msg){ if (val != msg) { console.log('Incrementor: ' + msg); val = msg; } }); });
Create a complete filtered output agency.txt Filter based on arguments passed from shell.
import csv import sys # agency.txt done # feed_info.txt nothing to change # calendar_dates.txt depends on service_id. # routes.txt depends on agency.txt # shapes.txt depends on trips.txt # stops.txt depends on stop_times.txt # stop_times.txt depends on trip_id. # transfers.txt depends on stop_id from and to, routes. # trips.txt contains shape_id, also route_id to trip_id. def clean_agency_file(*agencies): with open('agency.txt', 'r') as f: reader = csv.reader(f) filtered_rows = [] filtered_rows.append(next(reader)) for row in reader: if row[0] in agencies: filtered_rows.append(row) with open('cleaned/agency.txt', 'w') as f: writer = csv.writer(f) writer.writerows(filtered_rows) def main(): agencies = sys.argv[1:] clean_agency_file(*agencies) if __name__ == '__main__': main()
import csv import sys # agency.txt done # feed_info.txt nothing to change # calendar_dates.txt depends on service_id. # routes.txt depends on agency.txt # shapes.txt depends on trips.txt # stops.txt depends on stop_times.txt # stop_times.txt depends on trip_id. # transfers.txt depends on stop_id from and to, routes. # trips.txt contains shape_id, also route_id to trip_id. def clean_agency_file(*agencies): with open('agency.txt', 'r') as f: reader = csv.reader(f) next(f) for row in reader: if row[0] in agencies: print(row) def main(): agencies = sys.argv[1:] clean_agency_file(*agencies) if __name__ == '__main__': main()
Update due to API change
package org.gemoc.sample.tfsm.xdsml.api.impl; import java.lang.reflect.Method; import java.util.List; import org.gemoc.execution.engine.trace.gemoc_execution_trace.MSEOccurrence; import org.gemoc.gemoc_language_workbench.api.dsa.CodeExecutionException; import org.gemoc.gemoc_language_workbench.api.dsa.ICodeExecutor; public class TfsmCodeExecutor implements ICodeExecutor { @Override public Object execute(Object className, String methodName, List<Object> parameters) throws CodeExecutionException { Class c; try { c = Class.forName((String)className); Method method = c.getMethod(methodName, parameters.get(0).getClass().getInterfaces()[0]); Object o = c.newInstance(); method.invoke(o, parameters.get(0)); } catch (Exception e) { e.printStackTrace(); } return null; } @Override public Object execute(MSEOccurrence mseOccurrence) throws CodeExecutionException { return null; } @Override public String getExcutorID() { return getClass().getSimpleName(); } }
package org.gemoc.sample.tfsm.xdsml.api.impl; import java.lang.reflect.Method; import java.util.List; import org.gemoc.execution.engine.trace.gemoc_execution_trace.MSEOccurrence; import org.gemoc.gemoc_language_workbench.api.dsa.CodeExecutionException; import org.gemoc.gemoc_language_workbench.api.dsa.ICodeExecutor; public class TfsmCodeExecutor implements ICodeExecutor { @Override public Object execute(Object className, String methodName, List<Object> parameters) throws CodeExecutionException { Class c; try { c = Class.forName((String)className); Method method = c.getMethod(methodName, parameters.get(0).getClass().getInterfaces()[0]); Object o = c.newInstance(); method.invoke(o, parameters.get(0)); } catch (Exception e) { e.printStackTrace(); } return null; } @Override public Object execute(MSEOccurrence mseOccurrence) throws CodeExecutionException { return null; } }
Patch logic which determines if a feature context is supported or not
<?php namespace swestcott\MonologExtension\Context\Initializer; use Behat\Behat\Context\Initializer\InitializerInterface, Behat\Behat\Context\ContextInterface; class MonologInitializer implements InitializerInterface { private $container; public function __construct($container) { $this->container = $container; } public function initialize(ContextInterface $context) { $loggerName = $this->container->getParameter('behat.monolog.logger_name'); $class = $this->container->getParameter('behat.monolog.class'); $def = $this->container->getDefinition('behat.monolog.logger.manager'); $def->setArguments(array(get_class($context))); // In theory, this uses my factory to generate the logger instance, // passing in the Behat Context class name to factory->get($name) $logger = $this->container->get('behat.monolog.logger.manager'); // Finally, attached logger to (sub-)context $context->$loggerName = $logger; } public function supports(ContextInterface $context) { $class = new \ReflectionClass($context); return $class->implementsInterface('Behat\Behat\Context\SubcontextableContextInterface'); } }
<?php namespace swestcott\MonologExtension\Context\Initializer; use Behat\Behat\Context\Initializer\InitializerInterface, Behat\Behat\Context\ContextInterface; class MonologInitializer implements InitializerInterface { private $container; public function __construct($container) { $this->container = $container; } public function initialize(ContextInterface $context) { $loggerName = $this->container->getParameter('behat.monolog.logger_name'); $class = $this->container->getParameter('behat.monolog.class'); $def = $this->container->getDefinition('behat.monolog.logger.manager'); $def->setArguments(array(get_class($context))); // In theory, this uses my factory to generate the logger instance, // passing in the Behat Context class name to factory->get($name) $logger = $this->container->get('behat.monolog.logger.manager'); // Finally, attached logger to (sub-)context $context->$loggerName = $logger; } public function supports(ContextInterface $context) { return ($context instanceof SubcontextableContextInterface); } }
Support for screen resolution option
/** * Provides the --viewport option to set any device resolution and pixel density ratio. * If the user sets a viewport size as well as a device option (--phone, --tablet, ...), * we assume that he/she wants to overwrite the device values. * * Two syntaxes are supported: * - 1200x800 will set a 1x pixel density ratio * - 1200x800x2 will set the given ratio (float values such as 1.5 are accepted) */ 'use strict'; module.exports = function(phantomas) { const viewport = phantomas.getParam('viewport'); if (viewport === undefined) { phantomas.log('No viewport option specified, will use the device default viewport'); return; } phantomas.log('Viewport: %s provided', viewport); const viewportValues = viewport.split('x'); const options = { width: parseInt(viewportValues[0], 10), height: parseInt(viewportValues[1], 10), deviceScaleFactor: parseFloat(viewportValues[2]) || 1 }; phantomas.on('init', async page => { // @see https://github.com/puppeteer/puppeteer/blob/v1.11.0/docs/api.md#pagesetviewportviewport await page.setViewport(options); phantomas.log('page.setViewport() called with options %j', options); }); };
/** * Provides the --viewport option to set any device resolution and pixel density ratio. * If the user sets a viewport size as well as a device option (--phone, --tablet, ...), * we assume that he/she wants to overwrite the device values. * * Two syntaxes are supported: * - 1200x800 will set a 1x pixel density ratio * - 1200x800x2 will set the given ratio (float values such as 1.5 are accepted) */ 'use strict'; module.exports = function(phantomas) { const viewport = phantomas.getParam('viewport'); if (viewport === undefined) { phantomas.log('No viewport option specified, will use the device default viewport'); return; } phantomas.log('Viewport: %s provided', viewport); const viewportValues = viewport.split('x'); const options = { width: viewportValues[0], height: viewportValues[1], deviceScaleFactor: viewportValues[2] || 1 }; phantomas.on('init', async page => { // @see https://github.com/puppeteer/puppeteer/blob/v1.11.0/docs/api.md#pagesetviewportviewport await page.setViewport(options); phantomas.log('page.setViewport() called with options %j', options); }); };
Fix reading from hashed file names. Bioformats expects file extensions to exist, so flag that we should always appear as actual, fully-pathed files.
# -*- coding: utf-8 -*- ############################################################################## # Copyright Kitware 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 cherrypy from girder_large_image.girder_tilesource import GirderTileSource from . import BioformatsFileTileSource, _stopJavabridge cherrypy.engine.subscribe('stop', _stopJavabridge) class BioformatsGirderTileSource(BioformatsFileTileSource, GirderTileSource): """ Provides tile access to Girder items that can be read with bioformats. """ cacheName = 'tilesource' name = 'bioformats' def mayHaveAdjacentFiles(self, largeImageFile): # bioformats uses extensions to determine how to open a file, so this # needs to be set for all file formats. return True
# -*- coding: utf-8 -*- ############################################################################## # Copyright Kitware 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 cherrypy from girder_large_image.girder_tilesource import GirderTileSource from . import BioformatsFileTileSource, _stopJavabridge cherrypy.engine.subscribe('stop', _stopJavabridge) class BioformatsGirderTileSource(BioformatsFileTileSource, GirderTileSource): """ Provides tile access to Girder items that can be read with bioformats. """ cacheName = 'tilesource' name = 'bioformats'
Fix a typo in Javadoc.
/* * Copyright 2017, TeamDev Ltd. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.tools.protodoc; /** * A formatting action, that formats a {@code String}. * * @author Dmytro Grankin */ interface FormattingAction { /** * Obtains the formatted representation of the specified text. * * <p>The specified text may contain line separators. * * @param text the text to format * @return the formatted text */ String execute(String text); }
/* * Copyright 2017, TeamDev Ltd. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.tools.protodoc; /** * A formatting action, that formats a {@code String}. * * @author Dmytro Grankin */ interface FormattingAction { /** * Obtains the formatted representation of the specified text. * * <p>The specified text may contains line separators. * * @param text the text to format * @return the formatted text */ String execute(String text); }
Change channel update retry timeout
'use strict' const TelegramBot = require('node-telegram-bot-api'); const config = require('../config'); const utils = require('./utils'); const Kinospartak = require('./Kinospartak/Kinospartak'); const bot = new TelegramBot(config.TOKEN); const kinospartak = new Kinospartak(); /** * updateSchedule - update schedule and push updates to Telegram channel * * @return {Promise} */ function updateSchedule() { return kinospartak.getChanges() .then(changes => changes.length ? utils.formatSchedule(changes) : undefined) .then(messages => messages ? utils.sendInOrder(bot, config.CHANNEL, messages) : undefined) .then(() => kinospartak.commitChanges()) }; /** * updateNews - update news and push updates to Telegram channel * * @return {Promise} */ function updateNews() { return kinospartak.getLatestNews() .then(news => news.length ? utils.formatNews(news) : undefined) .then(messages => messages ? utils.sendInOrder(bot, config.CHANNEL, messages) : undefined) .then(() => kinospartak.setNewsOffset(new Date().toString())) }; function update() { return Promise.all([ updateSchedule, updateNews ]).catch((err) => { setTimeout(() => { update(); }, 1000 * 60 * 5); }) } update();
'use strict' const TelegramBot = require('node-telegram-bot-api'); const config = require('../config'); const utils = require('./utils'); const Kinospartak = require('./Kinospartak/Kinospartak'); const bot = new TelegramBot(config.TOKEN); const kinospartak = new Kinospartak(); /** * updateSchedule - update schedule and push updates to Telegram channel * * @return {Promise} */ function updateSchedule() { return kinospartak.getChanges() .then(changes => changes.length ? utils.formatSchedule(changes) : undefined) .then(messages => messages ? utils.sendInOrder(bot, config.CHANNEL, messages) : undefined) .then(() => kinospartak.commitChanges()) }; /** * updateNews - update news and push updates to Telegram channel * * @return {Promise} */ function updateNews() { return kinospartak.getLatestNews() .then(news => news.length ? utils.formatNews(news) : undefined) .then(messages => messages ? utils.sendInOrder(bot, config.CHANNEL, messages) : undefined) .then(() => kinospartak.setNewsOffset(new Date().toString())) }; function update() { return Promise.all([ updateSchedule, updateNews ]).catch((err) => { setTimeout(() => { update(); }, 60 * 5); }) } update();
Save model in a separate variable.
var mistigri = require("../mistigri.js"); var fs = require("fs"); // Some generic setup mistigri.options.escapeFunction = String; function readFile(name, options) { return new Promise(function fsReadFile(fulfill, reject) { var fsCallback = function fsCallback(error, data) { if (error) reject(error); else fulfill(data); } fs.readFile(name, (options === undefined) ? "utf8" : options, fsCallback); }); } // This is the filter function function uppercaseFilter(args) { var toUpper = function toUpper(text) { return text.toLocaleUpperCase(); } if ('$invertBlock' in args) // we are inside a block { return mistigri.prrcess(args.$template, args.$model).then(toUpper); } else { return toUpper(args.text); } } // Render the template using the filter var model = {CAPS: uppercaseFilter}; readFile("filter.mi").then(function(template) { return mistigri.prrcess(template, model); }).then(console.log);
var mistigri = require("../mistigri.js"); var fs = require("fs"); // Some generic setup mistigri.options.escapeFunction = String; function readFile(name, options) { return new Promise(function fsReadFile(fulfill, reject) { var fsCallback = function fsCallback(error, data) { if (error) reject(error); else fulfill(data); } fs.readFile(name, (options === undefined) ? "utf8" : options, fsCallback); }); } // This is the filter function function uppercaseFilter(args) { var toUpper = function toUpper(text) { return text.toLocaleUpperCase(); } if ('$invertBlock' in args) // we are inside a block { return mistigri.prrcess(args.$template, args.$model).then(toUpper); } else { return toUpper(args.text); } } // Render the template using the filter readFile("filter.mi").then(function(template) { return mistigri.prrcess(template, { CAPS: uppercaseFilter }); }).then(console.log);
Support for diallowing official images.
import os, sys import json as _json from flask import Flask, Response, request app = Flask(__name__) app.debug = True import lib @app.route("/", methods=["HEAD", "GET", "POST", "DELETE", "PUT"]) def adapter(): json = request.get_data() decoded = _json.loads(json) docker_json = _json.loads(decoded['ClientRequest']['Body']) image = docker_json['Image'] if "/" not in image: user = "_" else: user = image.split("/")[0] if user != app.config['ALLOWED_USER']: return '', 403 response = lib.pre_hook_response( decoded['ClientRequest']['Method'], decoded['ClientRequest']['Request'], decoded['ClientRequest']['Body'], ) return Response(response, mimetype="application/json") if __name__ == "__main__": try: app.config['ALLOWED_USER'] = os.environ['USER'] except KeyError: sys.stdout.write("""Error: Configuration environment variable USER not provided. Specify an image username on the Docker command-line by using docker run -e USER=<user>. Use the user "_" to only allow official Docker images. """) sys.exit(1) app.run(port=80)
import os, sys import json as _json from flask import Flask, Response, request app = Flask(__name__) app.debug = True import lib @app.route("/", methods=["HEAD", "GET", "POST", "DELETE", "PUT"]) def adapter(): json = request.get_data() decoded = _json.loads(json) docker_json = _json.loads(decoded['ClientRequest']['Body']) image = docker_json['Image'] user = image.split("/")[0] if user != app.config['ALLOWED_USER']: return '', 403 response = lib.pre_hook_response( decoded['ClientRequest']['Method'], decoded['ClientRequest']['Request'], decoded['ClientRequest']['Body'], ) return Response(response, mimetype="application/json") if __name__ == "__main__": try: app.config['ALLOWED_USER'] = os.environ['USER'] except KeyError: sys.stdout.write("""Error: Configuration environment variable USER not provided. Specify an image username on the Docker command-line by using docker run -e USER=<user>. Use the user "_" to only allow official Docker images. """) sys.exit(1) app.run(port=80)
Revert "log integrations with zabbix through pyzabbix" This reverts commit 1506b6ad3e35e4a10ca36d42a75f3a572add06b7.
#!/usr/bin/env python # -*- coding: utf-8 -*- from dbaas_zabbix.dbaas_api import DatabaseAsAServiceApi from dbaas_zabbix.provider_factory import ProviderFactory from pyzabbix import ZabbixAPI def factory_for(**kwargs): databaseinfra = kwargs['databaseinfra'] credentials = kwargs['credentials'] del kwargs['databaseinfra'] del kwargs['credentials'] zabbix_api = ZabbixAPI if kwargs.get('zabbix_api'): zabbix_api = kwargs.get('zabbix_api') del kwargs['zabbix_api'] dbaas_api = DatabaseAsAServiceApi(databaseinfra, credentials) return ProviderFactory.factory(dbaas_api, zabbix_api=zabbix_api, **kwargs)
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging import sys from dbaas_zabbix.dbaas_api import DatabaseAsAServiceApi from dbaas_zabbix.provider_factory import ProviderFactory from pyzabbix import ZabbixAPI stream = logging.StreamHandler(sys.stdout) stream.setLevel(logging.DEBUG) log = logging.getLogger('pyzabbix') log.addHandler(stream) log.setLevel(logging.DEBUG) def factory_for(**kwargs): databaseinfra = kwargs['databaseinfra'] credentials = kwargs['credentials'] del kwargs['databaseinfra'] del kwargs['credentials'] zabbix_api = ZabbixAPI if kwargs.get('zabbix_api'): zabbix_api = kwargs.get('zabbix_api') del kwargs['zabbix_api'] dbaas_api = DatabaseAsAServiceApi(databaseinfra, credentials) return ProviderFactory.factory(dbaas_api, zabbix_api=zabbix_api, **kwargs)
[user] Use the Model constructor to generate a default value
import hashlib import random import string from ext.aboard.model import * class Token(Model): """A token model.""" id = None user = Integer() timestamp = Integer() value = String(pkey=True) def __init__(self, user=None, timestamp=None): value = None if user and timestamp: value = Token.get_token_value(user, timestamp) Model.__init__(self, user=user, timestamp=timestamp, value=value) @staticmethod def get_token_value(user, timestamp): """Randomly create and return a token value.""" value = str(user) + "_" + str(timestamp) len_rand = random.randint(20, 40) to_pick = string.digits + string.ascii_letters + \ "_-+^$" for i in range(len_rand): value += random.choice(to_pick) print("Private value", value) # Hash the value hashed = hashlib.sha512(value.encode()) value = hashed.hexdigest() print("Public value", value) return value
import hashlib import random import string from ext.aboard.model import * def set_value(token): """Randomly create and return a value.""" value = str(token.user) + "_" + str(token.timestamp) len_rand = random.randint(20, 40) to_pick = string.digits + string.ascii_letters + \ "_-+^$" for i in range(len_rand): value += random.choice(to_pick) print("Private value", value) # Hash the value hashed = hashlib.sha512(value.encode()) value = hashed.hexdigest() print("Public value", value) return value class Token(Model): """A token model.""" id = None user = Integer() timestamp = Integer() value = String(pkey=True, default=set_value)
Fix display artifact that prevented sidebar from showing after login, until page was refreshed [#LEI-294]
import Ember from 'ember'; export default Ember.Controller.extend({ session: Ember.inject.service(), isExpanded: true, isNotLogin: Ember.computed('currentPath', function() { return this.get('currentPath') !== 'login'; }), sizeContainer: function() { var winWidth = Ember.$(window).width(); if (winWidth < 992 && this.isExpanded) { this.send('toggleMenu'); } }, attachResizeListener : function () { Ember.$(window).on('resize', Ember.run.bind(this, this.sizeContainer)); }.on('init'), actions: { toggleMenu: function() { this.toggleProperty('isExpanded'); }, invalidateSession: function() { return this.get('session').invalidate().then(() => { window.location.reload(true); }); } } });
import Ember from 'ember'; export default Ember.Controller.extend({ session: Ember.inject.service(), isExpanded: true, isNotLogin: Ember.computed('this.currentPath', function() { if (this.currentPath !== 'login') { return true; } else { return false; } }), sizeContainer: function() { var winWidth = Ember.$(window).width(); if (winWidth < 992 && this.isExpanded) { this.send('toggleMenu'); } }, attachResizeListener : function () { Ember.$(window).on('resize', Ember.run.bind(this, this.sizeContainer)); }.on('init'), actions: { toggleMenu: function() { this.toggleProperty('isExpanded'); }, invalidateSession: function() { return this.get('session').invalidate().then(() => { window.location.reload(true); }); } } });
Add type info in comment.
#------------------------------------------------------------------------------ # # Copyright (c) 2008, Enthought, Inc. # All rights reserved. # # This software is provided without warranty under the terms of the BSD # license included in enthought/LICENSE.txt and may be redistributed only # under the conditions described in the aforementioned license. The license # is also available online at http://www.enthought.com/licenses/BSD.txt # # Thanks for using Enthought open source! # # Author: Judah De Paula # Date: 10/7/2008 # #------------------------------------------------------------------------------ """ A Traits UI editor that wraps a WX calendar panel. """ from enthought.traits.trait_types import Bool, Any from enthought.traits.ui.editor_factory import EditorFactory #-- DateEditor definition ----------------------------------------------------- class DateEditor ( EditorFactory ): """ Editor factory for date/time editors. """ #--------------------------------------------------------------------------- # Trait definitions: #--------------------------------------------------------------------------- # Is multiselect enabled for a CustomEditor? # If True, then the edited object must be a Date. If False, then it's # a List of Dates. multi_select = Bool(False) # Should users be able to pick future dates when using the CustomEditor? allow_future = Bool(True) #-- end DateEditor definition ------------------------------------------------- #-- eof -----------------------------------------------------------------------
#------------------------------------------------------------------------------ # # Copyright (c) 2008, Enthought, Inc. # All rights reserved. # # This software is provided without warranty under the terms of the BSD # license included in enthought/LICENSE.txt and may be redistributed only # under the conditions described in the aforementioned license. The license # is also available online at http://www.enthought.com/licenses/BSD.txt # # Thanks for using Enthought open source! # # Author: Judah De Paula # Date: 10/7/2008 # #------------------------------------------------------------------------------ """ A Traits UI editor that wraps a WX calendar panel. """ from enthought.traits.trait_types import Bool, Any from enthought.traits.ui.editor_factory import EditorFactory #-- DateEditor definition ----------------------------------------------------- class DateEditor ( EditorFactory ): """ Editor factory for date/time editors. """ #--------------------------------------------------------------------------- # Trait definitions: #--------------------------------------------------------------------------- # Is multiselect enabled for a CustomEditor? multi_select = Bool(False) # Should users be able to pick future dates when using the CustomEditor? allow_future = Bool(True) #-- end DateEditor definition ------------------------------------------------- #-- eof -----------------------------------------------------------------------
Support prod runmode on Linux (On Linux the service doesn't append .prod if it's prod, for some reason.)
import {OS_DESKTOP} from './platform.shared' import path from 'path' export const isDev = process.env.NODE_ENV === 'development' export const OS = OS_DESKTOP export const isMobile = false const runMode = process.env.KEYBASE_RUN_MODE || 'devel' const envedPathOSX = { staging: 'KeybaseStaging', devel: 'KeybaseDevel', prod: 'Keybase' } function findSocketRoot () { const paths = { 'darwin': `${process.env.HOME}/Library/Caches/${envedPathOSX[runMode]}/`, 'linux': `${process.env.XDG_RUNTIME_DIR}/keybase.${runMode}/` } if (runMode === 'prod') { paths['linux'] = `${process.env.XDG_RUNTIME_DIR}/keybase/` } return paths[process.platform] } export const socketRoot = findSocketRoot() export const socketName = 'keybased.sock' export const socketPath = path.join(socketRoot, socketName) function findDataRoot () { const paths = { 'darwin': `${process.env.HOME}/Library/Application Support/${envedPathOSX[runMode]}/`, 'linux': `${process.env.XDG_DATA_DIR}/keybase.${runMode}/` } return paths[process.platform] } export const dataRoot = findDataRoot()
import {OS_DESKTOP} from './platform.shared' import path from 'path' export const isDev = process.env.NODE_ENV === 'development' export const OS = OS_DESKTOP export const isMobile = false const runMode = process.env.KEYBASE_RUN_MODE || 'devel' const envedPathOSX = { staging: 'KeybaseStaging', devel: 'KeybaseDevel', prod: 'Keybase' } function findSocketRoot () { const paths = { 'darwin': `${process.env.HOME}/Library/Caches/${envedPathOSX[runMode]}/`, 'linux': `${process.env.XDG_RUNTIME_DIR}/keybase.${runMode}/` } return paths[process.platform] } export const socketRoot = findSocketRoot() export const socketName = 'keybased.sock' export const socketPath = path.join(socketRoot, socketName) function findDataRoot () { const paths = { 'darwin': `${process.env.HOME}/Library/Application Support/${envedPathOSX[runMode]}/`, 'linux': `${process.env.XDG_DATA_DIR}/keybase.${runMode}/` } return paths[process.platform] } export const dataRoot = findDataRoot()
Exclude `simpleWorker` from `editorSimpleWorker` in bundling
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; function createModuleDescription(name, exclude) { var result= {}; result.name= name; var excludes = ['vs/css', 'vs/nls', 'vs/text']; if (Array.isArray(exclude) && exclude.length > 0) { excludes = excludes.concat(exclude); } result.exclude= excludes; return result; } function addInclude(config, include) { if (!config.include) { config.include = []; } config.include.push(include); return config; } exports.collectModules= function() { return [ // Include the severity module into the base worker code since it is used by many languages // It can cause waterfall loading if one language excludes another language it depends on and // both use vs/base/common/severity addInclude( createModuleDescription('vs/editor/common/worker/editorWorkerServer', ['vs/base/common/worker/workerServer']), 'vs/base/common/severity' ), createModuleDescription('vs/editor/common/services/editorSimpleWorker', ['vs/base/common/worker/simpleWorker']), ]; };
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; function createModuleDescription(name, exclude) { var result= {}; result.name= name; var excludes = ['vs/css', 'vs/nls', 'vs/text']; if (Array.isArray(exclude) && exclude.length > 0) { excludes = excludes.concat(exclude); } result.exclude= excludes; return result; } function addInclude(config, include) { if (!config.include) { config.include = []; } config.include.push(include); return config; } exports.collectModules= function() { return [ // Include the severity module into the base worker code since it is used by many languages // It can cause waterfall loading if one language excludes another language it depends on and // both use vs/base/common/severity addInclude( createModuleDescription('vs/editor/common/worker/editorWorkerServer', ['vs/base/common/worker/workerServer']), 'vs/base/common/severity' ), createModuleDescription('vs/editor/common/services/editorSimpleWorker'), ]; };
Fix scope of loaded dependencies
/** * Gray Matter * Copyright (c) 2014 Jon Schlinkert, Brian Woodward, contributors. * Licensed under the MIT license. */ 'use strict'; // node_modules var YAML = require('js-yaml'); // The module to export var parse = module.exports = {}; parse.yaml = function(src) { return YAML.load(src); }; parse.json = function(src) { return JSON.parse(src); }; parse.coffee = function(src, options) { options = options || {}; try { var coffee = require('coffee-script'); return coffee['eval'](src, options); } catch (e) { console.warn('Could not parse coffee-script:', e); } }; parse.toml = function(src) { try { var toml = require('toml'); return toml.parse(src.trim()); } catch (e) { console.warn('Count not parse toml:' + src, e); } };
/** * Gray Matter * Copyright (c) 2014 Jon Schlinkert, Brian Woodward, contributors. * Licensed under the MIT license. */ 'use strict'; // node_modules var YAML = require('js-yaml'), coffee, toml; // The module to export var parse = module.exports = {}; parse.yaml = function(src) { return YAML.load(src); }; parse.json = function(src) { return JSON.parse(src); }; parse.coffee = function(src, options) { options = options || {}; if (!coffee) { coffee = require('coffee-script'); } try { return coffee['eval'](src, options); } catch (e) { console.warn('Could not parse coffee-script:', e); } }; parse.toml = function(src) { if (!toml) { toml = require('toml'); } try { return toml.parse(src.trim()); } catch (e) { console.warn('Count not parse toml:' + src, e); } };
Use hash mode for router as server can't be changed for use with history mode.
import Vue from 'vue'; import VueRouter from 'vue-router'; import RestaurantList from '../components/RestaurantList.vue' Vue.use(VueRouter); const router = new VueRouter({ mode: 'hash', base: '/menu/', routes: [ { path: '/solna', component: RestaurantList, props: { list_type: 'solna' }, alias: ['/ki'] }, { path: '/uppsala', component: RestaurantList, props: { list_type: 'uppsala' }, alias: ['/uu', '/bmc'] }, { path: '/', component: RestaurantList, props: { list_type: 'both' }, alias: ['*'] }, ] }); export default router;
import Vue from 'vue'; import VueRouter from 'vue-router'; import RestaurantList from '../components/RestaurantList.vue' Vue.use(VueRouter); const router = new VueRouter({ mode: 'history', routes: [ { path: '/solna', component: RestaurantList, props: { list_type: 'solna' }, alias: ['/ki'] }, { path: '/uppsala', component: RestaurantList, props: { list_type: 'uppsala' }, alias: ['/uu', '/bmc'] }, { path: '/', component: RestaurantList, props: { list_type: 'both' }, alias: ['*'] }, ] }); export default router;
[BEAM-8470] Add an assert of equality in the encoders test
package org.apache.beam.runners.spark.structuredstreaming.utils; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.List; import org.apache.beam.runners.spark.structuredstreaming.translation.helpers.EncoderHelpers; import org.apache.beam.sdk.coders.VarIntCoder; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.SparkSession; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) /** * Test of the wrapping of Beam Coders as Spark ExpressionEncoders. */ public class EncodersTest { @Test public void beamCoderToSparkEncoderTest() { SparkSession sparkSession = SparkSession.builder().appName("beamCoderToSparkEncoderTest") .master("local[4]").getOrCreate(); List<Integer> data = new ArrayList<>(); data.add(1); data.add(2); data.add(3); Dataset<Integer> dataset = sparkSession .createDataset(data, EncoderHelpers.fromBeamCoder(VarIntCoder.of())); List<Integer> results = dataset.collectAsList(); assertEquals(data, results); } }
package org.apache.beam.runners.spark.structuredstreaming.utils; import java.util.ArrayList; import java.util.List; import org.apache.beam.runners.spark.structuredstreaming.translation.helpers.EncoderHelpers; import org.apache.beam.sdk.coders.Coder; import org.apache.beam.sdk.coders.VarIntCoder; import org.apache.spark.sql.SparkSession; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) /** * Test of the wrapping of Beam Coders as Spark ExpressionEncoders. */ public class EncodersTest { @Test public void beamCoderToSparkEncoderTest() { SparkSession sparkSession = SparkSession.builder().appName("beamCoderToSparkEncoderTest") .master("local[4]").getOrCreate(); List<Integer> data = new ArrayList<>(); data.add(1); data.add(2); data.add(3); sparkSession.createDataset(data, EncoderHelpers.fromBeamCoder(VarIntCoder.of())); // sparkSession.createDataset(data, EncoderHelpers.genericEncoder()); } }
TEST: Increase pause before clicking diagnosis node This fixes an issue when page is rendered with no scope diagnosis nodes when a node clicked too fast.
'use strict'; var log = require('../modules/log'); exports.command = function(scenario, callback) { var client = this; this.perform(function() { log.command('Processing Scope diagnosis - scenario: ' + scenario.title); client .ensureCorrectPage('body.js-enabled', '/scope/diagnosis', { 'h1': 'Choose the area you most need help with' }) .useXpath() ; scenario.nodes.forEach(function(node) { var xpath = '//a[starts-with(normalize-space(.), "' + node + '")]'; client .waitForElementPresent(xpath, 3000, ' - node ‘' + node + '’ visible') .pause(200) // KLUDGE: Wait a bit to ensure element is accessible before being clicked .click(xpath, function() { console.log(' • node ‘' + node + '’ clicked'); }); }); client.useCss(); }); if (typeof callback === 'function') { callback.call(client); } return client; };
'use strict'; var log = require('../modules/log'); exports.command = function(scenario, callback) { var client = this; this.perform(function() { log.command('Processing Scope diagnosis - scenario: ' + scenario.title); client .ensureCorrectPage('body.js-enabled', '/scope/diagnosis', { 'h1': 'Choose the area you most need help with' }) .useXpath() ; scenario.nodes.forEach(function(node) { var xpath = '//a[starts-with(normalize-space(.), "' + node + '")]'; client .waitForElementPresent(xpath, 3000, ' - node ‘' + node + '’ visible') .pause(50) // KLUDGE: Wait a bit to ensure element is accessible before being clicked .click(xpath, function() { console.log(' • node ‘' + node + '’ clicked'); }); }); client.useCss(); }); if (typeof callback === 'function') { callback.call(client); } return client; };
Replace 'write' method with '__str__'
import collections class Settings(object): def __init__(self): self._settings = collections.OrderedDict() def __setattr__(self, name, value): if name.startswith('_'): super(Settings, self).__setattr__(name, value) else: self._settings[name] = value def __str__(self): lines = [] for name, value in self._settings.iteritems(): if name.startswith('_'): lines.append(value) else: lines.append('%s = %s' % (name.upper(), value.__repr__())) return '\n'.join(lines) def _set_raw_value(self, value): self._settings['_%d' % len(self._settings)] = value def imp(self, module_name): value = 'import %s' % module_name self._set_raw_value(value)
import collections class Settings(object): def __init__(self): self._settings = collections.OrderedDict() def __setattr__(self, name, value): if name.startswith('_'): super(Settings, self).__setattr__(name, value) else: self._settings[name] = value def _set_raw_value(self, value): self._settings['_%d' % len(self._settings)] = value def imp(self, module_name): value = 'import %s' % module_name self._set_raw_value(value) def write(self): for name, value in self._settings.iteritems(): if name.startswith('_'): print value else: print '%s = %s' % (name.upper(), value.__repr__())
Remove unused import of TokenNormalizer Fixes the build
# Copyright (C) 2012 Peter Teichman import itertools import logging from cobe.analysis import ( AccentNormalizer, StemNormalizer, WhitespaceAnalyzer) from cobe.kvstore import SqliteStore from cobe.model import Model from cobe.search import RandomWalkSearcher log = logging.getLogger(__name__) class StandardAnalyzer(WhitespaceAnalyzer): """A basic analyzer for test purposes. This combines a whitespace tokenizer with AccentNormalizer. """ def __init__(self): super(StandardAnalyzer, self).__init__() self.add_token_normalizer(AccentNormalizer()) self.add_token_normalizer(StemNormalizer("english")) class Brain(object): """The all-in-one interface to a cobe stack.""" def __init__(self, filename): self.analyzer = StandardAnalyzer() store = SqliteStore(filename) self.model = Model(self.analyzer, store) self.searcher = RandomWalkSearcher(self.model) def reply(self, text): # Create a search query from the input query = self.analyzer.query(text, self.model) result = itertools.islice(self.searcher.search(query), 1).next() return self.analyzer.join(result) def train(self, text): pass
# Copyright (C) 2012 Peter Teichman import itertools import logging from cobe.analysis import ( AccentNormalizer, StemNormalizer, TokenNormalizer, WhitespaceAnalyzer) from cobe.kvstore import SqliteStore from cobe.model import Model from cobe.search import RandomWalkSearcher log = logging.getLogger(__name__) class StandardAnalyzer(WhitespaceAnalyzer): """A basic analyzer for test purposes. This combines a whitespace tokenizer with AccentNormalizer. """ def __init__(self): super(StandardAnalyzer, self).__init__() self.add_token_normalizer(AccentNormalizer()) self.add_token_normalizer(StemNormalizer("english")) class Brain(object): """The all-in-one interface to a cobe stack.""" def __init__(self, filename): self.analyzer = StandardAnalyzer() store = SqliteStore(filename) self.model = Model(self.analyzer, store) self.searcher = RandomWalkSearcher(self.model) def reply(self, text): # Create a search query from the input query = self.analyzer.query(text, self.model) result = itertools.islice(self.searcher.search(query), 1).next() return self.analyzer.join(result) def train(self, text): pass
[WEB-1338] Add relative position to default container styles
export default ({ borders, colors, radii, space }) => { const defaultStyles = { mx: 'auto', bg: colors.white, width: ['100%', '85%'], mb: `${space[6]}px`, position: 'relative', }; const large = { ...defaultStyles, maxWidth: '1280px', }; const medium = { ...defaultStyles, maxWidth: '840px', }; const small = { ...defaultStyles, maxWidth: '600px', }; const bordered = { borderLeft: ['none', borders.default], borderRight: ['none', borders.default], borderTop: borders.default, borderBottom: borders.default, borderRadius: ['none', radii.default], }; return { large, largeBordered: { ...large, ...bordered, }, medium, mediumBordered: { ...medium, ...bordered, }, small, smallBordered: { ...small, ...bordered, }, }; };
export default ({ borders, colors, radii, space }) => { const defaultStyles = { mx: 'auto', bg: colors.white, width: ['100%', '85%'], mb: `${space[6]}px`, }; const large = { ...defaultStyles, maxWidth: '1280px', }; const medium = { ...defaultStyles, maxWidth: '840px', }; const small = { ...defaultStyles, maxWidth: '600px', }; const bordered = { borderLeft: ['none', borders.default], borderRight: ['none', borders.default], borderTop: borders.default, borderBottom: borders.default, borderRadius: ['none', radii.default], }; return { large, largeBordered: { ...large, ...bordered, }, medium, mediumBordered: { ...medium, ...bordered, }, small, smallBordered: { ...small, ...bordered, }, }; };
Fix rout for diary/event, argument has to be item_id For error see here: http://devlol.at/diary/event/22/ as an example
from django.conf.urls import patterns, include, url from django.contrib import admin urlpatterns = patterns('', url(r'^$', 'devlol.views.index'), # Static Stuff url(r'^location/$', 'devlol.views.location'), url(r'^mail/$', 'devlol.views.mail'), # Diary Stuff url(r'^diary/$', 'devlol.views.index'), url(r'^diary/event/(?P<item_id>[0-9]+)/$', 'diary.views.item'), # API Stuff url(r'^api/events$', 'devlol.views.events'), # iCal Export url(r'^export/ical/events.ics$', 'devlol.views.ical'), # Admin Stuff url(r'^admin/', include(admin.site.urls)), )
from django.conf.urls import patterns, include, url from django.contrib import admin urlpatterns = patterns('', url(r'^$', 'devlol.views.index'), # Static Stuff url(r'^location/$', 'devlol.views.location'), url(r'^mail/$', 'devlol.views.mail'), # Diary Stuff url(r'^diary/$', 'devlol.views.index'), url(r'^diary/event/(?P<event_id>[0-9]+)/$', 'diary.views.item'), # API Stuff url(r'^api/events$', 'devlol.views.events'), # iCal Export url(r'^export/ical/events.ics$', 'devlol.views.ical'), # Admin Stuff url(r'^admin/', include(admin.site.urls)), )
Change the logging format to begin with the threadname
# Copyright (c) 2014 Wieland Hoffmann # License: MIT, see LICENSE for details import argparse import logging from . import config from .indexing import reindex logger = logging.getLogger("sir") def watch(args): raise NotImplementedError def main(): loghandler = logging.StreamHandler() formatter = logging.Formatter(fmt="%(threadName)s %(asctime)s %(levelname)s: %(message)s") loghandler.setFormatter(formatter) logger.addHandler(loghandler) parser = argparse.ArgumentParser() parser.add_argument("-d", "--debug", action="store_true") subparsers = parser.add_subparsers() reindex_parser = subparsers.add_parser("reindex", help="Reindexes all or a single entity type") reindex_parser.set_defaults(func=reindex) reindex_parser.add_argument('--entities', action='append', help='The entities to reindex') watch_parser = subparsers.add_parser("watch", help="Watches for incoming messages on an AMQP queue") watch_parser.set_defaults(func=watch) args = parser.parse_args() if args.debug: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) config.read_config() func = args.func args = vars(args) func(args["entities"], args["debug"]) if __name__ == '__main__': main()
# Copyright (c) 2014 Wieland Hoffmann # License: MIT, see LICENSE for details import argparse import logging from . import config from .indexing import reindex logger = logging.getLogger("sir") def watch(args): raise NotImplementedError def main(): loghandler = logging.StreamHandler() formatter = logging.Formatter(fmt="%(asctime)s %(threadName)s %(levelname)s: %(message)s") loghandler.setFormatter(formatter) logger.addHandler(loghandler) parser = argparse.ArgumentParser() parser.add_argument("-d", "--debug", action="store_true") subparsers = parser.add_subparsers() reindex_parser = subparsers.add_parser("reindex", help="Reindexes all or a single entity type") reindex_parser.set_defaults(func=reindex) reindex_parser.add_argument('--entities', action='append', help='The entities to reindex') watch_parser = subparsers.add_parser("watch", help="Watches for incoming messages on an AMQP queue") watch_parser.set_defaults(func=watch) args = parser.parse_args() if args.debug: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) config.read_config() func = args.func args = vars(args) func(args["entities"], args["debug"]) if __name__ == '__main__': main()
Add id to the error output Signed-off-by: Ulysses Souza <9b58b28cc7619bff4119b8572e41bbb4dd363aab@gmail.com>
package cmd import ( "fmt" "strings" "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/docker/api/client" ) type rmOpts struct { force bool } // RmCommand deletes containers func RmCommand() *cobra.Command { var opts rmOpts cmd := &cobra.Command{ Use: "rm", Aliases: []string{"delete"}, Short: "Remove containers", Args: cobra.MinimumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { var errs []string c, err := client.New(cmd.Context()) if err != nil { return errors.Wrap(err, "cannot connect to backend") } for _, id := range args { err := c.ContainerService().Delete(cmd.Context(), id, opts.force) if err != nil { errs = append(errs, err.Error()+" "+id) continue } fmt.Println(id) } if len(errs) > 0 { return errors.New(strings.Join(errs, "\n")) } return nil }, } cmd.Flags().BoolVarP(&opts.force, "force", "f", false, "Force removal") return cmd }
package cmd import ( "fmt" "strings" "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/docker/api/client" ) type rmOpts struct { force bool } // RmCommand deletes containers func RmCommand() *cobra.Command { var opts rmOpts cmd := &cobra.Command{ Use: "rm", Aliases: []string{"delete"}, Short: "Remove containers", Args: cobra.MinimumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { var errs []string c, err := client.New(cmd.Context()) if err != nil { return errors.Wrap(err, "cannot connect to backend") } for _, id := range args { err := c.ContainerService().Delete(cmd.Context(), id, opts.force) if err != nil { errs = append(errs, err.Error()) continue } fmt.Println(id) } if len(errs) > 0 { return errors.New(strings.Join(errs, "\n")) } return nil }, } cmd.Flags().BoolVarP(&opts.force, "force", "f", false, "Force removal") return cmd }
Remove SideMenu from app root
/** * Sample React Native App * https://github.com/facebook/react-native */ 'use strict'; import React, { AppRegistry, Component, StyleSheet, Text, View } from 'react-native'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import rootReducer from './app/reducers/rootReducer.js'; import ViewContainer from './app/containers/container_viewContainer'; import thunk from 'redux-thunk'; import createLogger from 'redux-logger'; import promise from 'redux-promise'; //creates logger const logger = createLogger(); // creates store const store = createStore( rootReducer, applyMiddleware(thunk, promise, logger) ); const findAR = () => ( <Provider store={store}> <ViewContainer /> </Provider> ); AppRegistry.registerComponent('findAR', () => findAR);
/** * Sample React Native App * https://github.com/facebook/react-native */ 'use strict'; import React, { AppRegistry, Component, StyleSheet, Text, View } from 'react-native'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import rootReducer from './app/reducers/rootReducer.js'; import ViewContainer from './app/containers/container_viewContainer'; import Menu from './app/components/Menu.js'; import thunk from 'redux-thunk'; import createLogger from 'redux-logger'; import promise from 'redux-promise'; const SideMenu = require('react-native-side-menu'); //creates logger const logger = createLogger(); // creates store const store = createStore( rootReducer, applyMiddleware(thunk, promise, logger) ); class findAR extends Component { constructor() { super(); } onMenuItemSelected () { return ''; } render() { const menu = <Menu onItemSelected={this.onMenuItemSelected} navigator={navigator}/>; return ( <Provider store={store}> <SideMenu menu={menu}> <ViewContainer > </ViewContainer> </SideMenu> </Provider> ); } } AppRegistry.registerComponent('findAR', () => findAR);
Fix for crash over badly formatted auth requests
package io.reon.auth; import java.util.HashMap; import io.reon.util.Hex; public abstract class AbstractAuth implements HttpAuth { public static final String REALM = "realm"; public static final String RESPONSE = "response"; public static final String NONCE = "nonce"; public static final String PK = "pk"; public static final String EQ = "=\""; public static final String EOS = "\", "; public static final String EOT = "\""; public static HashMap<String, String> parse(String text) { HashMap<String, String> attrs = new HashMap<>(); try { String[] fields = text.substring(text.indexOf(' ') + 1).split(","); for (String field : fields) { String[] kv = field.split("="); attrs.put(kv[0].trim(), kv[1].replace('"', ' ').trim()); } } catch (RuntimeException ex) { // ignore } return attrs; } public static byte[] fromHex(String value) { return Hex.decodeHex(value); } public static String toHex(byte[] value) { return Hex.encodeHex(value, false); } }
package io.reon.auth; import java.util.HashMap; import io.reon.util.Hex; public abstract class AbstractAuth implements HttpAuth { public static final String REALM = "realm"; public static final String RESPONSE = "response"; public static final String NONCE = "nonce"; public static final String PK = "pk"; public static final String EQ = "=\""; public static final String EOS = "\", "; public static final String EOT = "\""; public static HashMap<String, String> parse(String text) { String[] fields = text.substring(text.indexOf(' ')+1).split(","); HashMap<String, String> attrs = new HashMap<>(); for(String field: fields) { String[] kv = field.split("="); attrs.put(kv[0].trim(), kv[1].replace('"',' ').trim()); } return attrs; } public static byte[] fromHex(String value) { return Hex.decodeHex(value); } public static String toHex(byte[] value) { return Hex.encodeHex(value, false); } }
Update comments for form clear button.
/* ========================================================================== Initialize Chosen.js ========================================================================== */ $(".chosen-select").chosen({ width: '100%', no_results_text: "Oops, nothing found!" }); /* ========================================================================== Clear form button - Clear checkboxes and selects - Clear Chosen.js elements - Clear jquery.custom-input elements ========================================================================== */ $('.js-form_clear').on('click', function() { var $this = $(this), $form = $this.parents('form'); // Clear checkboxes $form.find('[type="checkbox"]') .removeAttr('checked'); // Clear select options $form.find('select option') .removeAttr('selected'); $form.find('select option:first') .attr('selected', true); // Clear .custom-input elements $form.find('.custom-input').trigger('updateState'); // Clear Chosen.js elements $form.find('.chosen-select') .val('') .trigger("chosen:updated"); });
/* ========================================================================== Initialize Chosen.js ========================================================================== */ $(".chosen-select").chosen({ width: '100%', no_results_text: "Oops, nothing found!" }); // Reset buttons sould also reset Chosen.js elements $('.js-form_clear').on('click', function() { var $this = $(this), $form = $this.parents('form'); // Reset checkboxes $form.find('[type="checkbox"]') .removeAttr('checked'); // Reset select options $form.find('select option') .removeAttr('selected'); $form.find('select option:first') .attr('selected', true); // Reset .custom-input elements $form.find('.custom-input').trigger('updateState'); // Reset Chosen.js elements $form.find('.chosen-select') .val('') .trigger("chosen:updated"); });
Add shinken in bind dependancy
# -*- coding: utf-8 -*- ############################################################################## # # Author: Yannick Buron # Copyright 2013 Yannick Buron # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'Clouder Template Bind', 'version': '1.0', 'category': 'Community', 'depends': ['clouder','clouder_template_shinken'], 'author': 'Yannick Buron', 'license': 'AGPL-3', 'website': 'https://github.com/YannickB', 'description': """ Clouder Template Bind """, 'demo': [], 'data': ['clouder_template_bind_data.xml'], 'installable': True, 'application': True, }
# -*- coding: utf-8 -*- ############################################################################## # # Author: Yannick Buron # Copyright 2013 Yannick Buron # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'Clouder Template Bind', 'version': '1.0', 'category': 'Community', 'depends': ['clouder'], 'author': 'Yannick Buron', 'license': 'AGPL-3', 'website': 'https://github.com/YannickB', 'description': """ Clouder Template Bind """, 'demo': [], 'data': ['clouder_template_bind_data.xml'], 'installable': True, 'application': True, }
Use === instead of == to please the standard
var shell = require('shelljs') if (exec('git status --porcelain').stdout) { console.error('Git working directory not clean. Please commit all chances to release a new package to npm.') process.exit(2) } var versionIncrement = process.argv[process.argv.length - 1] var versionIncrements = ['major', 'minor', 'patch'] if (versionIncrements.indexOf(versionIncrement) < 0) { console.error('Usage: node release.js major|minor|patch') process.exit(1) } exec('npm test') var geotag = execOptional('npm run geotag') if (geotag.code === 0) { exec('git commit -m "Geotag package for release" package.json') } exec('npm version ' + versionIncrement) exec('git push') exec('git push --tags') exec('npm publish') function exec (cmd) { var ret = shell.exec(cmd, { silent: true }) if (ret.code !== 0) { console.error(ret.stdout) process.exit(1) } return ret } function execOptional (cmd) { var ret = shell.exec(cmd, { silent: true }) if (ret.code !== 0) { console.log(ret.stdout) } return ret }
var shell = require('shelljs') if (exec('git status --porcelain').stdout) { console.error('Git working directory not clean. Please commit all chances to release a new package to npm.') process.exit(2) } var versionIncrement = process.argv[process.argv.length - 1] var versionIncrements = ['major', 'minor', 'patch'] if (versionIncrements.indexOf(versionIncrement) < 0) { console.error('Usage: node release.js major|minor|patch') process.exit(1) } exec('npm test') var geotag = execOptional('npm run geotag') if (geotag.code == 0) { exec('git commit -m "Geotag package for release" package.json') } exec('npm version ' + versionIncrement) exec('git push') exec('git push --tags') exec('npm publish') function exec (cmd) { var ret = shell.exec(cmd, { silent: true }) if (ret.code !== 0) { console.error(ret.stdout) process.exit(1) } return ret } function execOptional (cmd) { var ret = shell.exec(cmd, { silent: true }) if (ret.code !== 0) { console.log(ret.stdout) } return ret }
Add component as function support
import h from 'snabbdom/h' import extend from 'extend' const sanitizeProps = (props) => { props = props === null ? {} : props Object.keys(props).map((prop) => { const keysRiver = prop.split('-').reverse() if(keysRiver.length > 1) { let newObject = keysRiver.reduce( (object, key) => ({ [key]: object }), props[prop] ) extend(true, props, newObject) delete props[prop] } else if (!(['class', 'props', 'attrs', 'style', 'on', 'hook', 'key'].indexOf(prop) > -1)) { extend(true, props, {props: { [prop]: props[prop] } }) delete props[prop] } }) return props } const sanitizeChilds = (children) => { return children.length === 1 && typeof children[0] === 'string' ? children[0] : children } export const createElement = (type, props, ...children) => { return (typeof type === 'function') ? type(props, children) : h(type, sanitizeProps(props), sanitizeChilds(children)) } export default { createElement }
import h from 'snabbdom/h' import extend from 'extend' const sanitizeProps = (props) => { props = props === null ? {} : props Object.keys(props).map((prop) => { const keysRiver = prop.split('-').reverse() if(keysRiver.length > 1) { let newObject = keysRiver.reduce( (object, key) => ({ [key]: object }), props[prop] ) extend(true, props, newObject) delete props[prop] } else if (!(['class', 'props', 'attrs', 'style', 'on', 'hook', 'key'].indexOf(prop) > -1)) { extend(true, props, {props: { [prop]: props[prop] } }) delete props[prop] } }) return props } const sanitizeChilds = (children) => { return children.length === 1 && typeof children[0] === 'string' ? children[0] : children } export const createElement = (type, props, ...children) => { return h(type, sanitizeProps(props), sanitizeChilds(children)) } export default { createElement }
Add context for page templates
var Templating = require('../templating'); var TemplateEngine = require('../models/templateEngine'); var Api = require('../api'); var Plugins = require('../plugins'); var defaultBlocks = require('../constants/defaultBlocks'); var defaultFilters = require('../constants/defaultFilters'); /** Create template engine for an output. It adds default filters/blocks, then add the ones from plugins @param {Output} output @return {TemplateEngine} */ function createTemplateEngine(output) { var plugins = output.getPlugins(); var book = output.getBook(); var rootFolder = book.getContentRoot(); var logger = book.getLogger(); var filters = Plugins.listFilters(plugins); var blocks = Plugins.listBlocks(plugins); // Extend with default blocks = defaultBlocks.merge(blocks); filters = defaultFilters.merge(filters); // Create loader var loader = new Templating.ConrefsLoader(rootFolder, logger); // Create API context var context = Api.encodeGlobal(output); return new TemplateEngine({ filters: filters, blocks: blocks, loader: loader, context: context }); } module.exports = createTemplateEngine;
var Immutable = require('immutable'); var Templating = require('../templating'); var TemplateEngine = require('../models/templateEngine'); var Plugins = require('../plugins'); var defaultBlocks = require('../constants/defaultBlocks'); var defaultFilters = require('../constants/defaultFilters'); /** Create template engine for an output. It adds default filters/blocks, then add the ones from plugins @param {Output} output @return {TemplateEngine} */ function createTemplateEngine(output) { var plugins = output.getPlugins(); var book = output.getBook(); var rootFolder = book.getContentRoot(); var logger = book.getLogger(); var filters = Plugins.listFilters(plugins); var blocks = Plugins.listBlocks(plugins); // Extend with default blocks = defaultBlocks.merge(blocks); filters = defaultFilters.merge(filters); // Create loader var loader = new Templating.ConrefsLoader(rootFolder, logger); return new TemplateEngine({ filters: filters, blocks: blocks, loader: loader // todo: build context for filters/blocks }); } module.exports = createTemplateEngine;
Make site optional for RenderEvironment
<?php class CM_RenderEnvironment extends CM_Class_Abstract { /** @var CM_Model_User|null */ protected $_viewer; /** @var CM_Site_Abstract */ protected $_site; /** * @param CM_Site_Abstract|null $site * @param CM_Model_User|null $viewer */ public function __construct(CM_Site_Abstract $site = null, CM_Model_User $viewer = null) { if (!$site) { $site = CM_Site_Abstract::factory(); } $this->_site = $site; $this->_viewer = $viewer; } /** * @return \CM_Site_Abstract */ public function getSite() { return $this->_site; } /** * @param boolean|null $needed * @return CM_Model_User|null * @throws CM_Exception_AuthRequired */ public function getViewer($needed = null) { if (!$this->_viewer) { if ($needed) { throw new CM_Exception_AuthRequired(); } return null; } return $this->_viewer; } }
<?php class CM_RenderEnvironment extends CM_Class_Abstract { /** @var CM_Model_User|null */ protected $_viewer; /** @var CM_Site_Abstract */ protected $_site; /** * @param CM_Site_Abstract $site * @param CM_Model_User|null $viewer */ public function __construct(CM_Site_Abstract $site, CM_Model_User $viewer = null) { if (!$site) { $site = CM_Site_Abstract::factory(); } $this->_site = $site; $this->_viewer = $viewer; } /** * @return \CM_Site_Abstract */ public function getSite() { return $this->_site; } /** * @param boolean|null $needed * @return CM_Model_User|null * @throws CM_Exception_AuthRequired */ public function getViewer($needed = null) { if (!$this->_viewer) { if ($needed) { throw new CM_Exception_AuthRequired(); } return null; } return $this->_viewer; } }
Make test independent of whatever else is in the database. Also, use a different way of calling subprocess.Popen so that we can use quotes and dollars without having to do difficult cross-architectural escaping.
import os, sys try: import sybprocess except ImportError: # user private copy for old Python versions import MonetDBtesting.subprocess26 as subprocess def client(cmd, input = None): clt = subprocess.Popen(cmd, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, universal_newlines = True) out, err = clt.communicate(input) sys.stdout.write(out) sys.stderr.write(err) def main(): xq_client = os.getenv('XQUERY_CLIENT').split() client(xq_client + ['--input=my-document', '--collection=my-collection'], '<document>test document</document>') client(xq_client + ['-s', 'for $doc in pf:documents() where $doc/@url = "my-document" return $doc']) client(xq_client + ['-s', 'pf:del-doc("my-document")']) main()
import os, sys try: import sybprocess except ImportError: # user private copy for old Python versions import MonetDBtesting.subprocess26 as subprocess def client(cmd, input = None): clt = subprocess.Popen(cmd, shell = True, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, universal_newlines = True) out, err = clt.communicate(input) sys.stdout.write(out) sys.stderr.write(err) def main(): xq_client = os.getenv('XQUERY_CLIENT') client('%s --input=my-document --collection=my-collection' % xq_client, '<document>test document</document>') client('%s -s "pf:documents()"' % xq_client) client('%s -s "pf:del-doc(\'my-document\')"' % xq_client) main()
Fix typo in new class comment. GITHUB_BREAKING_CHANGES=n/a ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=260048297
/* * Copyright 2019 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. */ package com.google.template.soy.error; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.collect.ImmutableList; /** * An unrecoverable exception in the Soy compiler. Reports parse errors found before the compiler * failed. */ public final class SoyInternalCompilerException extends RuntimeException { private final ImmutableList<SoyError> errors; public SoyInternalCompilerException(Iterable<SoyError> errors, Throwable cause) { super(cause); this.errors = ImmutableList.sortedCopyOf(errors); checkArgument(!this.errors.isEmpty()); } @Override public String getMessage() { return "Unrecoverable internal Soy error. Prior to failure found " + SoyErrors.formatErrors(errors); } }
/* * Copyright 2019 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. */ package com.google.template.soy.error; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.collect.ImmutableList; /** * An unrecoverable exception in the Soy compiler. Reports parse errors found before the the * compiler failed. */ public final class SoyInternalCompilerException extends RuntimeException { private final ImmutableList<SoyError> errors; public SoyInternalCompilerException(Iterable<SoyError> errors, Throwable cause) { super(cause); this.errors = ImmutableList.sortedCopyOf(errors); checkArgument(!this.errors.isEmpty()); } @Override public String getMessage() { return "Unrecoverable internal Soy error. Prior to failure found " + SoyErrors.formatErrors(errors); } }
Allow Database to receive a connection string.
var util = require('util'); var mongoose = require('mongoose'); var Grid = require('gridfs-stream') var Datastore = function(config) { this._config = config; this._masters = config.database.masters; this._slaves = config.database.read; } util.inherits( Datastore , require('events').EventEmitter ); Datastore.prototype.connectionString = function() { var config = this._config; if (config.database.string) { return config.database.string; } else { return 'mongodb://' + config.database.masters.join(',') + '/' + config.database.name; } } Datastore.prototype.connect = function( done ) { var self = this; if (!done) var done = new Function(); // we should always create a new connection, as the singleton model // will get in the way of asynchronous processes, like tests, which // attempt to close the connection as part of their testing //self.connection = mongoose.createConnection( self.connectionString() ); //self.connection.on('open', done ); mongoose.connect( self.connectionString() ); self.mongoose = mongoose; // <- temporary hack self.db = mongoose.connection; self.db.once('open', function() { self.gfs = Grid( self.db.db , mongoose.mongo ); self.emit('ready'); done(); }); } Datastore.prototype.disconnect = function( done ) { var self = this; mongoose.disconnect( done ); } /* export a copy of our Datastore */ module.exports = Datastore;
var util = require('util'); var mongoose = require('mongoose'); var Grid = require('gridfs-stream') var Datastore = function(config) { this._config = config; this._masters = config.database.masters; this._slaves = config.database.read; } util.inherits( Datastore , require('events').EventEmitter ); Datastore.prototype.connectionString = function() { var config = this._config; return 'mongodb://' + config.database.masters.join(',') + '/' + config.database.name; } Datastore.prototype.connect = function( done ) { var self = this; if (!done) var done = new Function(); // we should always create a new connection, as the singleton model // will get in the way of asynchronous processes, like tests, which // attempt to close the connection as part of their testing //self.connection = mongoose.createConnection( self.connectionString() ); //self.connection.on('open', done ); mongoose.connect( self.connectionString() ); self.mongoose = mongoose; // <- temporary hack self.db = mongoose.connection; self.db.once('open', function() { self.gfs = Grid( self.db.db , mongoose.mongo ); self.emit('ready'); done(); }); } Datastore.prototype.disconnect = function( done ) { var self = this; mongoose.disconnect( done ); } /* export a copy of our Datastore */ module.exports = Datastore;
Fix options passed to es6-transpiler Otherwise, `options` is useless.
var es6tr = require("es6-transpiler"); var createES6TranspilerPreprocessor = function(args, config, logger, helper) { config = config || {}; var log = logger.create('preprocessor.es6-transpiler'); var defaultOptions = { }; var options = helper.merge(defaultOptions, args.options || {}, config.options || {}); var transformPath = args.transformPath || config.transformPath || function(filepath) { return filepath.replace(/\.es6.js$/, '.js').replace(/\.es6$/, '.js'); }; return function(content, file, done) { log.info('Processing "%s".', file.originalPath); file.path = transformPath(file.originalPath); options.filename = file.originalPath; var result = es6tr.run(options); var transpiledContent = result.src; result.errors.forEach(function(err) { log.error(err); }); if (result.errors.length) { return done(new Error('ES6-TRANSPILER COMPILE ERRORS\n' + result.errors.join('\n'))); } // TODO: add sourceMap to transpiledContent return done(null, transpiledContent); }; }; createES6TranspilerPreprocessor.$inject = ['args', 'config.es6TranspilerPreprocessor', 'logger', 'helper']; // export es6-transpiler preprocessor module.exports = { 'preprocessor:es6-transpiler': ['factory', createES6TranspilerPreprocessor] };
var es6tr = require("es6-transpiler"); var createES6TranspilerPreprocessor = function(args, config, logger, helper) { config = config || {}; var log = logger.create('preprocessor.es6-transpiler'); var defaultOptions = { }; var options = helper.merge(defaultOptions, args.options || {}, config.options || {}); var transformPath = args.transformPath || config.transformPath || function(filepath) { return filepath.replace(/\.es6.js$/, '.js').replace(/\.es6$/, '.js'); }; return function(content, file, done) { log.info('Processing "%s".', file.originalPath); file.path = transformPath(file.originalPath); options.filename = file.originalPath; var result = es6tr.run({ filename: options.filename }); var transpiledContent = result.src; result.errors.forEach(function(err) { log.error(err); }); if (result.errors.length) { return done(new Error('ES6-TRANSPILER COMPILE ERRORS\n' + result.errors.join('\n'))); } // TODO: add sourceMap to transpiledContent return done(null, transpiledContent); }; }; createES6TranspilerPreprocessor.$inject = ['args', 'config.es6TranspilerPreprocessor', 'logger', 'helper']; // export es6-transpiler preprocessor module.exports = { 'preprocessor:es6-transpiler': ['factory', createES6TranspilerPreprocessor] };
Simplify the groupfinder a little. In general we should try to use session.query(...).get() rather than .filter().
from sqlalchemy.orm.exc import NoResultFound from .storage import ( DBSession, UserMap, ) def groupfinder(login, request): if ':' not in login: return None namespace, localname = login.split(':', 1) if namespace == 'mailto': session = DBSession() model = session.query(UserMap).get(login) if model is None: return None user = model.user principals = ['userid:' + str(user.rid)] principals.extend('lab:' + lab_uuid for lab_uuid in user.statement.object.get('lab_uuids', [])) return principals elif namespace == 'remoteuser': if localname in ['TEST', 'IMPORT']: return ['group:admin']
from sqlalchemy.orm.exc import NoResultFound from .storage import ( DBSession, UserMap, ) def groupfinder(login, request): if ':' not in login: return None namespace, localname = login.split(':', 1) if namespace == 'mailto': session = DBSession() query = session.query(UserMap).filter(UserMap.login == login) try: user = query.one().user principals = ['userid:' + str(user.rid)] principals.extend('lab:' + lab_uuid for lab_uuid in user.statement.object.get('lab_uuids', [])) return principals except NoResultFound: return None elif namespace == 'remoteuser': if localname in ['TEST', 'IMPORT']: return ['group:admin']
Make 'delete' default to `no_output` true
'use strict'; const { EngineError } = require('../../../error'); // Sets modifiers.noOutput, by using args.no_output // It only flags that part of the response is to be removed, // but it's up to the main interface middleware to actually remove it const noOutputSet = function () { return async function noOutputSet(input) { const flaggedAction = flagNoOutput(input); const response = await this.next(input); if (flaggedAction) { response.modifiers.noOutput = flaggedAction; } return response; }; }; const flagNoOutput = function ({ args, fullAction, action }) { let { no_output: noOutput } = args; if (noOutput === undefined) { // Delete actions use no_output by default if (action.type === 'delete') { noOutput = true; } else { return; } } // Do not pass args.no_output to next layers delete args.no_output; if (noOutput === false) { return; } if (typeof noOutput !== 'boolean') { const message = `Wrong parameters: 'no_output' must be true of false, not '${noOutput}'`; throw new EngineError(message, { reason: 'INPUT_VALIDATION' }); } return fullAction; }; module.exports = { noOutputSet, };
'use strict'; const { EngineError } = require('../../../error'); // Sets modifiers.noOutput, by using args.no_output // It only flags that part of the response is to be removed, // but it's up to the main interface middleware to actually remove it const noOutputSet = function () { return async function noOutputSet(input) { const flaggedAction = flagNoOutput(input); const response = await this.next(input); if (flaggedAction) { response.modifiers.noOutput = flaggedAction; } return response; }; }; const flagNoOutput = function ({ args, fullAction }) { const { no_output: noOutput } = args; if (noOutput === undefined) { return; } // Do not pass args.no_output to next layers delete args.no_output; if (noOutput === false) { return; } if (typeof noOutput !== 'boolean') { const message = `Wrong parameters: 'no_output' must be true of false, not '${noOutput}'`; throw new EngineError(message, { reason: 'INPUT_VALIDATION' }); } return fullAction; }; module.exports = { noOutputSet, };
Fix: Use anonymous class as test double Co-authored-by: Andreas Möller <96e8155732e8324ae26f64d4516eb6fe696ac84f@localheinz.com> Co-authored-by: Arne Blankerts <2d7739f42ebd62662a710577d3d9078342a69dee@Blankerts.de>
<?php declare(strict_types=1); /* * This file is part of PHPUnit. * * (c) Sebastian Bergmann <sebastian@phpunit.de> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Event\Test; use PHPUnit\Framework\TestCase; /** * @covers \PHPUnit\Event\Test\AfterTest */ final class AfterTestTest extends TestCase { public function testConstructorSetsValues(): void { $test = new Test(); $result = new class implements Result { public function is(Result $other): bool { return false; } public function asString(): string { return get_class($this); } }; $event = new AfterTest( $test, $result ); $this->assertSame($test, $event->test()); $this->assertSame($result, $event->result()); } }
<?php declare(strict_types=1); /* * This file is part of PHPUnit. * * (c) Sebastian Bergmann <sebastian@phpunit.de> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Event\Test; use PHPUnit\Framework\TestCase; /** * @covers \PHPUnit\Event\Test\AfterTest */ final class AfterTestTest extends TestCase { public function testConstructorSetsValues(): void { $test = new Test(); $result = $this->createMock(Result::class); $event = new AfterTest( $test, $result ); $this->assertSame($test, $event->test()); $this->assertSame($result, $event->result()); } }
GPII-1852: Fix for (quietly reported) test failure in registryResolver
/* * Windows Utilities Unit Tests * * Copyright 2015 Raising the Floor - International * * Licensed under the New BSD license. You may not use this file except in * compliance with this License. * * The research leading to these results has received funding from the European Union's * Seventh Framework Programme (FP7/2007-2013) * under grant agreement no. 289016. * * You may obtain a copy of the License at * https://github.com/GPII/universal/blob/master/LICENSE.txt */ "use strict"; var fluid = require("universal"); var jqUnit = fluid.require("node-jqunit"); var gpii = fluid.registerNamespace("gpii"); fluid.registerNamespace("gpii.tests.windows.registryResolver"); require("../src/RegistryResolver.js"); jqUnit.module("Registry Resolver"); jqUnit.test("Test Boolean Registry Lookups", function () { jqUnit.expect(2); jqUnit.assertTrue("Testing a registry key that always exists.", gpii.deviceReporter.registryKeyExists("HKEY_CURRENT_USER", "Software\\Microsoft\\Command Processor", "CompletionChar", "REG_DWORD")); jqUnit.assertFalse("Testing a registry key that does not exist.", gpii.deviceReporter.registryKeyExists("HKEY_CURRENT_USER", "Software\\Microsoft\\ScreenMagnifier", "NotARealSubPath", "REG_DWORD")); });
/* * Windows Utilities Unit Tests * * Copyright 2015 Raising the Floor - International * * Licensed under the New BSD license. You may not use this file except in * compliance with this License. * * The research leading to these results has received funding from the European Union's * Seventh Framework Programme (FP7/2007-2013) * under grant agreement no. 289016. * * You may obtain a copy of the License at * https://github.com/GPII/universal/blob/master/LICENSE.txt */ "use strict"; var fluid = require("universal"); var jqUnit = fluid.require("jqUnit"); var gpii = fluid.registerNamespace("gpii"); fluid.registerNamespace("gpii.tests.windows.registryResolver"); fluid.require("%gpii-windows"); jqUnit.module("Registry Resolver"); jqUnit.test("Test Boolean Registry Lookups", function () { jqUnit.expect(2); jqUnit.assertTrue("Testing a registry key that always exists.", gpii.deviceReporter.registryKeyExists("HKEY_CURRENT_USER", "Software\\Microsoft\\Command Processor", "CompletionChar", "REG_DWORD")); jqUnit.assertFalse("Testing a registry key that does not exist.", gpii.deviceReporter.registryKeyExists("HKEY_CURRENT_USER", "Software\\Microsoft\\ScreenMagnifier", "NotARealSubPath", "REG_DWORD")); });
Add unmatched_legislator to the spec
from .base import BaseImporter class MembershipImporter(BaseImporter): _type = 'membership' def __init__(self, jurisdiction_id, person_importer, org_importer): super(MembershipImporter, self).__init__(jurisdiction_id) self.person_importer = person_importer self.org_importer = org_importer def get_db_spec(self, membership): spec = {'organization_id': membership['organization_id'], 'person_id': membership['person_id'], 'role': membership['role'], # if this is a historical role, only update historical roles 'end_date': membership.get('end_date') } if 'unmatched_legislator' in membership: spec['unmatched_legislator'] = membership['unmatched_legislator'] return spec def prepare_object_from_json(self, obj): org_json_id = obj['organization_id'] obj['organization_id'] = self.org_importer.resolve_json_id(org_json_id) person_json_id = obj['person_id'] obj['person_id'] = self.person_importer.resolve_json_id(person_json_id) return obj
from .base import BaseImporter class MembershipImporter(BaseImporter): _type = 'membership' def __init__(self, jurisdiction_id, person_importer, org_importer): super(MembershipImporter, self).__init__(jurisdiction_id) self.person_importer = person_importer self.org_importer = org_importer def get_db_spec(self, membership): spec = {'organization_id': membership['organization_id'], 'person_id': membership['person_id'], 'role': membership['role'], # if this is a historical role, only update historical roles 'end_date': membership.get('end_date') } return spec def prepare_object_from_json(self, obj): org_json_id = obj['organization_id'] obj['organization_id'] = self.org_importer.resolve_json_id(org_json_id) person_json_id = obj['person_id'] obj['person_id'] = self.person_importer.resolve_json_id(person_json_id) return obj
Add error checking in servlet and remove hardcoded event id.
package com.google.sps.servlets; import com.google.sps.data.VolunteeringOpportunity; import com.google.sps.utilities.CommonUtils; import com.google.sps.utilities.DatabaseConstants; import com.google.sps.utilities.SpannerTasks; import java.io.IOException; import java.util.Set; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** Servlet to get all volunteering data for a given event */ @WebServlet("/event-volunteering-data") public class EventVolunteeringDataServlet extends HttpServlet { private static final String EVENT_ID = "event-id"; /** * Queries database for all opportunities with event ID given in the request parameter and writes * opportunities to the response. * * @param request servlet request * @param response servlet response * @throws IOException if Input/Output error occurs */ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String eventId = request.getParameter(EVENT_ID); if (eventId == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, String.format("No event specified.")); return; } Set<VolunteeringOpportunity> opportunities = SpannerTasks.getVolunteeringOpportunitiesByEventId(eventId); response.setContentType("application/json;"); response.getWriter().println(CommonUtils.convertToJson(opportunities)); } }
package com.google.sps.servlets; import com.google.sps.data.VolunteeringOpportunity; import com.google.sps.utilities.CommonUtils; import com.google.sps.utilities.DatabaseConstants; import com.google.sps.utilities.SpannerTasks; import java.io.IOException; import java.util.Set; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** Servlet to get all volunteering data for a given event */ @WebServlet("/event-volunteering-data") public class EventVolunteeringDataServlet extends HttpServlet { private static final String HARDCODED_EVENT_ID = "0883de79-17d7-49a3-a866-dbd5135062a8"; /** * Queries database for all opportunities with event ID given in the request parameter and writes * opportunities to the response. * * @param request servlet request * @param response servlet response * @throws IOException if Input/Output error occurs */ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { // TO DO: change eventId to parameter value Set<VolunteeringOpportunity> opportunities = SpannerTasks.getVolunteeringOpportunitiesByEventId(HARDCODED_EVENT_ID); response.setContentType("application/json;"); response.getWriter().println(CommonUtils.convertToJson(opportunities)); } }
Update ban_datetime on allowed status change
package v1 import ( "time" "git.zxq.co/ripple/rippleapi/common" ) type setAllowedData struct { UserID int `json:"user_id"` Allowed int `json:"allowed"` } // UserManageSetAllowedPOST allows to set the allowed status of an user. func UserManageSetAllowedPOST(md common.MethodData) common.CodeMessager { data := setAllowedData{} if err := md.RequestData.Unmarshal(&data); err != nil { return ErrBadJSON } if data.Allowed < 0 || data.Allowed > 2 { return common.SimpleResponse(400, "Allowed status must be between 0 and 2") } var banDatetime int64 if data.Allowed == 0 { banDatetime = time.Now().Unix() } _, err := md.DB.Exec("UPDATE users SET allowed = ?, ban_datetime = ? WHERE id = ?", data.Allowed, banDatetime, data.UserID) if err != nil { md.Err(err) return Err500 } query := ` SELECT users.id, users.username, register_datetime, rank, latest_activity, users_stats.username_aka, users_stats.country, users_stats.show_country FROM users LEFT JOIN users_stats ON users.id=users_stats.id WHERE users.id=? LIMIT 1` return userPuts(md, md.DB.QueryRow(query, data.UserID)) }
package v1 import "git.zxq.co/ripple/rippleapi/common" type setAllowedData struct { UserID int `json:"user_id"` Allowed int `json:"allowed"` } // UserManageSetAllowedPOST allows to set the allowed status of an user. func UserManageSetAllowedPOST(md common.MethodData) common.CodeMessager { data := setAllowedData{} if err := md.RequestData.Unmarshal(&data); err != nil { return ErrBadJSON } if data.Allowed < 0 || data.Allowed > 2 { return common.SimpleResponse(400, "Allowed status must be between 0 and 2") } _, err := md.DB.Exec("UPDATE users SET allowed = ? WHERE id = ?", data.Allowed, data.UserID) if err != nil { md.Err(err) return Err500 } query := ` SELECT users.id, users.username, register_datetime, rank, latest_activity, users_stats.username_aka, users_stats.country, users_stats.show_country FROM users LEFT JOIN users_stats ON users.id=users_stats.id WHERE users.id=? LIMIT 1` return userPuts(md, md.DB.QueryRow(query, data.UserID)) }
Fix translation extraction. Was breaking because it only pulls from js and html. TS doesn't work. Changed to pull from the build files folder instead.
var gulp = require( 'gulp' ); var plugins = require( 'gulp-load-plugins' )(); var sequence = require( 'run-sequence' ); var renameLangs = require( '../plugins/gulp-rename-langs.js' ); var splitTranslations = require( '../plugins/gulp-split-translations.js' ); var sanitizeTranslations = require( '../plugins/gulp-sanitize-translations.js' ); module.exports = function( config ) { gulp.task( 'translations:extract', function() { return gulp.src( [ 'build/dev/**/*.{js,html}', ] ) .pipe( plugins.angularGettext.extract( 'main.pot' ) ) .pipe( gulp.dest( 'build/translations' ) ); } ); gulp.task( 'translations:compile', function() { return gulp.src( config.libDir + '/' + config.translations + '/**/*.po' ) .pipe( plugins.angularGettext.compile( { format: 'json', } ) ) // Works around a difference in poeditor and angular-gettext: en-us -> en_US. .pipe( renameLangs() ) .pipe( sanitizeTranslations() ) .pipe( splitTranslations( config.translationSections ) ) .pipe( gulp.dest( config.buildDir + '/translations' ) ); } ); };
var gulp = require( 'gulp' ); var plugins = require( 'gulp-load-plugins' )(); var sequence = require( 'run-sequence' ); var renameLangs = require( '../plugins/gulp-rename-langs.js' ); var splitTranslations = require( '../plugins/gulp-split-translations.js' ); var sanitizeTranslations = require( '../plugins/gulp-sanitize-translations.js' ); module.exports = function( config ) { gulp.task( 'translations:extract', function() { return gulp.src( [ 'src/**/*.{js,html}', '!src/bower-lib/**/*', ] ) .pipe( plugins.angularGettext.extract( 'main.pot' ) ) .pipe( gulp.dest( 'build/translations' ) ); } ); gulp.task( 'translations:compile', function() { return gulp.src( config.libDir + '/' + config.translations + '/**/*.po' ) .pipe( plugins.angularGettext.compile( { format: 'json', } ) ) // Works around a difference in poeditor and angular-gettext: en-us -> en_US. .pipe( renameLangs() ) .pipe( sanitizeTranslations() ) .pipe( splitTranslations( config.translationSections ) ) .pipe( gulp.dest( config.buildDir + '/translations' ) ); } ); };
Fix new form template requirement
/** * Add app view */ var _ = require('underscore'); var Backbone = require('backbone'); var templates = require('../../dist/'); var App = require('../../models/app'); module.exports = Backbone.View.extend({ tagName : 'article', className : 'section', template : templates.addAppForm, $appName : null, events : { 'click #addAppBtn' : 'addApp' }, render : function () { var tmpl = _.template(this.template, { variable : 'data' }); this.$el.html(tmpl({ formModel : 'application' })); this.$appName = this.$el.find('#addAppName'); return this; }, addApp : function () { var name = this.$appName.val(); var app = new App({ name : name }); if(!app.isValid()) return; app.save([], { success : function (model) { this.clean(); this.trigger('new_app', model); }.bind(this), error : function (model, response) { alert('Error adding application'); console.log(response.responseText); }.bind(this) }); }, clean : function () { this.$appName.val(''); } });
/** * Add app view */ var _ = require('underscore'); var Backbone = require('backbone'); var templates = require('../../dist/'); var App = require('../../models/app'); module.exports = Backbone.View.extend({ tagName : 'article', className : 'section', template : templates.addAppForm, $appName : null, events : { 'click #addAppBtn' : 'addApp' }, render : function () { var tmpl = _.template(this.template, { variable : 'data' }); this.$el.html(tmpl()); this.$appName = this.$el.find('#addAppName'); return this; }, addApp : function () { var name = this.$appName.val(); var app = new App({ name : name }); if(!app.isValid()) return; app.save([], { success : function (model) { this.clean(); this.trigger('new_app', model); }.bind(this), error : function (model, response) { alert('Error adding application'); console.log(response.responseText); }.bind(this) }); }, clean : function () { this.$appName.val(''); } });
Disable int tag collectors test
package edu.columbia.cs.psl.test.phosphor; import org.junit.Test; import java.util.Arrays; import java.util.List; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.IntStream; public class LambdaIntTagITCase { // This is known to not work correctly on int tags. It may never be possible to make it work completely on int tags, because // we need to add a fake parameter to every modified constructor to make sure that it is unique. But, we can't do that // for cases where INVOKEDYNAMIC binds a constructor to a non-constructor call (although maybe we can fix this, not enough // time to look into it now) // @Test // public void testCollectors() throws Exception{ // List<String> givenList = Arrays.asList("a", "bb", "ccc", "dd"); // givenList.stream().collect(Collectors.toList()); // // } @Test public void testEmptyLambda() throws Exception { Runnable r = () -> { }; } @Test public void testIntStreamsDontCrash() throws Exception { int sum = IntStream.of(1, 2, 3, 4, 5).sum(); //creates a bunch of lambdas } @Test public void testSupplier() throws Exception { Supplier<double[]> supplier = () -> new double[3]; double[] d = supplier.get(); } }
package edu.columbia.cs.psl.test.phosphor; import org.junit.Test; import java.util.Arrays; import java.util.List; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.IntStream; public class LambdaIntTagITCase { @Test public void testCollectors() throws Exception{ List<String> givenList = Arrays.asList("a", "bb", "ccc", "dd"); givenList.stream().collect(Collectors.toList()); } @Test public void testEmptyLambda() throws Exception { Runnable r = () -> { }; } @Test public void testIntStreamsDontCrash() throws Exception { int sum = IntStream.of(1, 2, 3, 4, 5).sum(); //creates a bunch of lambdas } @Test public void testSupplier() throws Exception { Supplier<double[]> supplier = () -> new double[3]; double[] d = supplier.get(); } }
Fix page type identifier generator
<?php namespace Soda\Cms\Models; use Exception; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; use Soda\Cms\Models\Traits\DraftableTrait; use Soda\Cms\Models\Traits\DynamicCreatorTrait; use Soda\Cms\Models\Traits\OptionallyInApplicationTrait; class PageType extends AbstractDynamicType { use OptionallyInApplicationTrait, DraftableTrait; protected $table = 'page_types'; public $fillable = [ 'name', 'identifier', 'description', 'application_id', 'status', 'position', 'package', 'action', 'action_type', 'edit_action', 'edit_action_type', ]; public function fields() { return $this->morphToMany(Field::class, 'fieldable'); } public function block() { return $this->hasMany(Block::class, 'block_type_id'); } public function setIdentifierAttribute($value) { $this->attributes['identifier'] = str_slug($value, '_'); } }
<?php namespace Soda\Cms\Models; use Exception; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; use Soda\Cms\Models\Traits\DraftableTrait; use Soda\Cms\Models\Traits\DynamicCreatorTrait; use Soda\Cms\Models\Traits\OptionallyInApplicationTrait; class PageType extends AbstractDynamicType { use OptionallyInApplicationTrait, DraftableTrait; protected $table = 'page_types'; public $fillable = [ 'name', 'identifier', 'description', 'application_id', 'status', 'position', 'package', 'action', 'action_type', 'edit_action', 'edit_action_type', ]; public function fields() { return $this->morphToMany(Field::class, 'fieldable'); } public function block() { return $this->hasMany(Block::class, 'block_type_id'); } public function setIdentifierAttribute($value) { $this->attributes['identifier'] = str_slug($value); } }
Use ma.owl with MA test, not mp file.
package org.mousephenotype.cda.loads.cdaloader; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mousephenotype.cda.db.pojo.OntologyTerm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.validation.constraints.NotNull; import java.util.List; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = {TestConfigLoaders.class} ) @TestPropertySource(locations = {"file:${user.home}/configfiles/${profile}/test.properties"}) public class OntologyParserTest { private OntologyParser ontologyParser; private final Logger logger = LoggerFactory.getLogger(this.getClass()); @NotNull @Value("${owlPath}") protected String owlPath; @Before public void setUp() throws Exception { Sy String path = owlPath + "/ma.owl"; String prefix = "MA"; ontologyParser = new OntologyParser(path, prefix); } @Test public void testgetTerms() { List<OntologyTerm> terms = ontologyParser.getTerms(); Assert.assertTrue(terms.size() > 1000); } }
package org.mousephenotype.cda.loads.cdaloader; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mousephenotype.cda.db.pojo.OntologyTerm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.validation.constraints.NotNull; import java.util.List; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = {TestConfigLoaders.class} ) @TestPropertySource(locations = {"file:${user.home}/configfiles/${profile}/test.properties"}) public class OntologyParserTest { private OntologyParser ontologyParser; private final Logger logger = LoggerFactory.getLogger(this.getClass()); @NotNull @Value("${owlPath}") protected String owlPath; @Before public void setUp() throws Exception { String path = owlPath + "/mp.owl"; String prefix = "MA"; ontologyParser = new OntologyParser(path, prefix); } @Test public void testgetTerms() { List<OntologyTerm> terms = ontologyParser.getTerms(); Assert.assertTrue(terms.size() > 1000); } }
Fix path to enable the app to start
/** Potential server side rendering strategy 1. ask flux dispatcher to start tracking new store requests 2. start the render - this is syncronis so any store request that happen during render are of concern 3. ask flux dispatcher to stop tracking and notify when all tracked request have been resolved 4. repeat set 1-3 till no more requests are being produced (cap max number of renders) 5. once no more requests are being produced take the render output and return page Some modules may have data dependency causing a new module to be rendered. These in turn may have more data dependencies. Hence the need for step 4. */ require('node-jsx').install({harmony: true}); var fs = require("fs"); var React = require("react"); var App = require("../../client/app/components/app"); var router = require('express').Router({caseSensitive: true, strict: true}); //only read on startup var template = fs.readFileSync(__dirname + "/../../client/app.html", {encoding:'utf8'}); function renderToHtml(route, callback){ //render the app var body = React.renderComponentToString( App() ); //merge body into template var html = template.replace(/<\/body>/, body + "</body>"); process.nextTick(function(){ callback(null, html); }); } //wildcard route to pass to react client app router.get('*', function(req, res) { renderToHtml(req.url, function(err, html){ res.send(html); }); }); module.exports = router;
/** Potential server side rendering strategy 1. ask flux dispatcher to start tracking new store requests 2. start the render - this is syncronis so any store request that happen during render are of concern 3. ask flux dispatcher to stop tracking and notify when all tracked request have been resolved 4. repeat set 1-3 till no more requests are being produced (cap max number of renders) 5. once no more requests are being produced take the render output and return page Some modules may have data dependency causing a new module to be rendered. These in turn may have more data dependencies. Hence the need for step 4. */ require('node-jsx').install({harmony: true}); var fs = require("fs"); var React = require("react"); var App = require("../../client/app/app"); var router = require('express').Router({caseSensitive: true, strict: true}); //only read on startup var template = fs.readFileSync(__dirname + "/../../client/app.html", {encoding:'utf8'}); function renderToHtml(route, callback){ //render the app var body = React.renderComponentToString( App() ); //merge body into template var html = template.replace(/<\/body>/, body + "</body>"); process.nextTick(function(){ callback(null, html); }); } //wildcard route to pass to react client app router.get('*', function(req, res) { renderToHtml(req.url, function(err, html){ res.send(html); }); }); module.exports = router;
Add .owl extension for rdf conversion
package de.linkvt.bachelor.config; import de.linkvt.bachelor.web.converter.OntologyHttpMessageConverter; import de.linkvt.bachelor.web.converter.RdfXmlOntologyHttpMessageConverter; import de.linkvt.bachelor.web.converter.TurtleOntologyHttpMessageConverter; import org.springframework.boot.autoconfigure.web.HttpMessageConverters; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * Configures the web module. */ @Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter { @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { configurer.ignoreAcceptHeader(true) .mediaType("owl", MediaType.TEXT_XML) .mediaType("rdf", MediaType.TEXT_XML) .mediaType("xml", MediaType.TEXT_XML) .mediaType("ttl", MediaType.TEXT_PLAIN); } @Bean public HttpMessageConverters customConverters() { OntologyHttpMessageConverter turtleConverter = new TurtleOntologyHttpMessageConverter(); OntologyHttpMessageConverter rdfConverter = new RdfXmlOntologyHttpMessageConverter(); return new HttpMessageConverters(turtleConverter, rdfConverter); } }
package de.linkvt.bachelor.config; import de.linkvt.bachelor.web.converter.OntologyHttpMessageConverter; import de.linkvt.bachelor.web.converter.RdfXmlOntologyHttpMessageConverter; import de.linkvt.bachelor.web.converter.TurtleOntologyHttpMessageConverter; import org.springframework.boot.autoconfigure.web.HttpMessageConverters; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * Configures the web module. */ @Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter { @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { configurer.ignoreAcceptHeader(true) .mediaType("rdf", MediaType.TEXT_XML) .mediaType("xml", MediaType.TEXT_XML) .mediaType("ttl", MediaType.TEXT_PLAIN); } @Bean public HttpMessageConverters customConverters() { OntologyHttpMessageConverter turtleConverter = new TurtleOntologyHttpMessageConverter(); OntologyHttpMessageConverter rdfConverter = new RdfXmlOntologyHttpMessageConverter(); return new HttpMessageConverters(turtleConverter, rdfConverter); } }
Remove global binding that is now not needed anymore
(function () { 'use strict'; function fetchPonyfill(options) { var Promise = options && options.Promise || self.Promise; var XMLHttpRequest = options && options.XMLHttpRequest || self.XMLHttpRequest; var global = self; return (function () { var self = Object.create(global, { fetch: { value: undefined, writable: true } }); // {{whatwgFetch}} return { fetch: self.fetch, Headers: self.Headers, Request: self.Request, Response: self.Response }; }()); } if (typeof define === 'function' && define.amd) { define(function () { return fetchPonyfill; }); } else if (typeof exports === 'object') { module.exports = fetchPonyfill; } else { self.fetchPonyfill = fetchPonyfill; } }());
(function () { 'use strict'; function fetchPonyfill(options) { var Promise = options && options.Promise || self.Promise; var XMLHttpRequest = options && options.XMLHttpRequest || self.XMLHttpRequest; var global = self; return (function () { var self = Object.create(global, { fetch: { value: undefined, writable: true } }); // {{whatwgFetch}} return { fetch: self.fetch.bind(global), Headers: self.Headers, Request: self.Request, Response: self.Response }; }()); } if (typeof define === 'function' && define.amd) { define(function () { return fetchPonyfill; }); } else if (typeof exports === 'object') { module.exports = fetchPonyfill; } else { self.fetchPonyfill = fetchPonyfill; } }());
Connect to Docker before walking.
var walk = require('walk'); var request = require('request'); var logger = require('./logger'); var prepare = require('./prepare'); prepare.connect(); // walk the filesystem from . to find directories that contain a _deconst.json file. var options = { followLinks: false, }; walker = walk.walk(".", options); walker.on('directories', function (root, stats, callback) { logger.debug('Traversing directories: %s', root); // Don't traverse into dot or common build directories. for (var i = stats.length; i--; i >= 0) { var name = stats[i].name; if (/^\./.test(name) || name === '_build' || name === '_site') { stats.splice(i, 1); } } callback(); }); walker.on('files', function (root, stats, callback) { var hasContent = stats.some(function (each) { return each.name === '_deconst.json'; }); if (hasContent) { logger.info('Deconst content directory: %s', root); prepare.prepare(root, callback); } else { callback(); } }); walker.on('errors', function (root, stats, callback) { logger.error('Error walking %s', root, { errors: stats.map(function (e) { return e.error; }) }); callback(); }); walker.on('end', function () { logger.debug('Walk completed'); });
var walk = require('walk'); var request = require('request'); var logger = require('./logger'); var prepare = require('./prepare'); // walk the filesystem from . to find directories that contain a _deconst.json file. var options = { followLinks: false, }; walker = walk.walk(".", options); walker.on('directories', function (root, stats, callback) { logger.debug('Traversing directories: %s', root); // Don't traverse into dot or common build directories. for (var i = stats.length; i--; i >= 0) { var name = stats[i].name; if (/^\./.test(name) || name === '_build' || name === '_site') { stats.splice(i, 1); } } callback(); }); walker.on('files', function (root, stats, callback) { var hasContent = stats.some(function (each) { return each.name === '_deconst.json'; }); if (hasContent) { logger.info('Deconst content directory: %s', root); prepare.prepare(root, callback); } else { callback(); } }); walker.on('errors', function (root, stats, callback) { logger.error('Error walking %s', root, { errors: stats.map(function (e) { return e.error; }) }); callback(); }); walker.on('end', function () { logger.debug('Walk completed'); });
Set an attr on the model whilst a request is mid-flight Done by overriding fetch and listening for sync/error which are triggered on success/error respectively
define(['backbone'], function(Backbone) { var MoxieModel = Backbone.Model.extend({ registeredFetch: false, // By default the fetch method will set an attr // "midFetch" to true whilst the request to the API // is in flight. This attr is removed once done. fetch: function(options) { this.set('midFetch', true); if (!this.registeredFetch) { // Careful to only listen on sync/error once this.registeredFetch = true; this.on('sync error', function(model, response, options) { // We've either got the model successfully or it has failed // either way we unset the midFetch attr model.unset('midFetch'); }); } return Backbone.Model.prototype.fetch.apply(this, [options]); }, }); return MoxieModel; });
define(['backbone'], function(Backbone) { var MoxieModel = Backbone.Model.extend({ fetch: function(options) { options = options || {}; // Set a default error handler if (!options.error) { options.error = _.bind(function() { // Pass all the error arguments through // These are [model, response, options] this.trigger("errorFetching", arguments); }, this); } return Backbone.Model.prototype.fetch.apply(this, [options]); }, }); return MoxieModel; });
Update to use zara4.com instead of dev.zara4.com
<?php namespace Zara4\API\Communication; use GuzzleHttp\Client; use GuzzleHttp\Exception\RequestException; class Util { const BASE_URL = "https://zara4.com"; /** * Get the url to the given path. * * @param $path * @return string */ public static function url($path) { return self::BASE_URL . $path; } /** * Post the given $data to the given $url. * * @param $url * @param $data * @return array * @throws Exception * @throws AccessDeniedException */ public static function post($url, $data) { // // Attempt Request // try { $client = new Client(); $res = $client->post($url, $data); return json_decode($res->getBody()); } // // Error Handling // catch(RequestException $e) { $responseData = json_decode($e->getResponse()->getBody()); // Client does not have scope permission if($responseData->{"error"} == "invalid_scope") { throw new AccessDeniedException("The client credentials are not authorised to perform this action. Scope error."); } // Generic error throw new Exception($responseData->{"error_description"}); } } }
<?php namespace Zara4\API\Communication; use GuzzleHttp\Client; use GuzzleHttp\Exception\RequestException; class Util { const BASE_URL = "http://dev.zara4.com"; /** * Get the url to the given path. * * @param $path * @return string */ public static function url($path) { return self::BASE_URL . $path; } /** * Post the given $data to the given $url. * * @param $url * @param $data * @return array * @throws Exception * @throws AccessDeniedException */ public static function post($url, $data) { // // Attempt Request // try { $client = new Client(); $res = $client->post($url, $data); return json_decode($res->getBody()); } // // Error Handling // catch(RequestException $e) { $responseData = json_decode($e->getResponse()->getBody()); // Client does not have scope permission if($responseData->{"error"} == "invalid_scope") { throw new AccessDeniedException("The client credentials are not authorised to perform this action. Scope error."); } // Generic error throw new Exception($responseData->{"error_description"}); } } }
Use the right cog icon Was occasionally getting confused because the cog is also the symbol for the settings page and this loaded first (I think). This seems to make tests pass more.
package com.autonomy.abc.selenium.iso; import com.autonomy.abc.selenium.menu.TopNavBar; import com.hp.autonomy.frontend.selenium.util.Waits; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; class IdolIsoTopNavBar extends TopNavBar { IdolIsoTopNavBar(WebDriver driver) { super(driver); } @Override public void logOut() { clickCog(); new WebDriverWait(getDriver(),5).until(ExpectedConditions.visibilityOfElementLocated(By.className("navigation-logout"))).click(); } private void clickCog(){ findElement(By.cssSelector(".navbar-top-link:not(.top-navbar-notifications)")).click(); Waits.loadOrFadeWait(); } void switchPage(TabId tab) { clickCog(); findElement(tab.locator).click(); } enum TabId { ABOUT("About"), SETTINGS("Settings"), USERS("Users"); private final By locator; TabId(String linkText) { locator = By.linkText(linkText); } } }
package com.autonomy.abc.selenium.iso; import com.autonomy.abc.selenium.menu.TopNavBar; import com.hp.autonomy.frontend.selenium.util.Waits; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; class IdolIsoTopNavBar extends TopNavBar { IdolIsoTopNavBar(WebDriver driver) { super(driver); } @Override public void logOut() { clickCog(); new WebDriverWait(getDriver(),5).until(ExpectedConditions.visibilityOfElementLocated(By.className("navigation-logout"))).click(); } private void clickCog(){ findElement(By.className("hp-settings")).click(); Waits.loadOrFadeWait(); } void switchPage(TabId tab) { clickCog(); findElement(tab.locator).click(); } enum TabId { ABOUT("About"), SETTINGS("Settings"), USERS("Users"); private final By locator; TabId(String linkText) { locator = By.linkText(linkText); } } }
Make sure number of responses matches number of requests
package knc import ( "fmt" "os/exec" "encoding/json" "keycommon/reqtarget" ) type KncServer struct { Hostname string } func (k KncServer) kncRequest(data []byte) ([]byte, error) { cmd := exec.Command("/usr/bin/knc", fmt.Sprintf("host@%s", k.Hostname), "20575") stdin, err := cmd.StdinPipe() if err != nil { return nil, err } go func() { defer stdin.Close() stdin.Write(data) }() response, err := cmd.Output() if err != nil { return nil, err } return response, nil } func (k KncServer) SendRequests(reqs []reqtarget.Request) ([]string, error) { raw_reqs, err := json.Marshal(reqs) if err != nil { return nil, err } raw_resps, err := k.kncRequest(raw_reqs) if err != nil { return nil, err } resps := []string{} err = json.Unmarshal(raw_resps, &resps) if err != nil { return nil, err } if len(resps) != len(reqs) { return nil, errors.New("Wrong number of results") } return resps, nil }
package knc import ( "fmt" "os/exec" "encoding/json" "keycommon/reqtarget" ) type KncServer struct { Hostname string } func (k KncServer) kncRequest(data []byte) ([]byte, error) { cmd := exec.Command("/usr/bin/knc", fmt.Sprintf("host@%s", k.Hostname), "20575") stdin, err := cmd.StdinPipe() if err != nil { return nil, err } go func() { defer stdin.Close() stdin.Write(data) }() response, err := cmd.Output() if err != nil { return nil, err } return response, nil } func (k KncServer) SendRequests(reqs []reqtarget.Request) ([]string, error) { raw_reqs, err := json.Marshal(reqs) if err != nil { return nil, err } raw_resps, err := k.kncRequest(raw_reqs) if err != nil { return nil, err } resps := []string{} err = json.Unmarshal(raw_resps, &resps) if err != nil { return nil, err } return resps, nil }
Add actions to handle posting a message
import { GET_CURRENT_LISTING_SUCCESS, FETCHING_LISTING, CHANGE_CONTACT_FIELD, POST_CONTACT_MESSAGE_SUCCESS } from '../constants'; import { changeCenter, addMapMarker } from './googleMapActions'; import { fetchCurrentListing, postContactMessage } from './api'; const startFetchListing = () => ({ type: FETCHING_LISTING, }); export const changeContactField = (field, value) => ({ type: CHANGE_CONTACT_FIELD, field, value, }); export const getCurrentListingSuccess = payload => ({ type: GET_CURRENT_LISTING_SUCCESS, payload, }); export const postContactMessageSuccess = payload => ({ type: POST_CONTACT_MESSAGE_SUCCESS, payload, }); export const getCurrentListing = listingId => (dispatch) => { dispatch(startFetchListing()); fetchCurrentListing(listingId) .then((res) => { res.json() .then((data) => { dispatch(changeCenter(data)); dispatch(addMapMarker(data)); dispatch(getCurrentListingSuccess(data)); }); }); }; export const sendMessage = data => (dispatch, getState) => { postContactMessage(data) .then((res) => { res.json() .then((payload) => { dispatch(postContactMessageSuccess(payload)); }); }); };
import { GET_CURRENT_LISTING_SUCCESS, FETCHING_LISTING, CHANGE_CONTACT_FIELD } from '../constants'; import { changeCenter, addMapMarker } from './googleMapActions'; import { fetchCurrentListing } from './api'; const startFetchListing = () => ({ type: FETCHING_LISTING, }); export const changeContactField = (field, value) => ({ type: CHANGE_CONTACT_FIELD, field, value, }); export const getCurrentListingSuccess = payload => ({ type: GET_CURRENT_LISTING_SUCCESS, payload, }); export const getCurrentListing = listingId => (dispatch) => { dispatch(startFetchListing()); fetchCurrentListing(listingId) .then((res) => { res.json() .then((data) => { dispatch(changeCenter(data)); dispatch(addMapMarker(data)); dispatch(getCurrentListingSuccess(data)); }); }); };
Fix for random sentence always displaying the same sentence in Internet Explorer 8.
/* Tatoeba Project, free collaborativ creation of languages corpuses project Copyright (C) 2009 TATOEBA Project(should be changed) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ $(document).ready(function(){ var lang = $("#randomLangChoice").val(); if(lang == null) lang = ''; loadRandom(lang); $("#showRandom").click(function(){ lang = $("#randomLangChoice").val(); loadRandom(lang); }) }); function loadRandom(lang){ $(".random_sentences_set").html("<img src='/img/loading.gif' alt='loading'>"); $(".random_sentences_set").load( "http://" + self.location.hostname + ":" + self.location.port + "/" + $("#showRandom").attr("lang") + "/sentences/random/" + lang + "/" + Math.random() // needed for IE // otherwise it always displays the same sentence when logged in... ); }
/* Tatoeba Project, free collaborativ creation of languages corpuses project Copyright (C) 2009 TATOEBA Project(should be changed) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ $(document).ready(function(){ var lang = $("#randomLangChoice").val(); if(lang == null) lang = ''; loadRandom(lang); $("#showRandom").click(function(){ lang = $("#randomLangChoice").val(); loadRandom(lang); }) }); function loadRandom(lang){ $(".random_sentences_set").html("<img src='/img/loading.gif' alt='loading'>"); $(".random_sentences_set").load("http://" + self.location.hostname + ":" + self.location.port + "/" + $("#showRandom").attr("lang") + "/sentences/random/" + lang); }
Fix typo that caused two classes to not get loaded
""" This enables use of course listings by subdomain. To see it in action, point the following domains to 127.0.0.1 in your /etc/hosts file: berkeley.dev harvard.dev mit.dev Note that OS X has a bug where using *.local domains is excruciatingly slow, so use *.dev domains instead for local testing. """ from .dev import * MITX_FEATURES['SUBDOMAIN_COURSE_LISTINGS'] = True COURSE_LISTINGS = { 'default' : ['BerkeleyX/CS169.1x/2012_Fall', 'BerkeleyX/CS188.1x/2012_Fall', 'HarvardX/CS50x/2012', 'HarvardX/PH207x/2012_Fall', 'MITx/3.091x/2012_Fall', 'MITx/6.002x/2012_Fall', 'MITx/6.00x/2012_Fall'], 'berkeley': ['BerkeleyX/CS169.1x/2012_Fall', 'BerkeleyX/CS188.1x/2012_Fall'], 'harvard' : ['HarvardX/CS50x/2012'], 'mit' : ['MITx/3.091x/2012_Fall', 'MITx/6.00x/2012_Fall'] }
""" This enables use of course listings by subdomain. To see it in action, point the following domains to 127.0.0.1 in your /etc/hosts file: berkeley.dev harvard.dev mit.dev Note that OS X has a bug where using *.local domains is excruciatingly slow, so use *.dev domains instead for local testing. """ from .dev import * MITX_FEATURES['SUBDOMAIN_COURSE_LISTINGS'] = True COURSE_LISTINGS = { 'default' : ['BerkeleyX/CS169.1x/2012_Fall', 'BerkeleyX/CS188.1x/2012_Fall', 'HarvardX/CS50x/2012', 'HarvardX/PH207x/2012_Fall' 'MITx/3.091x/2012_Fall', 'MITx/6.002x/2012_Fall', 'MITx/6.00x/2012_Fall'], 'berkeley': ['BerkeleyX/CS169.1x/2012_Fall', 'BerkeleyX/CS188.1x/2012_Fall'], 'harvard' : ['HarvardX/CS50x/2012'], 'mit' : ['MITx/3.091x/2012_Fall', 'MITx/6.00x/2012_Fall'] }
Fix websocket URL from localhost to the real one
'use strict'; angular.module('app').controller('LoginCtrl', function($scope, $uibModal, mafenSession, alertify, PATHS) { 'ngInject'; $scope.mafenSession = mafenSession; $scope.user = {}; $scope.login = function() { $scope.mafenSession.reset(); $scope.mafenSession.connect('ws://mafen.club:8000'); $scope.loginPromise = $scope.mafenSession.login($scope.user.username, $scope.user.password); $scope.loginPromise.then(function() { $uibModal.open({ ariaLabelledBy: 'charlist-modal-title', ariaDescribedBy: 'charlist-modal-body', templateUrl: PATHS.views + 'charlist.html', controller: 'CharListCtrl' }); }, function() { alertify.error('Authentication failed'); }); }; });
'use strict'; angular.module('app').controller('LoginCtrl', function($scope, $uibModal, mafenSession, alertify, PATHS) { 'ngInject'; $scope.mafenSession = mafenSession; $scope.user = {}; $scope.login = function() { $scope.mafenSession.reset(); $scope.mafenSession.connect('ws://127.0.0.1:8000'); $scope.loginPromise = $scope.mafenSession.login($scope.user.username, $scope.user.password); $scope.loginPromise.then(function() { $uibModal.open({ ariaLabelledBy: 'charlist-modal-title', ariaDescribedBy: 'charlist-modal-body', templateUrl: PATHS.views + 'charlist.html', controller: 'CharListCtrl' }); }, function() { alertify.error('Authentication failed'); }); }; });
Switch to using the v1 API to get total hits.
import requests, json, urllib SEARCH_URL = 'http://core.kmi.open.ac.uk/api/search/' API_KEY = 'FILL THIS IN' def getCOREMentions(identifier, **kwargs): """Return the number of mentions in CORE and a descriptor, as a tuple. Needs an API key, which can be obtained here: http://core.ac.uk/api-keys/register""" params = { 'api_key': API_KEY, 'format': 'json', } params.update(kwargs) response = requests.get(SEARCH_URL + urllib.quote_plus(identifier), params=params) response.raise_for_status() results = response.json() score = results['ListRecords'][0]['total_hits'] return score, 'mentions in Open Access articles (via http://core.ac.uk/)'
import requests, json, urllib SEARCH_URL = 'http://core.ac.uk:80/api-v2/articles/search/' API_KEY = 'FILL THIS IN' def getCOREMentions(identifier, **kwargs): """Return the number of mentions in CORE and a descriptor, as a tuple. Needs an API key, which can be obtained here: http://core.ac.uk/api-keys/register""" params = { 'apiKey': API_KEY, 'metadata': 'false', 'pageSize': 100, 'page': 1 } params.update(kwargs) response = requests.get(SEARCH_URL + urllib.quote_plus(identifier), params=params) response.raise_for_status() results = response.json() return (len(results['data'] or []), 'mentions in Open Access articles (via http://core.ac.uk/)')
Change order of env sources in getEnv()
"use strict"; var use = require("alamid-plugin/use.js"); var path = require("path"), argv = require("minimist")(process.argv.slice(2)); function dynamicConfig(basePath, fileName) { var env = dynamicConfig.getEnv(), filePath = dynamicConfig.getFilePath(basePath, env, fileName), config; if (dynamicConfig.options.log) { console.log("Loading configuration '" + fileName + "' from path '" + filePath + "'"); } config = dynamicConfig.loadConfig(filePath); return config; } dynamicConfig.getEnv = function() { return argv.env || argv.ENV || process.env.env || dynamicConfig.options.defaultEnv; }; dynamicConfig.getFilePath = function(basePath, env, fileName) { return path.join(basePath, env, fileName); }; dynamicConfig.loadConfig = function(filePath) { var config; try { config = require(filePath); } catch (err) { //handle only not found errors, throw the rest if (err.code === "MODULE_NOT_FOUND") { throw new Error("Config not found at '" + filePath + "'"); } throw err; } return config; }; dynamicConfig.options = { defaultEnv: "develop", log: false }; dynamicConfig.use = use; module.exports = dynamicConfig;
"use strict"; var use = require("alamid-plugin/use.js"); var path = require("path"), argv = require("minimist")(process.argv.slice(2)); function dynamicConfig(basePath, fileName) { var env = dynamicConfig.getEnv(), filePath = dynamicConfig.getFilePath(basePath, env, fileName), config; if (dynamicConfig.options.log) { console.log("Loading configuration '" + fileName + "' from path '" + filePath + "'"); } config = dynamicConfig.loadConfig(filePath); return config; } dynamicConfig.getEnv = function() { return process.env.env || argv.env || argv.ENV || dynamicConfig.options.defaultEnv; }; dynamicConfig.getFilePath = function(basePath, env, fileName) { return path.join(basePath, env, fileName); }; dynamicConfig.loadConfig = function(filePath) { var config; try { config = require(filePath); } catch (err) { //handle only not found errors, throw the rest if (err.code === "MODULE_NOT_FOUND") { throw new Error("Config not found at '" + filePath + "'"); } throw err; } return config; }; dynamicConfig.options = { defaultEnv: "develop", log: false }; dynamicConfig.use = use; module.exports = dynamicConfig;
Fix test, a plain realm now needs a credentials handler since it's only set in startInternal. git-svn-id: 79cef5a5a257cc9dbe40a45ac190115b4780e2d0@1758525 13f79535-47bb-0310-9956-ffa450edef68
/* * 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.catalina.realm; import java.security.Principal; import org.junit.Assert; import org.junit.Test; public class TestMemoryRealm { /** * Unknown user triggers NPE. */ @Test public void testBug56246() { MemoryRealm memoryRealm = new MemoryRealm(); memoryRealm.setCredentialHandler(new MessageDigestCredentialHandler()); Principal p = memoryRealm.authenticate("foo", "bar"); Assert.assertNull(p); } }
/* * 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.catalina.realm; import java.security.Principal; import org.junit.Assert; import org.junit.Test; public class TestMemoryRealm { /** * Unknown user triggers NPE. */ @Test public void testBug56246() { MemoryRealm memoryRealm = new MemoryRealm(); Principal p = memoryRealm.authenticate("foo", "bar"); Assert.assertNull(p); } }
Add User back into admin
from django.contrib.admin.sites import AdminSite from django.conf.urls.defaults import patterns, url from shells.admin_views import ShellsImagesUploader, upload_species_spreadsheet class ShellsAdmin(AdminSite): def get_urls(self): urls = super(ShellsAdmin, self).get_urls() my_urls = patterns('', url('upload_images/', self.admin_view(ShellsImagesUploader.as_view()), name="upload-images"), url(r'^upload/', self.admin_view(upload_species_spreadsheet), name='upload_species_spreadsheet'), ) return my_urls + urls shells_admin = ShellsAdmin() from shells.admin import SpeciesAdmin, SpecimenAdmin, SpeciesRepresentationAdmin from shells.models import Species, Specimen, SpeciesRepresentation shells_admin.register(Species, SpeciesAdmin) shells_admin.register(Specimen, SpecimenAdmin) shells_admin.register(SpeciesRepresentation, SpeciesRepresentationAdmin) from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User shells_admin.register(User, UserAdmin)
from django.contrib.admin.sites import AdminSite from django.conf.urls.defaults import patterns, url from shells.admin_views import ShellsImagesUploader, upload_species_spreadsheet class ShellsAdmin(AdminSite): def get_urls(self): urls = super(ShellsAdmin, self).get_urls() my_urls = patterns('', url('upload_images/', self.admin_view(ShellsImagesUploader.as_view()), name="upload-images"), url(r'^upload/', self.admin_view(upload_species_spreadsheet), name='upload_species_spreadsheet'), ) return my_urls + urls shells_admin = ShellsAdmin() from shells.admin import SpeciesAdmin, SpecimenAdmin, SpeciesRepresentationAdmin from shells.models import Species, Specimen, SpeciesRepresentation shells_admin.register(Species, SpeciesAdmin) shells_admin.register(Specimen, SpecimenAdmin) shells_admin.register(SpeciesRepresentation, SpeciesRepresentationAdmin)
Add { force: env.UNSAFE_MODE }
const gulp = require('gulp'); const del = require('del'); /** * Cleaning tasks * * @task clean:* */ gulp.task('clean:dest', (done) => { return del(env.DIR_DEST, { force: env.UNSAFE_MODE }); }); gulp.task('clean:docs', (done) => { return del(env.DIR_DOCS, { force: env.UNSAFE_MODE }); }); gulp.task('clean:minify', (done) => { return del([ env.DIR_DEST + '/assets/vendor' <% if (jstBuildSystem !== "no") { %>, env.DIR_DEST + '/assets/scripts/precompiledJst.js' <% } %> <% if (jstBuildSystem !== "no") { %>, env.DIR_SRC + '/assets/scripts/precompiledJst.js' <% } %> ], { force: env.UNSAFE_MODE }); }); gulp.task('clean:installed', (done) => { return del([ 'tools/node-*', env.DIR_BOWER, env.DIR_NPM ], { force: env.UNSAFE_MODE }); });
const gulp = require('gulp'); const del = require('del'); /** * Cleaning tasks * * @task clean:* */ gulp.task('clean:dest', (done) => { return del(env.DIR_DEST); }); gulp.task('clean:docs', (done) => { return del(env.DIR_DOCS); }); gulp.task('clean:minify', (done) => { return del([ env.DIR_DEST + '/assets/vendor' <% if (jstBuildSystem !== "no") { %>, env.DIR_DEST + '/assets/scripts/precompiledJst.js' <% } %> <% if (jstBuildSystem !== "no") { %>, env.DIR_SRC + '/assets/scripts/precompiledJst.js' <% } %> ]); }); gulp.task('clean:installed', (done) => { return del([ 'tools/node-*', env.DIR_BOWER, env.DIR_NPM ]); });
Update user locale without fetching user's account.
// Store the preference locale in cookies and (if available) session to use // on next requests. 'use strict'; var _ = require('lodash'); var LOCALE_COOKIE_MAX_AGE = 0xFFFFFFFF; // Maximum 32-bit unsigned integer. module.exports = function (N, apiPath) { N.validate(apiPath, { locale: { type: 'string' } }); N.wire.on(apiPath, function set_language(env, callback) { var locale = env.params.locale; if (!_.contains(N.config.locales.enabled, env.params.locale)) { // User sent a non-existent or disabled locale - reply with the default. locale = N.config.locales['default']; } env.extras.setCookie('locale', locale, { path: '/' , maxAge: LOCALE_COOKIE_MAX_AGE }); if (env.session) { env.session.locale = locale; } if (env.session && env.session.user_id) { N.models.users.User.update({ _id: env.session.user_id }, { locale: locale }, callback); } else { callback(); } }); };
// Store the preference locale in cookies and (if available) session to use // on next requests. 'use strict'; var _ = require('lodash'); var LOCALE_COOKIE_MAX_AGE = 0xFFFFFFFF; // Maximum 32-bit unsigned integer. module.exports = function (N, apiPath) { N.validate(apiPath, { locale: { type: 'string' } }); N.wire.on(apiPath, function set_language(env, callback) { var locale = env.params.locale; if (!_.contains(N.config.locales.enabled, env.params.locale)) { // User sent a non-existent or disabled locale - reply with the default. locale = N.config.locales['default']; } env.extras.setCookie('locale', locale, { path: '/' , maxAge: LOCALE_COOKIE_MAX_AGE }); if (env.session) { env.session.locale = locale; } if (env.session && env.session.user_id) { N.models.users.User.findByIdAndUpdate(env.session.user_id, { locale: locale }, callback); } else { callback(); } }); };
Swap weightings for Tax Disc AB test cohorts beta should be ~100%, beta_control should be 0%
//= require govuk/multivariate-test /*jslint browser: true, * indent: 2, * white: true */ /*global $, GOVUK */ $(function () { GOVUK.taxDiscBetaPrimary = function () { $('.primary-apply').html($('#beta-primary').html()); $('.secondary-apply').html($('#dvla-secondary').html()); }; if(window.location.href.indexOf("/tax-disc") > -1) { new GOVUK.MultivariateTest({ name: 'tax-disc-beta', customVarIndex: 20, cohorts: { tax_disc_beta_control: { weight: 0, callback: function () { } }, //~0% tax_disc_beta: { weight: 1, callback: GOVUK.taxDiscBetaPrimary } //~100% } }); } });
//= require govuk/multivariate-test /*jslint browser: true, * indent: 2, * white: true */ /*global $, GOVUK */ $(function () { GOVUK.taxDiscBetaPrimary = function () { $('.primary-apply').html($('#beta-primary').html()); $('.secondary-apply').html($('#dvla-secondary').html()); }; if(window.location.href.indexOf("/tax-disc") > -1) { new GOVUK.MultivariateTest({ name: 'tax-disc-beta', customVarIndex: 20, cohorts: { tax_disc_beta_control: { weight: 1, callback: function () { } }, //~100% tax_disc_beta: { weight: 0, callback: GOVUK.taxDiscBetaPrimary } //~0% } }); } });
Update animation actions to use new constants
import Velocity from 'velocity-animate' import { PAGE_SCROLL_STARTED, PAGE_SCROLL_ENDED } from '../constants' export function scrollPage({ content=false, mainPage=false }) { if (!content && !mainPage) { throw new Error("No scroll destination supplied") } const offset = content ? window.innerHeight : 0; return dispatch => { dispatch({type: PAGE_SCROLL_STARTED}); return Velocity(document.body, 'scroll', { offset: offset, duration: 1000, easing: "ease-in-out", complete: () => { dispatch({type: PAGE_SCROLL_ENDED}) } }); } }
import Velocity from 'velocity-animate' import { SCROLL_STARTED, SCROLL_ENDED } from '../constants' export function scrollPage({ content=false, mainPage=false }) { if (!content && !mainPage) { throw new Error("No scroll destination supplied") } const offset = content ? window.innerHeight : 0; return dispatch => { dispatch({type: SCROLL_STARTED}); return Velocity(document.body, 'scroll', { offset: offset, duration: 1000, easing: "ease-in-out", complete: () => { dispatch({type: SCROLL_ENDED}) } }); } }
Add background colors of cli support
<?php namespace Pagon\Utility; class Cli { /** * Color output text for the CLI * * @param string $text to color * @param string $color of text * @param bool|string $bold color * @param string $bg_color background color * @return string */ public static function colorize($text, $color, $bold = false, $bg_color = 'default') { $colors = array_flip(array(30 => 'gray', 'red', 'green', 'yellow', 'blue', 'purple', 'cyan', 'white')); $bg_colors = array_flip(array(40 => 'gray', 'red', 'green', 'yellow', 'blue', 'purple', 'cyan', 'white', 49 => 'default')); return "\033[" . ($bold ? '1' : '0') . ';' . $colors[$color] . ';' . $bg_colors[$bg_color] . "m$text\033[0m"; } }
<?php namespace Pagon\Utility; class Cli { /** * Color output text for the CLI * * @param string $text to color * @param string $color of text * @param bool|string $bold color * @param string $bg_color background color * @return string */ public static function colorize($text, $color, $bold = false, $bg_color = 'default') { $colors = array_flip(array(30 => 'gray', 'red', 'green', 'yellow', 'blue', 'purple', 'cyan', 'white', 'default')); $bg_colors = array_flip(array(40 => 'gray', 'red', 'green', 'yellow', 'blue', 'purple', 'cyan', 'white', 'default')); return "\033[" . ($bold ? '1' : '0') . ';' . $colors[$color] . ';' . $bg_colors[$bg_color] . "m$text\033[0m"; } }
Replace database 'reactiondbtest3' with 'reactiondb'
package Database; /** * This class stores a MySQL credential constants */ public enum Config { /** * Username to MySQL database */ USERNAME("root"), /** * Password to MySQL database */ PASSWORD("codeKenn"), /** * Location to MySQL database */ URL("jdbc:mysql://localhost:3306"), /** * MySQL database to establish connection */ DATABASE("reactiondb"), /** * MySQL table to query */ TABLE("reactions"); private String CONSTANT; /** * Construct this class * * @param CONSTANT to be set */ private Config(String CONSTANT) { this.CONSTANT = CONSTANT; } @Override public String toString() { return CONSTANT; } }
package Database; /** * This class stores a MySQL credential constants */ public enum Config { /** * Username to MySQL database */ USERNAME("root"), /** * Password to MySQL database */ PASSWORD("codeKenn"), /** * Location to MySQL database */ URL("jdbc:mysql://localhost:3306"), /** * MySQL database to establish connection */ DATABASE("reactiondbtest2"), /** * MySQL table to query */ TABLE("reactions"); private String CONSTANT; /** * Construct this class * * @param CONSTANT to be set */ private Config(String CONSTANT) { this.CONSTANT = CONSTANT; } @Override public String toString() { return CONSTANT; } }
Make resolve work with node v0.6.10 .
var Module = require('module'); var dirname = require('path').dirname; module.exports = function requireLike(path, uncached) { var parentModule = new Module(path); parentModule.filename = path; parentModule.paths = Module._nodeModulePaths(dirname(path)); function requireLike(file) { var cache = Module._cache; if (uncached) { Module._cache = {}; } var exports = Module._load(file, parentModule); Module._cache = cache; return exports; }; requireLike.resolve = function(request) { var resolved = Module._resolveFilename(request, parentModule); // Module._resolveFilename returns a string since node v0.6.10, // it used to return an array prior to that return (resolved instanceof Array) ? resolved[1] : resolved; } try { requireLike.paths = require.paths; } catch (e) { //require.paths was deprecated in node v0.5.x //it now throws an exception when called } requireLike.main = process.mainModule; requireLike.extensions = require.extensions; requireLike.cache = require.cache; return requireLike; };
var Module = require('module'); var dirname = require('path').dirname; module.exports = function requireLike(path, uncached) { var parentModule = new Module(path); parentModule.filename = path; parentModule.paths = Module._nodeModulePaths(dirname(path)); function requireLike(file) { var cache = Module._cache; if (uncached) { Module._cache = {}; } var exports = Module._load(file, parentModule); Module._cache = cache; return exports; }; requireLike.resolve = function(request) { return Module._resolveFilename(request, parentModule)[1]; } try { requireLike.paths = require.paths; } catch (e) { //require.paths was deprecated in node v0.5.x //it now throws an exception when called } requireLike.main = process.mainModule; requireLike.extensions = require.extensions; requireLike.cache = require.cache; return requireLike; };
Return model when finishing updating model
var _ = require('underscore'), async = require('async'), curry = require('curry'), Dependency = require('../models').Dependency, compHelper = require('./componentHelper'), compInstall = compHelper.install, compBuild = compHelper.build; module.exports = function updateModel (model, data, callback) { _.each(data, function (val, prop) { if (prop === 'dependencies') { model.dependencies = []; _.each(val, function (version, name) { model.dependencies.push(new Dependency({ name : name, version : version })); }) } else if (!_.isFunction(model[prop])) { model[prop] = val; } }); model.updated = new Date(); model.type = data['web-audio'].type; async.series([ curry([data], compInstall), curry([data], compBuild), function () { model.save.apply(model, arguments); } ], function (err) { callback(err, model); }); };
var _ = require('underscore'), async = require('async'), curry = require('curry'), Dependency = require('../models').Dependency, compHelper = require('./componentHelper'), compInstall = compHelper.install, compBuild = compHelper.build; module.exports = function updateModel (model, data, callback) { _.each(data, function (val, prop) { if (prop === 'dependencies') { model.dependencies = []; _.each(val, function (version, name) { model.dependencies.push(new Dependency({ name : name, version : version })); }) } else if (!_.isFunction(model[prop])) { model[prop] = val; } }); model.updated = new Date(); model.type = data['web-audio'].type; async.series([ curry([data], compInstall), curry([data], compBuild), function () { model.save.apply(model, arguments); } ], callback); };
Add default state to the reducer
const {PUSH, POP, REPLACE} = require('../constants/navigation'); module.exports = function navigate(state, {type, payload}) { if (!state) { return {__nav: {}}; } const stack = state.__nav.stack; const index = state.__nav.index; switch (type) { case PUSH: return Object.assign({}, state, { __nav: { stack: stack.unshift(payload), index: 0, }, }); case POP: const incremented = index + 1; if (incremented === stack.count()) { return state; } return Object.assign({}, state, { __nav: { stack: stack, index: incremented, }, }); case REPLACE: if (!stack.count()) { return state; } return Object.assign({}, state, { __nav: { stack: stack.splice(index, 1, payload), index: index, }, }); default: return state; } };
const {PUSH, POP, REPLACE} = require('../constants/navigation'); module.exports = function navigate(state, {type, payload}) { const stack = state.__nav.stack; const index = state.__nav.index; switch (type) { case PUSH: return Object.assign({}, state, { __nav: { stack: stack.unshift(payload), index: 0, }, }); case POP: const incremented = index + 1; if (incremented === stack.count()) { return state; } return Object.assign({}, state, { __nav: { stack: stack, index: incremented, }, }); case REPLACE: if (!stack.count()) { return state; } return Object.assign({}, state, { __nav: { stack: stack.splice(index, 1, payload), index: index, }, }); default: return state; } };
Add an explicit sleep in pointClustering test
#!/usr/bin/env python from time import sleep from selenium_test import FirefoxTest, ChromeTest,\ setUpModule, tearDownModule class glPointsBase(object): testCase = ('pointClustering',) testRevision = 4 def loadPage(self): self.resizeWindow(640, 480) self.loadURL('pointClustering/index.html') self.wait() self.resizeWindow(640, 480) sleep(5) def testClustering0(self): self.loadPage() self.screenshotTest('zoom0') def testClustering2(self): self.loadPage() self.runScript( 'myMap.zoom(5); myMap.center({x: -99, y: 40});' ) self.screenshotTest('zoom2') class FirefoxOSM(glPointsBase, FirefoxTest): testCase = glPointsBase.testCase + ('firefox',) class ChromeOSM(glPointsBase, ChromeTest): testCase = glPointsBase.testCase + ('chrome',) if __name__ == '__main__': import unittest unittest.main()
#!/usr/bin/env python from selenium_test import FirefoxTest, ChromeTest,\ setUpModule, tearDownModule class glPointsBase(object): testCase = ('pointClustering',) testRevision = 4 def loadPage(self): self.resizeWindow(640, 480) self.loadURL('pointClustering/index.html') self.wait() self.resizeWindow(640, 480) def testClustering0(self): self.loadPage() self.screenshotTest('zoom0') def testClustering2(self): self.loadPage() self.runScript( 'myMap.zoom(5); myMap.center({x: -99, y: 40});' ) self.screenshotTest('zoom2') class FirefoxOSM(glPointsBase, FirefoxTest): testCase = glPointsBase.testCase + ('firefox',) class ChromeOSM(glPointsBase, ChromeTest): testCase = glPointsBase.testCase + ('chrome',) if __name__ == '__main__': import unittest unittest.main()
Remove unused ol.style.Text width property
goog.provide('ol.style.Text'); /** * @constructor * @param {ol.style.TextOptions} options Options. */ ol.style.Text = function(options) { /** * @type {string|undefined} */ this.font = options.font; /** * @type {string|undefined} */ this.text = options.text; /** * @type {string|undefined} */ this.textAlign = options.textAlign; /** * @type {string|undefined} */ this.textBaseline = options.textBaseline; }; /** * @param {ol.style.Text} textStyle1 Text style 1. * @param {ol.style.Text} textStyle2 Text style 2. * @return {boolean} Equals. */ ol.style.Text.equals = function(textStyle1, textStyle2) { if (!goog.isNull(textStyle1)) { if (!goog.isNull(textStyle2)) { return textStyle1 === textStyle2 || ( textStyle1.font == textStyle2.font && textStyle1.text == textStyle2.text && textStyle1.textAlign == textStyle2.textAlign && textStyle1.textBaseline == textStyle2.textBaseline); } else { return false; } } else { if (!goog.isNull(textStyle2)) { return false; } else { return true; } } };
goog.provide('ol.style.Text'); /** * @constructor * @param {ol.style.TextOptions} options Options. */ ol.style.Text = function(options) { /** * @type {string|undefined} */ this.font = options.font; /** * @type {string|undefined} */ this.text = options.text; /** * @type {string|undefined} */ this.textAlign = options.textAlign; /** * @type {string|undefined} */ this.textBaseline = options.textBaseline; /** * @type {number} */ this.width = options.width; }; /** * @param {ol.style.Text} textStyle1 Text style 1. * @param {ol.style.Text} textStyle2 Text style 2. * @return {boolean} Equals. */ ol.style.Text.equals = function(textStyle1, textStyle2) { if (!goog.isNull(textStyle1)) { if (!goog.isNull(textStyle2)) { return textStyle1 === textStyle2 || ( textStyle1.font == textStyle2.font && textStyle1.text == textStyle2.text && textStyle1.textAlign == textStyle2.textAlign && textStyle1.textBaseline == textStyle2.textBaseline); } else { return false; } } else { if (!goog.isNull(textStyle2)) { return false; } else { return true; } } };
Fix route from app.jsx to workspace controller component
// inferno module import React from 'react'; import ReactDOM from "react-dom"; import { Router, Route, browserHistory } from 'react-router'; // scss module import './scss/main.scss'; // state modules import { Provider } from 'react-redux'; import store from './shared/store'; // app component import App from './App.jsx'; import WorkspaceController from './components/sidebar/WorkspacesController.jsx'; const routes = ( <Provider store={ store }> <Router history={ browserHistory }> <Route component={ App }> <Route path="/" component={ WorkspaceController } /> </Route> </Router> </Provider> ); ReactDOM.render(routes, document.getElementById('app-root'));
// inferno module import React from 'react'; import ReactDOM from "react-dom"; import { Router, Route, browserHistory } from 'react-router'; // scss module import './scss/main.scss'; // state modules import { Provider } from 'react-redux'; import store from './shared/store'; // app component import App from './App.jsx'; import Workspace from './Workspace.jsx'; import WorkspaceController from './components/workspaces/WorkspacesController.jsx'; const routes = ( <Provider store={ store }> <Router history={ browserHistory }> <Route component={ App }> <Route path="/" component={ WorkspaceController } /> </Route> </Router> </Provider> ); ReactDOM.render(routes, document.getElementById('app-root'));
Add contrib.admin to locally installed apps
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Management command entry point for working with migrations """ import sys import django from django.conf import settings INSTALLED_APPS = [ "django.contrib.auth", "django.contrib.admin", "django.contrib.contenttypes", "django.contrib.sites", "addendum", ] try: import south # noqa except ImportError: pass else: INSTALLED_APPS += ['south'] settings.configure( DEBUG=True, USE_TZ=True, USE_I18N=True, DATABASES={ "default": { "ENGINE": "django.db.backends.sqlite3", } }, MIDDLEWARE_CLASSES=(), # Silence Django 1.7 warnings SITE_ID=1, FIXTURE_DIRS=['tests/fixtures'], INSTALLED_APPS=INSTALLED_APPS, ROOT_URLCONF="tests.urls", ) try: django.setup() except AttributeError: pass if __name__ == '__main__': from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Management command entry point for working with migrations """ import sys import django from django.conf import settings INSTALLED_APPS = [ "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sites", "addendum", ] try: import south # noqa except ImportError: pass else: INSTALLED_APPS += ['south'] settings.configure( DEBUG=True, USE_TZ=True, USE_I18N=True, DATABASES={ "default": { "ENGINE": "django.db.backends.sqlite3", } }, MIDDLEWARE_CLASSES=(), # Silence Django 1.7 warnings SITE_ID=1, FIXTURE_DIRS=['tests/fixtures'], INSTALLED_APPS=INSTALLED_APPS, ROOT_URLCONF="tests.urls", ) try: django.setup() except AttributeError: pass if __name__ == '__main__': from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
Use Session class in upload controller
<?php namespace App\Http\Controllers\Files; use Storage; use Session; use App\Http\Controllers\Controller; use App\File; use Illuminate\Http\Request; class UploadController extends Controller { /** * Create a new upload controller instance. * * @return void */ public function __construct() { $this->middleware('verify.key'); } /** * POST function * * @param \Illuminate\Http\Request $request */ public function post(Request $request) { // Decode the file $contents = base64_decode($request['contents']); $hash = File::hash(); // Save the file in the database $file = new File; $file->name = $request['file']; $file->type = $request['type']; $file->hash = $hash; $file->owner = Session::get('user')->id; $file->save(); // Put the file at $hash Storage::put($hash, $contents); // Return the url of where the file is return 'http://dl.' . env('APP_URL') . '/' . $hash; } }
<?php namespace App\Http\Controllers\Files; use Storage; use App\Http\Controllers\Controller; use App\File; use Illuminate\Http\Request; class UploadController extends Controller { /** * Create a new upload controller instance. * * @return void */ public function __construct() { $this->middleware('verify.key'); } /** * POST function * * @param \Illuminate\Http\Request $request */ public function post(Request $request) { // Decode the file $contents = base64_decode($request['contents']); $hash = File::hash(); // Save the file in the database $file = new File; $file->name = $request['file']; $file->type = $request['type']; $file->hash = $hash; $file->owner = Session::get('user')->id; $file->save(); // Put the file at $hash Storage::put($hash, $contents); // Return the url of where the file is return 'http://dl.' . env('APP_URL') . '/' . $hash; } }
Use serverprefs localizer for TestingServerPreferencesGroup
from __future__ import annotations from typing import TYPE_CHECKING from botus_receptus.app_commands import test_guilds_only from discord import app_commands from .daily_bread.daily_bread_preferences_group import DailyBreadPreferencesGroup if TYPE_CHECKING: from ...erasmus import Erasmus from ...l10n import GroupLocalizer from .types import ParentCog @app_commands.default_permissions(administrator=True) @app_commands.guild_only() @test_guilds_only class TestingServerPreferencesGroup( app_commands.Group, name='test-server-prefs', description='Testing group' ): bot: Erasmus localizer: GroupLocalizer daily_bread = DailyBreadPreferencesGroup() def initialize_from_parent(self, parent: ParentCog, /) -> None: self.bot = parent.bot self.localizer = parent.localizer.for_group('serverprefs') self.daily_bread.initialize_from_parent(self)
from __future__ import annotations from typing import TYPE_CHECKING from botus_receptus.app_commands import test_guilds_only from discord import app_commands from .daily_bread.daily_bread_preferences_group import DailyBreadPreferencesGroup if TYPE_CHECKING: from ...erasmus import Erasmus from ...l10n import GroupLocalizer from .types import ParentCog @app_commands.default_permissions(administrator=True) @app_commands.guild_only() @test_guilds_only class TestingServerPreferencesGroup( app_commands.Group, name='test-server-prefs', description='Testing group' ): bot: Erasmus localizer: GroupLocalizer daily_bread = DailyBreadPreferencesGroup() def initialize_from_parent(self, parent: ParentCog, /) -> None: self.bot = parent.bot self.localizer = parent.localizer.for_group(self) self.daily_bread.initialize_from_parent(self)
Update ZF2 supported version info
<?php return array( 'view_manager' => array( 'template_map' => array( 'layout/layouttwb' => __DIR__ . '/../view/layout/layouttwb.phtml', ), 'template_path_stack' => array( 'dluTwBootstrap' => __DIR__ . '/../view', ), ), 'service_manager' => array( 'invokables' => array( 'dlu_twb_gen_util' => 'DluTwBootstrap\GenUtil', 'dlu_twb_form_util' => 'DluTwBootstrap\Form\FormUtil', 'dlu_twb_nav_view_helper_configurator' => 'DluTwBootstrap\View\Helper\Navigation\PluginConfigurator', ), ), 'dlu_tw_bootstrap' => array( 'sup_ver_zf2' => '2.0.0rc3 - 170 (commit 2f42641400)', 'sup_ver_twb' => '2.0.4', ), );
<?php return array( 'view_manager' => array( 'template_map' => array( 'layout/layouttwb' => __DIR__ . '/../view/layout/layouttwb.phtml', ), 'template_path_stack' => array( 'dluTwBootstrap' => __DIR__ . '/../view', ), ), 'service_manager' => array( 'invokables' => array( 'dlu_twb_gen_util' => 'DluTwBootstrap\GenUtil', 'dlu_twb_form_util' => 'DluTwBootstrap\Form\FormUtil', 'dlu_twb_nav_view_helper_configurator' => 'DluTwBootstrap\View\Helper\Navigation\PluginConfigurator', ), ), 'dlu_tw_bootstrap' => array( 'sup_ver_zf2' => '2.0.0rc3 - 116 (commit d959262b1c)', 'sup_ver_twb' => '2.0.4', ), );