text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Update rules property to ba a collection instead of array
<?php namespace GeniusTS\Preferences\Models; use Illuminate\Support\Collection; use Illuminate\Contracts\View\View; /** * Class Element * * @package GeniusTS\Preferences * @property string $name * @property string $namespace * @property string $rules * @property View $view */ class Element { /** * @var string */ protected $name; /** * @var string */ protected $namespace; /** * @var \Illuminate\Support\Collection */ protected $rules; /** * Element constructor. * * @param string $name * @param array|string $rules */ public function __construct($name, $rules = '') { $this->name = $name; $this->rules = new Collection(is_array($rules) ? $rules : [$name => $rules]); } /** * Set the name space of element * * @param string $namespace * * @return $this */ public function setNamespace($namespace) { $this->namespace = $namespace; return $this; } /** * @param string $property * * @return null */ public function __get($property) { if (property_exists($this, $property)) { return $this->{$property}; } return null; } }
<?php namespace GeniusTS\Preferences\Models; use Illuminate\Contracts\View\View; /** * Class Element * * @package GeniusTS\Preferences * @property string $name * @property string $namespace * @property string $rules * @property View $view */ class Element { /** * @var string */ protected $name; /** * @var string */ protected $namespace; /** * @var string */ protected $rules; /** * Element constructor. * * @param string $name * @param string $rules */ public function __construct($name, $rules = '') { $this->name = $name; if (is_array($rules)) { $this->rules = $rules; } else { $this->rules = [$name => $rules]; } } /** * Set the name space of element * * @param string $namespace * * @return $this */ public function setNamespace($namespace) { $this->namespace = $namespace; return $this; } /** * @param string $property * * @return null */ public function __get($property) { if (property_exists($this, $property)) { return $this->{$property}; } return null; } }
Disable source switcher during walkthrough Closes #4401 -- fixed as proposed in the issue's comments
import { event as d3_event, select as d3_select } from 'd3-selection'; import { t } from '../util/locale'; import { modeBrowse } from '../modes'; export function uiSourceSwitch(context) { var keys; function click() { d3_event.preventDefault(); if (context.inIntro()) return; if (context.history().hasChanges() && !window.confirm(t('source_switch.lose_changes'))) return; var live = d3_select(this) .classed('live'); context.history().clearSaved(); context.connection().switch(live ? keys[1] : keys[0]); context.enter(modeBrowse(context)); context.flush(); d3_select(this) .text(live ? t('source_switch.dev') : t('source_switch.live')) .classed('live', !live); } var sourceSwitch = function(selection) { selection .append('a') .attr('href', '#') .text(t('source_switch.live')) .classed('live', true) .attr('tabindex', -1) .on('click', click); }; sourceSwitch.keys = function(_) { if (!arguments.length) return keys; keys = _; return sourceSwitch; }; return sourceSwitch; }
import { event as d3_event, select as d3_select } from 'd3-selection'; import { t } from '../util/locale'; import { modeBrowse } from '../modes'; export function uiSourceSwitch(context) { var keys; function click() { d3_event.preventDefault(); if (context.history().hasChanges() && !window.confirm(t('source_switch.lose_changes'))) return; var live = d3_select(this) .classed('live'); context.history().clearSaved(); context.connection().switch(live ? keys[1] : keys[0]); context.enter(modeBrowse(context)); context.flush(); d3_select(this) .text(live ? t('source_switch.dev') : t('source_switch.live')) .classed('live', !live); } var sourceSwitch = function(selection) { selection .append('a') .attr('href', '#') .text(t('source_switch.live')) .classed('live', true) .attr('tabindex', -1) .on('click', click); }; sourceSwitch.keys = function(_) { if (!arguments.length) return keys; keys = _; return sourceSwitch; }; return sourceSwitch; }
Set singleRun setting to false
var webpackConfig = require("./webpack.config"); Object.assign(webpackConfig, { debug: true, devtool: "inline-source-map" }); webpackConfig.externals.push("react/lib/ExecutionEnvironment"); webpackConfig.externals.push("react/lib/ReactContext"); webpackConfig.externals.push("react/addons"); webpackConfig.externals.push("jsdom"); module.exports = function(config) { config.set({ basePath: "", frameworks: [ "jasmine" ], files: [ { pattern: "src/**/*.ts", watched: true, included: false, served: false }, { pattern: "tests/**/*.ts", watched: true, included: false, served: false }, "tests/test-index.js" ], exclude: [], preprocessors: { "tests/test-index.js": [ "webpack", "sourcemap" ] }, webpack: webpackConfig, webpackServer: { noInfo: true }, reporters: [ "progress", "kjhtml", "coverage" ], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: [ "Chrome" ], singleRun: false, concurrency: Infinity, coverageReporter: { dir: "./dist/testresults", reporters: [ { type: "json", subdir: ".", file: "coverage.json" }, { type: "text" } ] } }); };
var webpackConfig = require("./webpack.config"); Object.assign(webpackConfig, { debug: true, devtool: "inline-source-map" }); webpackConfig.externals.push("react/lib/ExecutionEnvironment"); webpackConfig.externals.push("react/lib/ReactContext"); webpackConfig.externals.push("react/addons"); webpackConfig.externals.push("jsdom"); module.exports = function(config) { config.set({ basePath: "", frameworks: [ "jasmine" ], files: [ { pattern: "src/**/*.ts", watched: true, included: false, served: false }, { pattern: "tests/**/*.ts", watched: true, included: false, served: false }, "tests/test-index.js" ], exclude: [], preprocessors: { "tests/test-index.js": [ "webpack", "sourcemap" ] }, webpack: webpackConfig, webpackServer: { noInfo: true }, reporters: [ "progress", "kjhtml", "coverage" ], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: [ "Chrome" ], singleRun: true, concurrency: Infinity, coverageReporter: { dir: "./dist/testresults", reporters: [ { type: "json", subdir: ".", file: "coverage.json" }, { type: "text" } ] } }); };
Fix Denite support for vim8.
# -*- coding: utf-8 -*- from .base import Base class Source(Base): def __init__(self, vim): super().__init__(vim) self.name = 'vimtex_toc' self.kind = 'file' @staticmethod def format_number(n): if not n or not type(n) is dict or n['frontmatter'] or n['backmatter']: return '' num = [str(n[k]) for k in [ 'part', 'chapter', 'section', 'subsection', 'subsubsection', 'subsubsubsection'] if n[k] is not 0] if n['appendix']: num[0] = chr(int(num[0]) + 64) fnum = '.'.join(num) return fnum @staticmethod def create_candidate(e, depth): indent = (' ' * 2*(int(depth) - int(e['level'])) + e['title'])[:60] number = Source.format_number(e['number']) abbr = '{:65}{:10}'.format(indent, number) return {'word': e['title'], 'abbr': abbr, 'action__path': e['file'], 'action__line': e.get('line', 0)} def gather_candidates(self, context): entries = self.vim.eval('vimtex#toc#get_entries()') depth = max([int(e['level']) for e in entries]) return [Source.create_candidate(e, depth) for e in entries]
# -*- coding: utf-8 -*- from .base import Base class Source(Base): def __init__(self, vim): super().__init__(vim) self.name = 'vimtex_toc' self.kind = 'file' @staticmethod def format_number(n): if not n or n['frontmatter'] or n['backmatter']: return '' num = [str(n[k]) for k in [ 'part', 'chapter', 'section', 'subsection', 'subsubsection', 'subsubsubsection'] if n[k] is not 0] if n['appendix']: num[0] = chr(int(num[0]) + 64) fnum = '.'.join(num) return fnum @staticmethod def create_candidate(e, depth): indent = (' ' * 2*(depth - e['level']) + e['title'])[:60] number = Source.format_number(e['number']) abbr = '{:65}{:10}'.format(indent, number) return {'word': e['title'], 'abbr': abbr, 'action__path': e['file'], 'action__line': e.get('line', 0)} def gather_candidates(self, context): entries = self.vim.eval('vimtex#toc#get_entries()') depth = max([e['level'] for e in entries]) return [Source.create_candidate(e, depth) for e in entries]
Use list comprehension for mailjet_users list
from django.core.management.base import BaseCommand from django.db import DEFAULT_DB_ALIAS from optparse import make_option class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option('--connection', action='store', dest='connection', default=DEFAULT_DB_ALIAS, ), ) def handle(self, *args, **options): from courriers.backends import get_backend from courriers.models import NewsletterSubscriber self.connection = options.get('connection') backend_klass = get_backend() backend = backend_klass() unsubscribed_users = (NewsletterSubscriber.objects.using(self.connection) .filter(is_unsubscribed=True) .values_list('email', flat=True) .order_by('-unsubscribed_at')) mailjet_contacts = backend.mailjet_api.contact.list() mailjet_users = [contact['email'] for contact in mailjet_contacts['result']] diff = list(set(unsubscribed_users) - set(mailjet_users)) print "%d contacts to unsubscribe" % len(diff) for email in diff: backend.unregister(email) print "Unsubscribe user: %s" % email
from django.core.management.base import BaseCommand from django.db import DEFAULT_DB_ALIAS from optparse import make_option class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option('--connection', action='store', dest='connection', default=DEFAULT_DB_ALIAS, ), ) def handle(self, *args, **options): from courriers.backends import get_backend from courriers.models import NewsletterSubscriber self.connection = options.get('connection') backend_klass = get_backend() backend = backend_klass() unsubscribed_users = (NewsletterSubscriber.objects.using(self.connection) .filter(is_unsubscribed=True) .values_list('email', flat=True) .order_by('-unsubscribed_at')) mailjet_contacts = backend.mailjet_api.contact.list() mailjet_users = [] for contact in mailjet_contacts['result']: mailjet_users.append(contact['email']) diff = list(set(unsubscribed_users) - set(mailjet_users)) print "%d contacts to unsubscribe" % len(diff) for email in diff: backend.unregister(email) print "Unsubscribe user: %s" % email
Update for tilelive.js exports change.
var _ = require('underscore')._, Tile = require('tilelive.js').Tile; var mapnik = require('mapnik'); mapnik.register_datasources('/usr/local/lib/mapnik2/input'); mapnik.register_fonts('/usr/local/lib/mapnik2/fonts/'); module.exports = function(app, settings) { app.get('/:scheme/:mapfile_64/:z/:x/:y.*', function(req, res, next) { /* * scheme: (xyz|tms|tile (tms)) * * format: * - Tile: (png|jpg) * - Data Tile: (geojson) * - Grid Tile: (*.grid.json) */ try { var tile = new Tile( req.params.scheme, req.params.mapfile_64, req.params.z, req.params.x, req.params.y, req.params[0], settings.mapfile_dir); } catch (err) { res.send('Tile invalid: ' + err.message); } tile.render(function(err, data) { if (!err) { // Using apply here allows the tile rendering // function to send custom heades without access // to the request object. data[1] = _.extend(settings.header_defaults, data[1]); res.send.apply(res, data); } else { next(err); } }); }); }
var _ = require('underscore')._, Tile = require('tilelive.js'); var mapnik = require('mapnik'); mapnik.register_datasources('/usr/local/lib/mapnik2/input'); mapnik.register_fonts('/usr/local/lib/mapnik2/fonts/'); module.exports = function(app, settings) { app.get('/:scheme/:mapfile_64/:z/:x/:y.*', function(req, res, next) { /* * scheme: (xyz|tms|tile (tms)) * * format: * - Tile: (png|jpg) * - Data Tile: (geojson) * - Grid Tile: (*.grid.json) */ try { var tile = new Tile( req.params.scheme, req.params.mapfile_64, req.params.z, req.params.x, req.params.y, req.params[0], settings.mapfile_dir); } catch (err) { res.send('Tile invalid: ' + err.message); } tile.render(function(err, data) { if (!err) { // Using apply here allows the tile rendering // function to send custom heades without access // to the request object. data[1] = _.extend(settings.header_defaults, data[1]); res.send.apply(res, data); } else { next(err); } }); }); }
Adjust the settings reset to work with Django 1.4 Django changed the `settings._wrapped` value from `None` to the special `empty` object. This change maintains backwards compatibility for 1.3.X, while using the new method for all other versions of Django.
import django import os, sys DEFAULT_SETTINGS = { 'DATABASE_ENGINE': 'sqlite3', 'DATABASES': { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'mydatabase' } }, } class VirtualDjango(object): def __init__(self, caller=sys.modules['__main__'], default_settings=DEFAULT_SETTINGS): self.caller = caller self.default_settings = default_settings def configure_settings(self, customizations, reset=True): # Django expects a `DATABASE_ENGINE` value custom_settings = self.default_settings custom_settings.update(customizations) settings = self.settings if reset: self.reset_settings(settings) settings.configure(**custom_settings) def reset_settings(self, settings): if django.VERSION[:2] == (1, 3): settings._wrapped = None return # This is the way to reset settings going forward from django.utils.functional import empty settings._wrapped = empty @property def settings(self): from django.conf import settings return settings @property def call_command(self): from django.core.management import call_command return call_command def run(self, my_settings): if hasattr(self.caller, 'setUp'): self.caller.setUp() self.configure_settings(my_settings) return self.call_command
import os, sys DEFAULT_SETTINGS = { 'DATABASE_ENGINE': 'sqlite3', 'DATABASES': { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'mydatabase' } }, } class VirtualDjango(object): def __init__(self, caller=sys.modules['__main__'], default_settings=DEFAULT_SETTINGS): self.caller = caller self.default_settings = default_settings def configure_settings(self, customizations, reset=True): # Django expects a `DATABASE_ENGINE` value custom_settings = self.default_settings custom_settings.update(customizations) settings = self.settings if reset: settings._wrapped = None settings.configure(**custom_settings) @property def settings(self): from django.conf import settings return settings @property def call_command(self): from django.core.management import call_command return call_command def run(self, my_settings): if hasattr(self.caller, 'setUp'): self.caller.setUp() self.configure_settings(my_settings) return self.call_command
Update Development Status to stable
""" Drupdates setup script. """ try: from setuptools import setup except ImportError: from distutils.core import setup setup( name='Drupdates', description='Drupal updates scripts', author='Jim Taylor', url='https://github.com/jalama/drupdates', download_url='https://github.com/jalama/drupdates', author_email='[email protected]', version='1.4.0', package_dir={'drupdates' : 'drupdates', 'drupdates.tests' : 'drupdates/tests'}, include_package_data=True, install_requires=['nose', 'gitpython', 'requests', 'pyyaml'], entry_points={ 'console_scripts': ['drupdates = drupdates.cli:main'], }, packages=['drupdates', 'drupdates.tests'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: System :: Systems Administration', 'Topic :: Software Development :: Build Tools', 'Topic :: Software Development :: Bug Tracking', ], )
""" Drupdates setup script. """ try: from setuptools import setup except ImportError: from distutils.core import setup setup( name='Drupdates', description='Drupal updates scripts', author='Jim Taylor', url='https://github.com/jalama/drupdates', download_url='https://github.com/jalama/drupdates', author_email='[email protected]', version='1.4.0', package_dir={'drupdates' : 'drupdates', 'drupdates.tests' : 'drupdates/tests'}, include_package_data=True, install_requires=['nose', 'gitpython', 'requests', 'pyyaml'], entry_points={ 'console_scripts': ['drupdates = drupdates.cli:main'], }, packages=['drupdates', 'drupdates.tests'], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: System :: Systems Administration', 'Topic :: Software Development :: Build Tools', 'Topic :: Software Development :: Bug Tracking', ], )
Remove upper case Not Present
from django import forms from datasets.models import DatasetRelease, CategoryComment class DatasetReleaseForm(forms.ModelForm): max_number_of_sounds = forms.IntegerField(required=False) class Meta: model = DatasetRelease fields = ['release_tag', 'type'] class PresentNotPresentUnsureForm(forms.Form): vote = forms.ChoiceField( required=True, widget=forms.RadioSelect, choices=( ('1', 'Present and predominant',), ('0.5', 'Present but not predominant',), ('-1', 'Not present',), ('0', 'Unsure',), ), ) annotation_id = forms.IntegerField( required=True, widget=forms.HiddenInput, ) visited_sound = forms.BooleanField( required=False, initial=False, widget=forms.HiddenInput, ) class CategoryCommentForm(forms.ModelForm): class Meta: model = CategoryComment fields = ['comment', 'category_id', 'dataset'] widgets = { 'comment': forms.Textarea(attrs={ 'cols': 80, 'rows': 3, 'placeholder': 'Add here any general comments you want to make about this category'}), 'category_id': forms.HiddenInput, 'dataset_id': forms.HiddenInput, }
from django import forms from datasets.models import DatasetRelease, CategoryComment class DatasetReleaseForm(forms.ModelForm): max_number_of_sounds = forms.IntegerField(required=False) class Meta: model = DatasetRelease fields = ['release_tag', 'type'] class PresentNotPresentUnsureForm(forms.Form): vote = forms.ChoiceField( required=True, widget=forms.RadioSelect, choices=( ('1', 'Present and predominant',), ('0.5', 'Present but not predominant',), ('-1', 'Not Present',), ('0', 'Unsure',), ), ) annotation_id = forms.IntegerField( required=True, widget=forms.HiddenInput, ) visited_sound = forms.BooleanField( required=False, initial=False, widget=forms.HiddenInput, ) class CategoryCommentForm(forms.ModelForm): class Meta: model = CategoryComment fields = ['comment', 'category_id', 'dataset'] widgets = { 'comment': forms.Textarea(attrs={ 'cols': 80, 'rows': 3, 'placeholder': 'Add here any general comments you want to make about this category'}), 'category_id': forms.HiddenInput, 'dataset_id': forms.HiddenInput, }
Fix test for anonymity in documentation
# -*- coding: utf-8 -*- from flask import Blueprint, render_template, url_for as base_url_for from flask.ext.security import current_user from ..extensions import user_datastore from ..models.taxis import Taxi from functools import partial mod = Blueprint('examples', __name__) @mod.route('/documentation/examples') def doc_index(): if not current_user.is_anonymous: apikeys_operator = set() apikeys_moteur = set() if 'operateur' in current_user.roles: apikeys_operator.add(('your token', current_user.apikey)) if 'moteur' in current_user.roles: apikeys_moteur.add(('your token', current_user.apikey)) apikeys_operator.add(('neotaxi', user_datastore.find_user(email='neotaxi').apikey)) apikeys_moteur.add(('neomap', user_datastore.find_user(email='neomap').apikey)) taxis = Taxi.query.filter(Taxi.added_by==user_datastore.\ find_user(email='neotaxi').id).all() else: apikeys_operator = [('anonymous', 'token')] apikeys_moteur = [('anonymous', 'token')] taxis = [] url_for = partial(base_url_for, _external=True) return render_template('documentation/examples.html', apikeys_operator=apikeys_operator, apikeys_moteur=apikeys_moteur, taxis=taxis, url_for=url_for)
# -*- coding: utf-8 -*- from flask import Blueprint, render_template, url_for as base_url_for from flask.ext.security import current_user from ..extensions import user_datastore from ..models.taxis import Taxi from functools import partial mod = Blueprint('examples', __name__) @mod.route('/documentation/examples') def doc_index(): if not current_user.is_anonymous(): apikeys_operator = set() apikeys_moteur = set() if 'operateur' in current_user.roles: apikeys_operator.add(('your token', current_user.apikey)) if 'moteur' in current_user.roles: apikeys_moteur.add(('your token', current_user.apikey)) apikeys_operator.add(('neotaxi', user_datastore.find_user(email='neotaxi').apikey)) apikeys_moteur.add(('neomap', user_datastore.find_user(email='neomap').apikey)) taxis = Taxi.query.filter(Taxi.added_by==user_datastore.\ find_user(email='neotaxi').id).all() else: apikeys_operator = [('anonymous', 'token')] apikeys_moteur = [('anonymous', 'token')] taxis = [] url_for = partial(base_url_for, _external=True) return render_template('documentation/examples.html', apikeys_operator=apikeys_operator, apikeys_moteur=apikeys_moteur, taxis=taxis, url_for=url_for)
Fix test paths on Mac OS
<?php namespace AppBundle\ShowUnusedPhpFiles; /** * Tests for the CommonPathDeterminator. */ final class CommonPathDeterminatorTest extends \PHPUnit_Framework_TestCase { /** * @test */ public function returnsEmptyStringForEmptyInput() { $result = (new CommonPathDeterminator())->determineCommonPath([]); $this->assertInternalType('string', $result); $this->assertEmpty($result); } /** * @test */ public function returnsEmptyStringIfNoCommonPath() { $result = (new CommonPathDeterminator())->determineCommonPath(['abc', 'def']); $this->assertInternalType('string', $result); $this->assertEmpty($result); } /** * @test */ public function returnsCommonPath() { $result = (new CommonPathDeterminator())->determineCommonPath([__DIR__ . '/fixtures/ignored', __DIR__ . '/fixtures/used']); $this->assertInternalType('string', $result); $this->assertEquals(__DIR__ . '/fixtures', $result); } /** * @test */ public function returnsCommonPathAndIsNotTrickedByCommonFileName() { $result = (new CommonPathDeterminator())->determineCommonPath([__DIR__ . '/fixtures/common-1', __DIR__ . '/fixtures/common-2']); $this->assertInternalType('string', $result); $this->assertEquals(__DIR__ . '/fixtures', $result); } }
<?php namespace AppBundle\ShowUnusedPhpFiles; /** * Tests for the CommonPathDeterminator. */ final class CommonPathDeterminatorTest extends \PHPUnit_Framework_TestCase { /** * @test */ public function returnsEmptyStringForEmptyInput() { $result = (new CommonPathDeterminator())->determineCommonPath([]); $this->assertInternalType('string', $result); $this->assertEmpty($result); } /** * @test */ public function returnsEmptyStringIfNoCommonPath() { $result = (new CommonPathDeterminator())->determineCommonPath(['abc', 'def']); $this->assertInternalType('string', $result); $this->assertEmpty($result); } /** * @test */ public function returnsCommonPath() { $result = (new CommonPathDeterminator())->determineCommonPath(['/var/a', '/var/b']); $this->assertInternalType('string', $result); $this->assertEquals('/var', $result); } /** * @test */ public function returnsCommonPathAndIsNotTrickedByCommonFileName() { $result = (new CommonPathDeterminator())->determineCommonPath(['/var/common-1', '/var/common-2']); $this->assertInternalType('string', $result); $this->assertEquals('/var', $result); } }
Fix gomp library dynamic loading issues * bug introduce from commit : 4a4676258bfd47a7fbefc51644eb58ffc60ab6ad
''' OpenMP wrapper using a (user provided) libgomp dynamically loaded library ''' import sys import glob import ctypes class omp(object): LD_LIBRARY_PATHS = [ "/usr/lib/x86_64-linux-gnu/", # MacPorts install gcc in a "non standard" path on OSX ] + glob.glob("/opt/local/lib/gcc*/") def __init__(self): # Paths are "non-standard" place to lookup paths = omp.LD_LIBRARY_PATHS # Try to load find libgomp shared library using loader search dirs libgomp_path = ctypes.util.find_library("gomp") # Try to use custom paths if lookup failed for path in paths: if libgomp_path: break libgomp_path = ctypes.util.find_library(path+"gomp") if not libgomp_path: raise EnvironmentError("I can't find a shared library for libgomp," " you may need to install it or adjust the " "LD_LIBRARY_PATH environment variable.") else: # Load the library (shouldn't fail with an absolute path right?) self.libomp = ctypes.CDLL(libgomp_path) def __getattribute__(self, name): if name == 'libomp': return object.__getattribute__(self, 'libomp') else: return getattr(self.libomp, 'omp_' + name) # see http://mail.python.org/pipermail/python-ideas/2012-May/014969.html sys.modules[__name__] = omp()
''' OpenMP wrapper using a (user provided) libgomp dynamically loaded library ''' import sys import glob import ctypes class omp(object): LD_LIBRARY_PATHS = [ "/usr/lib/x86_64-linux-gnu/", # MacPorts install gcc in a "non standard" path on OSX ] + glob.glob("/opt/local/lib/gcc*/") def __init__(self): # Paths are "non-standard" place to lookup paths = omp.LD_LIBRARY_PATHS # Try to load find libgomp shared library using loader search dirs libgomp_path = ctypes.util.find_library("libgomp") # Try to use custom paths if lookup failed for path in paths: if libgomp_path: break libgomp_path = ctypes.util.find_library(path+"libgomp") if not libgomp_path: raise EnvironmentError("I can't find a shared library for libgomp," " you may need to install it or adjust the " "LD_LIBRARY_PATH environment variable.") else: # Load the library (shouldn't fail with an absolute path right?) self.libomp = ctypes.CDLL(libgomp_path) def __getattribute__(self, name): if name == 'libomp': return object.__getattribute__(self, 'libomp') else: return getattr(self.libomp, 'omp_' + name) # see http://mail.python.org/pipermail/python-ideas/2012-May/014969.html sys.modules[__name__] = omp()
Stop displaying x as the code
#!/usr/bin/env python3 ''' Given: 1. status code: (0 - OK, other value - BAD) 2. terminal window width shows red/green bar to visualize return code of previous command ''' import sys def main(): if len(sys.argv) >= 2: code = sys.argv[1] if code == 'x': col_char = '3' cols_limit = 78 code = '' # No code provided - only yellow bar else: if code == 'y': col_char = '3' else: value = int(code) if value: col_char = '1' else: col_char = '2' cols_limit = int(sys.argv[2]) esc = chr(27) print (''.join(( esc, '[4', col_char, 'm', ' ' * (cols_limit - 2 - len(code)), code, esc, '[0m', ))) else: print (''' Usage: %(prog_name)s status_code number_of_columns 1. status code: 0 - OK (green color), other values - BAD (red color) 2. number of columns: the width of text console ''' % dict( prog_name=sys.argv[0], ))
#!/usr/bin/env python3 ''' Given: 1. status code: (0 - OK, other value - BAD) 2. terminal window width shows red/green bar to visualize return code of previous command ''' import sys def main(): if len(sys.argv) >= 2: code = sys.argv[1] if code == 'x': col_char = '3' cols_limit = 78 else: if code == 'y': col_char = '3' else: value = int(code) if value: col_char = '1' else: col_char = '2' cols_limit = int(sys.argv[2]) esc = chr(27) print (''.join(( esc, '[4', col_char, 'm', ' ' * (cols_limit - 2 - len(code)), code, esc, '[0m', ))) else: print (''' Usage: %(prog_name)s status_code number_of_columns 1. status code: 0 - OK (green color), other values - BAD (red color) 2. number of columns: the width of text console ''' % dict( prog_name=sys.argv[0], ))
Clean up ACL code for axo 20483
<?php namespace Rcm\Acl\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity * @ORM\Table( * name="rcm_acl_user_group", * indexes={@ORM\Index(name="userIdIndex", columns={"userId"})}) * ) */ class UserGroup { /** * @var integer * * @ORM\GeneratedValue * @ORM\Id * @ORM\Column(type="integer") */ protected $id; /** * @var string * * @ORM\Column(type="string") */ protected $userId; /** * @var string * * @ORM\Column(type="string") */ protected $group; /** * @return string */ public function getUserId(): string { return $this->userId; } /** * @param string $userId */ public function setUserId(string $userId): void { $this->userId = $userId; } /** * @return string */ public function getGroup(): string { return $this->group; } /** * @param string $group */ public function setGroup(string $group): void { $this->group = $group; } }
<?php namespace Rcm\Acl\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity * @ORM\Table( * name="rcm_acl_user_group", * indexes={@ORM\Index(name="userIdIndex", columns={"userId"})}) * ) */ class UserGroup { /** * @var integer * * @ORM\GeneratedValue * @ORM\Id * @ORM\Column(type="integer") */ protected $id; /** * @TODO add an index to this * * @var string * * @ORM\Column(type="string") */ protected $userId; /** * @var string * * @ORM\Column(type="string") */ protected $group; /** * @return string */ public function getUserId(): string { return $this->userId; } /** * @param string $userId */ public function setUserId(string $userId): void { $this->userId = $userId; } /** * @return string */ public function getGroup(): string { return $this->group; } /** * @param string $group */ public function setGroup(string $group): void { $this->group = $group; } }
Add missing FROM expression to consent SQL query
<?php namespace OpenConext\EngineBlock\Authentication\Repository; use DateTime; use Doctrine\DBAL\Connection as DbalConnection; use Doctrine\DBAL\DBALException; use OpenConext\EngineBlock\Authentication\Entity\Consent; use PDO; final class ConsentRepository { /** * @var DbalConnection */ private $connection; /** * @param DbalConnection $connection */ public function __construct(DbalConnection $connection) { $this->connection = $connection; } /** * @param string $userId * @return Consent[] * @throws DBALException */ public function findAll($userId) { $sql = 'SELECT service_id, consent_date, usage_date FROM consent WHERE hashed_user_id=:hashed_user_id'; $statement = $this->connection->executeQuery($sql, array('hashed_user_id' => sha1($userId))); $rows = $statement->fetchAll(PDO::FETCH_ASSOC); return array_map( function (array $row) use ($userId) { return new Consent( $userId, $row['service_id'], new DateTime($row['consent_date']), new DateTime($row['usage_date']) ); }, $rows ); } }
<?php namespace OpenConext\EngineBlock\Authentication\Repository; use DateTime; use Doctrine\DBAL\Connection as DbalConnection; use Doctrine\DBAL\DBALException; use OpenConext\EngineBlock\Authentication\Entity\Consent; use PDO; final class ConsentRepository { /** * @var DbalConnection */ private $connection; /** * @param DbalConnection $connection */ public function __construct(DbalConnection $connection) { $this->connection = $connection; } /** * @param string $userId * @return Consent[] * @throws DBALException */ public function findAll($userId) { $sql = 'SELECT service_id, consent_date, usage_date WHERE hashed_user_id=:hashed_user_id'; $statement = $this->connection->executeQuery($sql, array('hashed_user_id' => sha1($userId))); $rows = $statement->fetchAll(PDO::FETCH_ASSOC); return array_map( function (array $row) use ($userId) { return new Consent( $userId, $row['service_id'], new DateTime($row['consent_date']), new DateTime($row['usage_date']) ); }, $rows ); } }
Fix Trl Form_Dynamic: add missing parent call to getTemplateVars cssClass was missing
<?php class Kwc_Form_Dynamic_Trl_Component extends Kwc_Abstract_Composite_Trl_Component { public static function getSettings($masterComponentClass) { $ret = parent::getSettings($masterComponentClass); //form nicht übersetzen, sondern die exakt gleiche wie im master verwenden $g = Kwc_Abstract::getSetting($masterComponentClass, 'generators'); $ret['generators']['child']['component']['form'] = $g['child']['component']['form']; $ret['generators']['child']['masterComponentsMap'][$g['child']['component']['form']] = $g['child']['component']['form']; $ret['ownModel'] = 'Kwf_Component_FieldModel'; return $ret; } public function getTemplateVars() { $ret = parent::getTemplateVars(); $data = $this->getData(); $ret['data'] = $data; $ret['chained'] = $data->chained; $ret['template'] = self::getTemplateFile($data->chained->componentClass); $ret['form'] = $this->getData()->getChildComponent('-form'); return $ret; } public function getMailSettings() { $ret = $this->getData()->chained->getComponent()->getMailSettings(); $row = $this->getData()->getComponent()->getRow(); if ($row->subject) $ret['subject'] = $row->subject; if ($ret['send_confirm_mail'] && $row->confirm_subject) $ret['confirm_subject'] = $row->confirm_subject; return $ret; } }
<?php class Kwc_Form_Dynamic_Trl_Component extends Kwc_Abstract_Composite_Trl_Component { public static function getSettings($masterComponentClass) { $ret = parent::getSettings($masterComponentClass); //form nicht übersetzen, sondern die exakt gleiche wie im master verwenden $g = Kwc_Abstract::getSetting($masterComponentClass, 'generators'); $ret['generators']['child']['component']['form'] = $g['child']['component']['form']; $ret['generators']['child']['masterComponentsMap'][$g['child']['component']['form']] = $g['child']['component']['form']; $ret['ownModel'] = 'Kwf_Component_FieldModel'; return $ret; } public function getTemplateVars() { $data = $this->getData(); $ret['data'] = $data; $ret['chained'] = $data->chained; $ret['template'] = self::getTemplateFile($data->chained->componentClass); $ret['form'] = $this->getData()->getChildComponent('-form'); return $ret; } public function getMailSettings() { $ret = $this->getData()->chained->getComponent()->getMailSettings(); $row = $this->getData()->getComponent()->getRow(); if ($row->subject) $ret['subject'] = $row->subject; if ($ret['send_confirm_mail'] && $row->confirm_subject) $ret['confirm_subject'] = $row->confirm_subject; return $ret; } }
Use fixed value in the helper
from __future__ import absolute_import from ..layer import Layer def color_category_layer(source, value, top=11, palette='bold', title=''): return Layer( source, style={ 'point': { 'color': 'ramp(top(${0}, {1}), {2})'.format(value, top, palette) }, 'line': { 'color': 'ramp(top(${0}, {1}), {2})'.format(value, top, palette) }, 'polygon': { 'color': 'opacity(ramp(top(${0}, {1}), {2}), 0.9)'.format(value, top, palette) } }, popup={ 'hover': { 'label': title or value, 'value': '$' + value } }, legend={ 'type': 'basic', 'ramp': 'color', 'heading': title or value, 'description': '', 'othersLabel': 'Others' } )
from __future__ import absolute_import from ..layer import Layer def color_category_layer(source, value, top=11, palette='bold', title='', othersLabel='Others'): return Layer( source, style={ 'point': { 'color': 'ramp(top(${0}, {1}), {2})'.format(value, top, palette) }, 'line': { 'color': 'ramp(top(${0}, {1}), {2})'.format(value, top, palette) }, 'polygon': { 'color': 'opacity(ramp(top(${0}, {1}), {2}), 0.1)'.format(value, top, palette) } }, popup={ 'hover': { 'label': title or value, 'value': '$' + value } }, legend={ 'type': 'basic', 'ramp': 'color', 'heading': title or value, 'description': '', 'othersLabel': othersLabel } )
Add key prop to column containers
import React from "react/addons"; import times from "lodash.times"; const BATCH_SIZE = 2; class Columns extends React.Component { constructor(props) { super(props); } convertChildren(children) { if (children.length === 0) { return [] } if (children.length) { return children; } else { return [children]; } } componentWillMount() { } componentWillReceiveProps(newProps) { } componentDidMount() { } componentDidUnmount() { } componentDidUpdate() { } columnize(number, items) { let columns = []; times(number, n => { columns[n] = []; }); for (var i = 0; i < items.length; i++) { let item = items[i]; columns[i % number].push(item); } return columns; } render() { let items = this.convertChildren(this.props.children); let autoNumber = Math.min(items.length, this.props.number); let columnization = this.columnize(autoNumber, items); let containerElement = this.props.container || <div/> let columnContainers = columnization.map((column, i) => { return React.cloneElement(containerElement, {key: i}, column); } ); return ( <div id={this.props.id} className={this.props.className} style={this.props.style}> {columnContainers} </div> ); } } export default Columns;
import React from "react/addons"; import times from "lodash.times"; const BATCH_SIZE = 2; class Columns extends React.Component { constructor(props) { super(props); } convertChildren(children) { if (children.length === 0) { return [] } if (children.length) { return children; } else { return [children]; } } componentWillMount() { } componentWillReceiveProps(newProps) { } componentDidMount() { } componentDidUnmount() { } componentDidUpdate() { } columnize(number, items) { let columns = []; times(number, n => { columns[n] = []; }); for (var i = 0; i < items.length; i++) { let item = items[i]; columns[i % number].push(item); } return columns; } render() { let items = this.convertChildren(this.props.children); let autoNumber = Math.min(items.length, this.props.number); let columnization = this.columnize(autoNumber, items); let containerElement = this.props.container || <div/> let columnContainers = columnization.map(column => { return React.cloneElement(containerElement, {}, column); } ); return ( <div id={this.props.id} className={this.props.className} style={this.props.style}> {columnContainers} </div> ); } } export default Columns;
Set migrate to default safe to skip a step when running 'sails lift' in terminal
/** * Default model configuration * (sails.config.models) * * Unless you override them, the following properties will be included * in each of your models. * * For more info on Sails models, see: * http://sailsjs.org/#/documentation/concepts/ORM */ module.exports.models = { /*************************************************************************** * * * Your app's default connection. i.e. the name of one of your app's * * connections (see `config/connections.js`) * * * ***************************************************************************/ // connection: 'localDiskDb', /*************************************************************************** * * * How and whether Sails will attempt to automatically rebuild the * * tables/collections/etc. in your schema. * * * * See http://sailsjs.org/#/documentation/concepts/ORM/model-settings.html * * * ***************************************************************************/ migrate: 'safe' };
/** * Default model configuration * (sails.config.models) * * Unless you override them, the following properties will be included * in each of your models. * * For more info on Sails models, see: * http://sailsjs.org/#/documentation/concepts/ORM */ module.exports.models = { /*************************************************************************** * * * Your app's default connection. i.e. the name of one of your app's * * connections (see `config/connections.js`) * * * ***************************************************************************/ // connection: 'localDiskDb', /*************************************************************************** * * * How and whether Sails will attempt to automatically rebuild the * * tables/collections/etc. in your schema. * * * * See http://sailsjs.org/#/documentation/concepts/ORM/model-settings.html * * * ***************************************************************************/ // migrate: 'alter' };
Allow enter button to trigger login.
var authDialog; var loadingDialog; var authDialogPassword; var authSubmit; var forwardUrl = QueryString.fu; function onLoad() { authDialog = $("#auth_dialog"); loadingDialog = $("#busy_dialog"); authDialogPassword = $("#auth_dialog_password"); authSubmit = $("#auth_submit"); setupDialogs(); setupLogin(); //Show auth dialog rawElement(authDialog).showModal(); } function setupDialogs() { //Dialog polyfills if (!rawElement(loadingDialog).showModal) { dialogPolyfill.registerDialog(rawElement(loadingDialog)); } if (!rawElement(authDialog).showModal) { dialogPolyfill.registerDialog(rawElement(authDialog)); } } function setupLogin() { authSubmit.click(function () { rawElement(authDialog).close(); rawElement(loadingDialog).showModal(); TWApi.Commands.Auth.execute(function () { if (!valid(forwardUrl)) { forwardUrl = "/"; } //Redirect to forward URL window.location = forwardUrl; }, function () { authError(); rawElement(loadingDialog).close(); rawElement(authDialog).showModal(); }, {password: authDialogPassword.val()}) }); //Enter button triggers login authDialogPassword.keyup(function (event) { if (event.keyCode == 13) { authSubmit.click(); } }); } function authError() { snackbar.showSnackbar({ message: "Authentication error!", timeout: 2000 }); }
var authDialog; var loadingDialog; var authDialogPassword; var authSubmit; var forwardUrl = QueryString.fu; function onLoad() { authDialog = $("#auth_dialog"); loadingDialog = $("#busy_dialog"); authDialogPassword = $("#auth_dialog_password"); authSubmit = $("#auth_submit"); setupDialogs(); setupLogin(); rawElement(authDialog).showModal(); } function setupDialogs() { //Dialog polyfills if (!rawElement(loadingDialog).showModal) { dialogPolyfill.registerDialog(rawElement(loadingDialog)); } if (!rawElement(authDialog).showModal) { dialogPolyfill.registerDialog(rawElement(authDialog)); } } function setupLogin() { authSubmit.click(function () { rawElement(authDialog).close(); rawElement(loadingDialog).showModal(); TWApi.Commands.Auth.execute(function () { if (!valid(forwardUrl)) { forwardUrl = "/"; } //Redirect to forward URL window.location = forwardUrl; }, function () { authError(); rawElement(loadingDialog).close(); rawElement(authDialog).showModal(); }, {password: authDialogPassword.val()}) }); } function authError() { snackbar.showSnackbar({ message: "Authentication error!", timeout: 2000 }); }
Fix Doc comment (width => integer)
<?php /* * This file is part of PHP-FFmpeg. * * (c) Alchemy <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace FFMpeg\Coordinate; use FFMpeg\Exception\InvalidArgumentException; /** * Dimension object, used for manipulating width and height couples */ class Dimension { private $width; private $height; /** * @param integer $width * @param integer $height * * @throws InvalidArgumentException when one of the parameteres is invalid */ public function __construct($width, $height) { if ($width <= 0 || $height <= 0) { throw new InvalidArgumentException('Width and height should be positive integer'); } $this->width = (int) $width; $this->height = (int) $height; } /** * Returns width. * * @return integer */ public function getWidth() { return $this->width; } /** * Returns height. * * @return integer */ public function getHeight() { return $this->height; } /** * Returns the ratio. * * @param type $forceStandards Whether or not force the use of standards ratios; * * @return AspectRatio */ public function getRatio($forceStandards = true) { return AspectRatio::create($this, $forceStandards); } }
<?php /* * This file is part of PHP-FFmpeg. * * (c) Alchemy <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace FFMpeg\Coordinate; use FFMpeg\Exception\InvalidArgumentException; /** * Dimension object, used for manipulating width and height couples */ class Dimension { private $width; private $height; /** * @param integer $width * @param integer $height * * @throws InvalidArgumentException when one of the parameteres is invalid */ public function __construct($width, $height) { if ($width <= 0 || $height <= 0) { throw new InvalidArgumentException('Width and height should be positive integer'); } $this->width = (int) $width; $this->height = (int) $height; } /** * Returns width. * * @return width */ public function getWidth() { return $this->width; } /** * Returns height. * * @return integer */ public function getHeight() { return $this->height; } /** * Returns the ratio. * * @param type $forceStandards Whether or not force the use of standards ratios; * * @return AspectRatio */ public function getRatio($forceStandards = true) { return AspectRatio::create($this, $forceStandards); } }
Remove polyfill from unit test
var path = require('path') module.exports = function(config) { config.set({ singleRun: true, files: [ 'test/index.js', 'test/eventing.js' ], frameworks: [ 'mocha' ], preprocessors: { 'test/index.js': [ 'webpack', 'sourcemap' ], 'test/eventing.js': [ 'webpack', 'sourcemap' ] }, logLevel: config.LOG_INFO, reporters: [ 'spec' ], webpack: { devtool: 'inline-source-map', module: { loaders: [{ test: /\.js$/, loader: 'babel', include: [ path.join(__dirname, 'test') ] }] }, resolve: { modulesDirectories: [ '', 'node_modules' ], alias: { 'stream-dom': path.join(__dirname, 'lib') }, extensions: [ '', '.js' ] } }, webpackMiddleware: { // Display no info to console (only warnings and errors) noInfo: true }, plugins: [ require('karma-webpack'), require('karma-sourcemap-loader'), require('karma-mocha'), require('karma-chrome-launcher'), require('karma-firefox-launcher'), require('karma-spec-reporter') ], browsers: [ 'Chrome', 'Firefox' ] }) }
var path = require('path') module.exports = function(config) { config.set({ singleRun: true, files: [ './node_modules/babel-polyfill/browser.js', 'test/index.js', 'test/eventing.js' ], frameworks: [ 'mocha' ], preprocessors: { 'test/index.js': [ 'webpack', 'sourcemap' ], 'test/eventing.js': [ 'webpack', 'sourcemap' ] }, logLevel: config.LOG_INFO, reporters: [ 'spec' ], webpack: { devtool: 'inline-source-map', module: { loaders: [{ test: /\.js$/, loader: 'babel', include: [ path.join(__dirname, 'test') ] }] }, resolve: { modulesDirectories: [ '', 'node_modules' ], alias: { 'stream-dom': path.join(__dirname, 'lib') }, extensions: [ '', '.js' ] } }, webpackMiddleware: { // Display no info to console (only warnings and errors) noInfo: true }, plugins: [ require('karma-webpack'), require('karma-sourcemap-loader'), require('karma-mocha'), require('karma-chrome-launcher'), require('karma-firefox-launcher'), require('karma-spec-reporter') ], browsers: [ 'Chrome', 'Firefox' ] }) }
Send hostname from java client
package com.bugsnag; import java.net.InetAddress; import org.json.JSONObject; import org.json.JSONException; import com.bugsnag.utils.JSONUtils; public class Diagnostics { protected Configuration config; protected JSONObject deviceData = new JSONObject(); protected JSONObject appData = new JSONObject(); public Diagnostics(Configuration config) { this.config = config; JSONUtils.safePutOpt(deviceData, "osName", System.getProperty("os.name")); JSONUtils.safePutOpt(deviceData, "name", InetAddress.getLocalHost().getHostName()); } public JSONObject getAppData() { JSONUtils.safePutOpt(appData, "version", config.appVersion.get()); JSONUtils.safePutOpt(appData, "releaseStage", config.releaseStage.get()); return appData; } public JSONObject getAppState() { return new JSONObject(); } public JSONObject getDeviceData() { JSONUtils.safePutOpt(deviceData, "osVersion", config.osVersion.get()); return deviceData; } public JSONObject getDeviceState() { return new JSONObject(); } public String getContext() { return config.context.get(); } public JSONObject getUser() { return config.user; } public JSONObject getMetrics() { JSONObject metrics = new JSONObject(); JSONUtils.safePutOpt(metrics, "user", getUser()); JSONUtils.safePutOpt(metrics, "app", getAppData()); JSONUtils.safePutOpt(metrics, "device", getDeviceData()); return metrics; } }
package com.bugsnag; import org.json.JSONObject; import org.json.JSONException; import com.bugsnag.utils.JSONUtils; public class Diagnostics { protected Configuration config; protected JSONObject deviceData = new JSONObject(); protected JSONObject appData = new JSONObject(); public Diagnostics(Configuration config) { this.config = config; JSONUtils.safePutOpt(deviceData, "osName", System.getProperty("os.name")); } public JSONObject getAppData() { JSONUtils.safePutOpt(appData, "version", config.appVersion.get()); JSONUtils.safePutOpt(appData, "releaseStage", config.releaseStage.get()); return appData; } public JSONObject getAppState() { return new JSONObject(); } public JSONObject getDeviceData() { JSONUtils.safePutOpt(deviceData, "osVersion", config.osVersion.get()); return deviceData; } public JSONObject getDeviceState() { return new JSONObject(); } public String getContext() { return config.context.get(); } public JSONObject getUser() { return config.user; } public JSONObject getMetrics() { JSONObject metrics = new JSONObject(); JSONUtils.safePutOpt(metrics, "user", getUser()); JSONUtils.safePutOpt(metrics, "app", getAppData()); JSONUtils.safePutOpt(metrics, "device", getDeviceData()); return metrics; } }
Remove old versions with DB versions seeder (+ rename 1.7.10 to 1.7)
<?php use Illuminate\Database\Seeder; class MinecraftVersionsSeeder extends Seeder { private $versionsByType = [ 'PC' => [ 5 => '1.7', // 1.7.10 (not 1.7.2) 47 => '1.8', 107 => '1.9', 210 => '1.10', 315 => '1.11', 335 => '1.12', ], 'PE' => [ ] ]; /** * Run the database seeds. * * @return void */ public function run() { $ids = []; foreach ($this->versionsByType as $type => $versions) { foreach ($versions as $protocol_id => $name) { $id = DB::table('versions')->select('id')->where('type', $type)->where('name', $name)->first(); if ($id !== null) { $id = $id->id; } else { $id = DB::table('versions')->insertGetId([ 'type' => $type, 'protocol_id' => $protocol_id, 'name' => $name, ]); } $ids[] = $id; } } DB::table('versions')->whereNotIn('id', $ids)->delete(); } }
<?php use Illuminate\Database\Seeder; class MinecraftVersionsSeeder extends Seeder { private $versionsByType = [ 'PC' => [ 5 => '1.7.10', 47 => '1.8', 107 => '1.9', 210 => '1.10', 315 => '1.11', 335 => '1.12', ], 'PE' => [ ] ]; /** * Run the database seeds. * * @return void */ public function run() { foreach ($this->versionsByType as $type => $versions) { foreach ($versions as $protocol_id => $name) { $exists = DB::table('versions')->where('type', $type)->where('name', $name)->exists(); if (!$exists) { try { DB::table('versions')->insert([ 'type' => $type, 'protocol_id' => $protocol_id, 'name' => $name, ]); } catch (\Illuminate\Database\QueryException $e) { /* * Ignore duplicate entry exception */ if ($e->getCode() != 23000 /* ER_DUP_CODE */) { throw $e; } } } } } } }
Add service name for service definition initialization manager
<?php /* * This file is part of the PcdxParameterEncryptionBundle package. * * (c) picodexter <https://picodexter.io/> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Picodexter\ParameterEncryptionBundle\DependencyInjection; /** * ServiceNames. * * Contains names for this bundle's Symfony services that are referenced in the code. */ final class ServiceNames { const ALGORITHM_CONFIGURATION = 'pcdx_parameter_encryption.configuration.algorithm_configuration'; const ALGORITHM_PREFIX = 'pcdx_parameter_encryption.configuration.algorithm.'; const PARAMETER_REPLACER = 'pcdx_parameter_encryption.replacement.parameter_replacer'; const PARAMETER_REPLACEMENT_FETCHER = 'pcdx_parameter_encryption.replacement.parameter_replacement_fetcher'; const REPLACEMENT_PATTERN_ALGORITHM_PREFIX = 'pcdx_parameter_encryption.replacement.pattern.algorithm.'; const REPLACEMENT_PATTERN_REGISTRY = 'pcdx_parameter_encryption.replacement.pattern.registry'; const REPLACEMENT_PATTERN_TYPE_REGISTRY = 'pcdx_parameter_encryption.replacement.pattern.type_registry'; const REPLACEMENT_SOURCE_DECRYPTER_ALGORITHM_PREFIX = 'pcdx_parameter_encryption.replacement.source.decrypter.'; const SERVICE_DEFINITION_INITIALIZATION_MANAGER = 'pcdx_parameter_encryption.dependency_injection.service.definition_initialization_manager'; /** * Constructor. * * Forbid instantiation. */ public function __construct() { throw new \BadMethodCallException('This class cannot be instantiated.'); } }
<?php /* * This file is part of the PcdxParameterEncryptionBundle package. * * (c) picodexter <https://picodexter.io/> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Picodexter\ParameterEncryptionBundle\DependencyInjection; /** * ServiceNames. * * Contains names for this bundle's Symfony services that are referenced in the code. */ final class ServiceNames { const ALGORITHM_CONFIGURATION = 'pcdx_parameter_encryption.configuration.algorithm_configuration'; const ALGORITHM_PREFIX = 'pcdx_parameter_encryption.configuration.algorithm.'; const PARAMETER_REPLACER = 'pcdx_parameter_encryption.replacement.parameter_replacer'; const PARAMETER_REPLACEMENT_FETCHER = 'pcdx_parameter_encryption.replacement.parameter_replacement_fetcher'; const REPLACEMENT_PATTERN_ALGORITHM_PREFIX = 'pcdx_parameter_encryption.replacement.pattern.algorithm.'; const REPLACEMENT_PATTERN_REGISTRY = 'pcdx_parameter_encryption.replacement.pattern.registry'; const REPLACEMENT_PATTERN_TYPE_REGISTRY = 'pcdx_parameter_encryption.replacement.pattern.type_registry'; const REPLACEMENT_SOURCE_DECRYPTER_ALGORITHM_PREFIX = 'pcdx_parameter_encryption.replacement.source.decrypter.'; /** * Constructor. * * Forbid instantiation. */ public function __construct() { throw new \BadMethodCallException('This class cannot be instantiated.'); } }
Move string formatting onto two lines for readability
import string import socket import sys import time import threading class SimpleSocket: def __init__(self, hostname="localhost", port=8888, timeout=2): self.access_semaphor = threading.Semaphore(1) try: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error: sys.stderr.write( "socket() [Socket connection error] Cannot connect to %s, error: %s\n" % (hostname, socket.error)) sys.exit(1) self.sock.settimeout(timeout) try: self.sock.connect((hostname, port)) except socket.error: sys.stderr.write("connect() [Socket connection error] Cannot connect to %s:%d, error: %s\n" % ( hostname, port, socket.error)) sys.exit(2) def SendCommand(self, cmd): self.access_semaphor.acquire() cmd += '\n' self.sock.send(cmd.encode('utf-8')) self.access_semaphor.release() def Ask(self, cmd): self.access_semaphor.acquire() cmd += '\n' self.sock.send(cmd.encode('utf-8')) reply = self.sock.recv(2048).strip(b'\n') self.access_semaphor.release() return reply
import string import socket import sys import time import threading class SimpleSocket: def __init__(self, hostname="localhost", port=8888, timeout=2): self.access_semaphor = threading.Semaphore(1) try: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error: sys.stderr.write( "socket() [Socket connection error] Cannot connect to %s, error: %s\n" % (hostname, socket.error)) sys.exit(1) self.sock.settimeout(timeout) try: self.sock.connect((hostname, port)) except socket.error: sys.stderr.write("connect() [Socket connection error] Cannot connect to %s:%d, error: %s\n" % ( hostname, port, socket.error)) sys.exit(2) def SendCommand(self, cmd): self.access_semaphor.acquire() self.sock.send('{}\n'.format(cmd).encode('utf-8')) self.access_semaphor.release() def Ask(self, cmd): self.access_semaphor.acquire() self.sock.send('{}\n'.format(cmd).encode('utf-8')) reply = self.sock.recv(2048).strip(b'\n') self.access_semaphor.release() return reply
Remove required from passwordTrait salt. It has a salt generator fallback.
<?php /** * @link http://zoopcommerce.github.io/shard * @package Zoop * @license MIT */ namespace Zoop\Shard\User\DataModel; use Zoop\Shard\Crypt\SaltGenerator; use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM; use Zoop\Shard\Annotation\Annotations as Shard; /** * Implementation of Zoop\Common\User\PasswordInterface * * @since 1.0 * @author Tim Roediger <[email protected]> */ trait PasswordTrait { /** * @ODM\String * @Shard\Serializer\Ignore * @Shard\Validator\Chain({ * @Shard\Validator\Required, * @Shard\Validator\Password * }) * @Shard\Crypt\Hash */ protected $password; /** * @ODM\String * @Shard\Serializer\Ignore */ protected $salt; /** * Returns encrypted password * * @return string */ public function getPassword() { return $this->password; } /** * * @param string $plaintext */ public function setPassword($plaintext) { $this->password = (string) $plaintext; } public function getSalt() { if (!isset($this->salt)) { $this->salt = SaltGenerator::generateSalt(); } return $this->salt; } public function setSalt($value) { return $this->salt = (string) $value; } }
<?php /** * @link http://zoopcommerce.github.io/shard * @package Zoop * @license MIT */ namespace Zoop\Shard\User\DataModel; use Zoop\Shard\Crypt\SaltGenerator; use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM; use Zoop\Shard\Annotation\Annotations as Shard; /** * Implementation of Zoop\Common\User\PasswordInterface * * @since 1.0 * @author Tim Roediger <[email protected]> */ trait PasswordTrait { /** * @ODM\String * @Shard\Serializer\Ignore * @Shard\Validator\Chain({ * @Shard\Validator\Required, * @Shard\Validator\Password * }) * @Shard\Crypt\Hash */ protected $password; /** * @ODM\String * @Shard\Serializer\Ignore * @Shard\Validator\Required */ protected $salt; /** * Returns encrypted password * * @return string */ public function getPassword() { return $this->password; } /** * * @param string $plaintext */ public function setPassword($plaintext) { $this->password = (string) $plaintext; } public function getSalt() { if (!isset($this->salt)) { $this->salt = SaltGenerator::generateSalt(); } return $this->salt; } public function setSalt($value) { return $this->salt = (string) $value; } }
Reset key parameter on profile path redirect
<?php // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. namespace App\Libraries\User; use App\Exceptions\UserProfilePageLookupException; use App\Models\User; class FindForProfilePage { public static function find($id, ?string $type = null, ?bool $assertCanonicalId = null) { $user = User::lookupWithHistory($id, $type, true); $request = request(); if ($user === null || !priv_check('UserShow', $user)->can()) { throw new UserProfilePageLookupException(function () { if (is_json_request()) { abort(404); } return ext_view('users.show_not_found', null, null, 404); }); } if (($assertCanonicalId ?? !is_json_request()) && (string) $user->getKey() !== (string) $id) { $redirectTarget = route( $request->route()->getName(), array_merge($request->query(), $request->route()->parameters(), ['user' => $user, 'key' => null]) ); throw new UserProfilePageLookupException(fn () => ujs_redirect($redirectTarget)); } return $user; } }
<?php // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. namespace App\Libraries\User; use App\Exceptions\UserProfilePageLookupException; use App\Models\User; class FindForProfilePage { public static function find($id, ?string $type = null, ?bool $assertCanonicalId = null) { $user = User::lookupWithHistory($id, $type, true); $request = request(); if ($user === null || !priv_check('UserShow', $user)->can()) { throw new UserProfilePageLookupException(function () { if (is_json_request()) { abort(404); } return ext_view('users.show_not_found', null, null, 404); }); } if (($assertCanonicalId ?? !is_json_request()) && (string) $user->getKey() !== (string) $id) { $redirectTarget = route( $request->route()->getName(), array_merge($request->query(), $request->route()->parameters(), compact('user')) ); throw new UserProfilePageLookupException(fn () => ujs_redirect($redirectTarget)); } return $user; } }
CRM-2511: Access permissions for items in Activity List - FT fixes
<?php namespace Oro\Bundle\TestFrameworkBundle\Tests\Functional\Api\Rest; use Oro\Bundle\TestFrameworkBundle\Test\WebTestCase; use Oro\Bundle\UserBundle\Entity\User; /** * @outputBuffering enabled * @dbIsolation */ class ActivityListRoleControllerTest extends WebTestCase { protected function setUp() { $this->initClient([], $this->generateWsseAuthHeader(), true); $this->loadFixtures([ 'Oro\Bundle\ActivityListBundle\Tests\Functional\DataFixtures\LoadActivityData', 'Oro\Bundle\ActivityListBundle\Tests\Functional\DataFixtures\LoadUserData' ]); } /** * Test to verify access for user who does not have access to activity other user */ public function testGetListForUserWithOutPermissions() { $this->markTestSkipped("Test skipped. User wssi do not work. Test entity ACL do not work."); $this->client->request( 'GET', $this->getUrl( 'oro_activity_list_api_get_list', [ 'entityClass' => 'Oro_Bundle_TestFrameworkBundle_Entity_TestActivityTarget', 'entityId' => $this->getReference('test_activity_target_1')->getId() ] ) ); $result = $this->getJsonResponseContent($this->client->getResponse(), 200); $this->assertCount(0, $result['data']); $this->assertEquals(0, $result['count']); } }
<?php namespace Oro\Bundle\TestFrameworkBundle\Tests\Functional\Api\Rest; use Oro\Bundle\TestFrameworkBundle\Test\WebTestCase; use Oro\Bundle\UserBundle\Entity\User; /** * @outputBuffering enabled * @dbIsolation */ class ActivityListRoleControllerTest extends WebTestCase { protected function setUp() { $this->initClient([], $this->generateWsseAuthHeader(), true); $this->loadFixtures([ 'Oro\Bundle\ActivityListBundle\Tests\Functional\DataFixtures\LoadActivityData', 'Oro\Bundle\ActivityListBundle\Tests\Functional\DataFixtures\LoadUserData' ]); } /** * Test to verify access for user who does not have access to activity other user */ public function testGetListForUserWithOutPermissions() { $this->markTestSkipped("Test skipped. User wssi do not work"); $this->client->request( 'GET', $this->getUrl( 'oro_activity_list_api_get_list', [ 'entityClass' => 'Oro_Bundle_TestFrameworkBundle_Entity_TestActivityTarget', 'entityId' => $this->getReference('test_activity_target_1')->getId() ] ) ); $result = $this->getJsonResponseContent($this->client->getResponse(), 200); $this->assertCount(0, $result['data']); $this->assertEquals(0, $result['count']); } }
Add more information to callback matchers exception messages
<?php namespace PhpSpec\Matcher; use PhpSpec\Formatter\Presenter\PresenterInterface; use PhpSpec\Exception\Example\FailureException; class CallbackMatcher extends BasicMatcher { private $name; private $callback; private $presenter; public function __construct($name, $callback, PresenterInterface $presenter) { $this->name = $name; $this->callback = $callback; $this->presenter = $presenter; } public function supports($name, $subject, array $arguments) { return $name === $this->name; } protected function matches($subject, array $arguments) { array_unshift($arguments, $subject); return (Boolean) call_user_func_array($this->callback, $arguments); } protected function getFailureException($name, $subject, array $arguments) { return new FailureException(sprintf( '%s expected to %s(%s), but it is not.', $this->presenter->presentValue($subject), $this->presenter->presentString($name), implode(', ', array_map(array($this->presenter, 'presentValue'), $arguments)) )); } protected function getNegativeFailureException($name, $subject, array $arguments) { return new FailureException(sprintf( '%s not expected to %s(%s), but it is.', $this->presenter->presentValue($subject), $this->presenter->presentString($name), implode(', ', array_map(array($this->presenter, 'presentValue'), $arguments)) )); } }
<?php namespace PhpSpec\Matcher; use PhpSpec\Formatter\Presenter\PresenterInterface; use PhpSpec\Exception\Example\FailureException; class CallbackMatcher extends BasicMatcher { private $name; private $callback; private $presenter; public function __construct($name, $callback, PresenterInterface $presenter) { $this->name = $name; $this->callback = $callback; $this->presenter = $presenter; } public function supports($name, $subject, array $arguments) { return $name === $this->name; } protected function matches($subject, array $arguments) { array_unshift($arguments, $subject); return (Boolean) call_user_func_array($this->callback, $arguments); } protected function getFailureException($name, $subject, array $arguments) { return new FailureException(sprintf( '%s expected to %s, but it is not.', $this->presenter->presentValue($subject), $this->presenter->presentString($name) )); } protected function getNegativeFailureException($name, $subject, array $arguments) { return new FailureException(sprintf( '%s not expected to %s, but it is.', $this->presenter->presentValue($subject), $this->presenter->presentString($name) )); } }
Allow normaliseData to accept non-array values for the $data argument - means we can run the method on all data types, including objects, so if the method is overridden we don't have to convert them to arrays beforehand
<?php namespace Silktide\LazyBoy\Controller; use Symfony\Component\HttpFoundation\JsonResponse; /** * RestControllerTrait */ trait RestControllerTrait { private $prohibitedKeys = [ "password" => true, "salt" => true ]; protected function success($data = null, $code = 200) { if ($data === null) { $data = ["success" => true]; } else { $data = $this->normaliseData($data); } return new JsonResponse($data, $code); } protected function error($message, $data = [], $code = 400) { $payload = [ "success" => false, "error" => $message ]; if (!empty($data)) { $payload["context"] = $this->normaliseData($data); } return new JsonResponse($payload, $code); } protected function normaliseData($data) { if (is_array($data)) { foreach ($data as $key => $value) { if (isset($this->prohibitedKeys[$key])) { unset ($data[$key]); } else { $data[$key] = $this->normaliseData($value); } } } return $data; } }
<?php namespace Silktide\LazyBoy\Controller; use Symfony\Component\HttpFoundation\JsonResponse; /** * RestControllerTrait */ trait RestControllerTrait { private $prohibitedKeys = [ "password" => true, "salt" => true ]; protected function success($data = null, $code = 200) { if ($data === null) { $data = ["success" => true]; } elseif (is_array($data)) { $data = $this->normaliseData($data); } return new JsonResponse($data, $code); } protected function error($message, $data = [], $code = 400) { $payload = [ "success" => false, "error" => $message ]; if (!empty($data)) { $payload["context"] = $this->normaliseData($data); } return new JsonResponse($payload, $code); } protected function normaliseData($data) { foreach ($data as $key => $value) { if (isset($this->prohibitedKeys[$key])) { unset ($data[$key]); } elseif (is_array($value)) { $data[$key] = $this->normaliseData($value); } } return $data; } }
Fix mute on initial load
function demo($interval, demo) { return { restrict: 'E', template: '<div class=demo-container></div>', link: function(scope, element) { demo.setContainer(element[0].children[0]); setTimeout(function() { demo.resize(); }); scope.$watch(() => scope.main.fullscreen, function (toFullscreen){ if (toFullscreen) { // go to fullscreen document.body.classList.add('fullscreen'); } else { // exit fullscreen document.body.classList.remove('fullscreen'); } demo.resize(); }); scope.$watch(() => scope.main.mute, function (toMute) { if (toMute) { demo.music.setVolume(0); } else { demo.music.setVolume(scope.main.volume); } }); scope.$watch(() => scope.main.volume, volume => { if (scope.main.mute) return; demo.music.setVolume(volume); }); $interval(function() { scope.main.currentFrame = demo.getCurrentFrame(); scope.main.duration = demo.music.getDuration() * 60; }, 1000 / 60); setTimeout(function(){ demo.start(); demo.music.pause(); demo.jumpToFrame(0); }, 0); } }; } module.exports = demo;
function demo($interval, demo) { return { restrict: 'E', template: '<div class=demo-container></div>', link: function(scope, element) { demo.setContainer(element[0].children[0]); setTimeout(function() { demo.resize(); }); scope.$watch(() => scope.main.fullscreen, function (toFullscreen){ if (toFullscreen) { // go to fullscreen document.body.classList.add('fullscreen'); } else { // exit fullscreen document.body.classList.remove('fullscreen'); } demo.resize(); }); scope.$watch(() => scope.main.mute, function (toMute) { if (toMute) { demo.music.setVolume(0); } else { demo.music.setVolume(scope.main.volume); } }); scope.$watch(() => scope.main.volume, volume => { if (scope.mute) return; demo.music.setVolume(volume); }); $interval(function() { scope.main.currentFrame = demo.getCurrentFrame(); scope.main.duration = demo.music.getDuration() * 60; }, 1000 / 60); setTimeout(function(){ demo.start(); demo.music.pause(); demo.jumpToFrame(0); }, 0); } }; } module.exports = demo;
Clarify test_containers_to_host not using libnetwork
from subprocess import CalledProcessError from test_base import TestBase from tests.st.utils.docker_host import DockerHost class TestContainerToHost(TestBase): def test_container_to_host(self): """ Test that a container can ping the host. This function is important for Mesos, since the containerized executor needs to exchange messages with the Mesos Slave process on the host. Note also that we do not use the Docker Network driver for this test. The Docker Container Network Model defines a "network" as a group of endpoints that can communicate with each other, but are isolated from everything else. Thus, an endpoint of a Docker network should not be able to ping the host. """ with DockerHost('host', dind=False) as host: host.calicoctl("profile add TEST") # Use standard docker bridge networking. node1 = host.create_workload("node1") # Add the nodes to Calico networking. host.calicoctl("container add %s 192.168.100.1" % node1) # Get the endpoint IDs for the containers ep1 = host.calicoctl("container %s endpoint-id show" % node1) # Now add the profiles. host.calicoctl("endpoint %s profile set TEST" % ep1) # Check it works. Note that the profile allows all outgoing # traffic by default, and conntrack should allow the reply. node1.assert_can_ping(host.ip, retries=10)
from subprocess import CalledProcessError from test_base import TestBase from tests.st.utils.docker_host import DockerHost class TestContainerToHost(TestBase): def test_container_to_host(self): """ Test that a container can ping the host. (Without using the docker network driver, since it doesn't support that yet.) This function is important for Mesos, since the containerized executor needs to exchange messages with the Mesos Slave process on the host. """ with DockerHost('host', dind=False) as host: host.calicoctl("profile add TEST") # Use standard docker bridge networking. node1 = host.create_workload("node1") # Add the nodes to Calico networking. host.calicoctl("container add %s 192.168.100.1" % node1) # Get the endpoint IDs for the containers ep1 = host.calicoctl("container %s endpoint-id show" % node1) # Now add the profiles. host.calicoctl("endpoint %s profile set TEST" % ep1) # Check it works. Note that the profile allows all outgoing # traffic by default, and conntrack should allow the reply. node1.assert_can_ping(host.ip, retries=10) # Test the teardown commands host.calicoctl("profile remove TEST") host.calicoctl("container remove %s" % node1) host.calicoctl("pool remove 192.168.0.0/16") host.calicoctl("node stop")
Add random_challenge method to choose a challenge to answer
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import random from heartbeat import Challenge import requests from .utils import urlify from .exc import DownstreamError class DownstreamClient(object): def __init__(self, server_url): self.server = server_url.strip('/') self.challenges = [] def connect(self, url): raise NotImplementedError def store_path(self, path): raise NotImplementedError def get_chunk(self, hash): raise NotImplementedError def challenge(self, hash, challenge): raise NotImplementedError def answer(self, hash, hash_answer): raise NotImplementedError def _enc_fname(self, filename): return urlify(os.path.split(filename)[1]) def get_challenges(self, filename): enc_fname = urlify(os.path.split(filename)[1]) url = '%s/api/downstream/challenge/%s' % (self.server, enc_fname) resp = requests.get(url) try: resp.raise_for_status() except Exception as e: raise DownstreamError("Error connecting to downstream-node:", e.message) _json = resp.json() for challenge in _json['challenges']: chal = Challenge(challenge.get('block'), challenge.get('seed')) self.challenges.append(chal) def answer_challenge(self, filename): enc_fname = self._enc_fname(filename) raise NotImplementedError def random_challenge(self): random.choice(self.challenges)
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from heartbeat import Challenge import requests from .utils import urlify from .exc import DownstreamError class DownstreamClient(object): def __init__(self, server_url): self.server = server_url.strip('/') self.challenges = [] def connect(self, url): raise NotImplementedError def store_path(self, path): raise NotImplementedError def get_chunk(self, hash): raise NotImplementedError def challenge(self, hash, challenge): raise NotImplementedError def answer(self, hash, hash_answer): raise NotImplementedError def _enc_fname(self, filename): return urlify(os.path.split(filename)[1]) def get_challenges(self, filename): enc_fname = urlify(os.path.split(filename)[1]) url = '%s/api/downstream/challenge/%s' % (self.server, enc_fname) resp = requests.get(url) try: resp.raise_for_status() except Exception as e: raise DownstreamError("Error connecting to downstream-node:", e.message) _json = resp.json() for challenge in _json['challenges']: chal = Challenge(challenge.get('block'), challenge.get('seed')) self.challenges.append(chal) def answer_challenge(self, filename): enc_fname = self._enc_fname(filename) raise NotImplementedError
Fix Travis issue with Karma pt.2
// const webpack = require('webpack'); module.exports = (config) => { config.set({ browsers: ['Chrome'], // run in Chrome singleRun: true, // just run once by default frameworks: ['mocha', 'chai'], // use the mocha test framework files: [ 'tests.webpack.js', // just load this file ], preprocessors: { 'tests.webpack.js': ['webpack', 'sourcemap'], // preprocess with webpack and our sourcemap loader }, reporters: ['progress', 'coverage', 'coveralls'], webpack: { // kind of a copy of your webpack config devtool: 'inline-source-map', // just do inline source maps instead of the default module: { loaders: [ { test: /\.js$/, loader: 'babel-loader' }, ], }, }, coverageReporter: { check: { global: { statements: 11, branches: 0, functions: 0, lines: 11, }, }, reporters: [ { type: 'lcov', dir: 'coverage/', subdir: '.' }, { type: 'json', dir: 'coverage/', subdir: '.' }, { type: 'text-summary' }, ], }, webpackMiddleware: { noInfo: true }, colors: true, concurrency: Infinity, logLevel: config.LOG_DEBUG, }); };
// const webpack = require('webpack'); module.exports = (config) => { config.set({ browsers: process.env.TRAVIS ? ['Chrome_travis_ci'] : ['Chrome'], // run in Chrome singleRun: true, // just run once by default frameworks: ['mocha', 'chai'], // use the mocha test framework files: [ 'tests.webpack.js', // just load this file ], preprocessors: { 'tests.webpack.js': ['webpack', 'sourcemap'], // preprocess with webpack and our sourcemap loader }, reporters: ['progress', 'coverage', 'coveralls'], webpack: { // kind of a copy of your webpack config devtool: 'inline-source-map', // just do inline source maps instead of the default module: { loaders: [ { test: /\.js$/, loader: 'babel-loader' }, ], }, }, coverageReporter: { check: { global: { statements: 11, branches: 0, functions: 0, lines: 11, }, }, reporters: [ { type: 'lcov', dir: 'coverage/', subdir: '.' }, { type: 'json', dir: 'coverage/', subdir: '.' }, { type: 'text-summary' }, ], }, webpackMiddleware: { noInfo: true }, colors: true, concurrency: Infinity, logLevel: config.LOG_DEBUG, }); };
Update docstring for the ActiveHref template tag.
from django import template from bs4 import BeautifulSoup register = template.Library() @register.tag(name='activehref') def do_active_href(parser, token): nodelist = parser.parse(('endactivehref',)) parser.delete_first_token() return ActiveHref(nodelist) class ActiveHref(template.Node): """ This template tag will set an 'active' class attribute on any anchor with an href value that matches part of the current url path. Sample template usage: {% activehref %} <li><a href="{% url products %}">Products</a></li> <li><a href="{% url stores %}">Stores</a></li> <li><a href="{% url about %}">About</a></li> {% endactivehref %} """ def __init__(self, nodelist): self.nodelist = nodelist def render(self, context): soup = BeautifulSoup(self.nodelist.render(context)) if context.has_key('request'): path = context.get('request').path for a in soup.find_all('a'): href = a['href'] if href == '/': if path == href: a['class'] = 'active' break else: if href in path: a['class'] = 'active' break return soup
from django import template from bs4 import BeautifulSoup register = template.Library() @register.tag(name='activehref') def do_active_href(parser, token): nodelist = parser.parse(('endactivehref',)) parser.delete_first_token() return ActiveHref(nodelist) class ActiveHref(template.Node): """ This template tag will set an 'active' class attribute on any anchor with an href value that matches part of the current url path. """ def __init__(self, nodelist): self.nodelist = nodelist def render(self, context): soup = BeautifulSoup(self.nodelist.render(context)) if context.has_key('request'): path = context.get('request').path for a in soup.find_all('a'): href = a['href'] if href == '/': if path == href: a['class'] = 'active' break else: if href in path: a['class'] = 'active' break return soup
Fix for STORE-1330: Remove direct binding of `click` API to `on`
$(function () { $('.action-container').on( { mouseenter: function () { $(this).find("i").removeClass().addClass("fa fa-remove"); }, mouseleave: function () { $(this).find("i").removeClass().addClass("fa fa-star"); }, click: function () { var elem = $(this); asset.unsubscribeBookmark(elem.data('type'), elem.data('aid'), location.href, elem); } },'#btn-remove-subscribe').on( { click: function () { var elem = $(this); asset.process(elem.data('type'), elem.data('aid'), location.href, elem); } },'#btn-add-gadget'); $("a[data-toggle='tooltip']").tooltip(); $('.embed-snippet').hide(); $('.btn-embed').click(function () { $('.embed-snippet').toggle(400); return false; }); var el = $('.user-rating'), rating = el.data('rating'); $($('input', el)[rating - 1]).attr('checked', 'checked'); $('.auto-submit-star').rating({ callback: function (value, link) { if (value == undefined) { value = 0; } $('.rate-num-assert').html('(' + value + ')'); caramel.post('/apis/rate', { asset: $('#assetp-tabs').data('aid'), value: value || 0 }, function (data) { }); } }); });
$(function () { $('#btn-add-gadget').click(function () { var elem = $(this); asset.process(elem.data('type'), elem.data('aid'), location.href, elem); }); $('#btn-remove-subscribe').click(function () { var elem = $(this); asset.unsubscribeBookmark(elem.data('type'), elem.data('aid'), location.href, elem); }); $('#btn-remove-subscribe').hover( function () { $(this).find("i").removeClass().addClass("fa fa-remove"); }, function () { $(this).find("i").removeClass().addClass("fa fa-star"); }); $("a[data-toggle='tooltip']").tooltip(); $('.embed-snippet').hide(); $('.btn-embed').click(function () { $('.embed-snippet').toggle(400); return false; }); var el = $('.user-rating'), rating = el.data('rating'); $($('input', el)[rating - 1]).attr('checked', 'checked'); $('.auto-submit-star').rating({ callback: function (value, link) { if (value == undefined) { value = 0; } $('.rate-num-assert').html('(' + value + ')'); caramel.post('/apis/rate', { asset: $('#assetp-tabs').data('aid'), value: value || 0 }, function (data) { }); } }); });
Change the static mention of views cache path to the path on the configuration file
<?php namespace Fitztrev\LaravelHtmlMinify; use Illuminate\Support\ServiceProvider; use Illuminate\View\Engines\CompilerEngine; class LaravelHtmlMinifyServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { $this->package('fitztrev/laravel-html-minify'); } /** * Register the service provider. * * @return void */ public function register() { $app = $this->app; $app->view->getEngineResolver()->register( 'blade.php', function () use ($app) { $cachePath = storage_path() . '/views'; $compiler = new LaravelHtmlMinifyCompiler( $app->make('config')->get('laravel-html-minify::config'), $app['files'], $cachePath ); return new CompilerEngine($compiler); } ); $app->view->addExtension('blade.php', 'blade.php'); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array(); } }
<?php namespace Fitztrev\LaravelHtmlMinify; use Illuminate\Support\ServiceProvider; use Illuminate\View\Engines\CompilerEngine; class LaravelHtmlMinifyServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { $this->package('fitztrev/laravel-html-minify'); } /** * Register the service provider. * * @return void */ public function register() { $app = $this->app; $app->view->getEngineResolver()->register( 'blade.php', function () use ($app) { $cachePath = $app['path'].'/storage/views'; $compiler = new LaravelHtmlMinifyCompiler( $app->make('config')->get('laravel-html-minify::config'), $app['files'], $cachePath ); return new CompilerEngine($compiler); } ); $app->view->addExtension('blade.php', 'blade.php'); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array(); } }
Refactor to OOP ish design
/* * Refresh rendered file through mfr */ var $ = require('jquery'); var $osf = require('js/osfHelpers'); function FileRenderer(url, selector) { var self = this; self.url = url; self.tries = 0; self.selector = selector; self.ALLOWED_RETRIES = 10; self.element = $(selector); self.start = function() { self.getCachedFromServer(); }; self.reload = function() { self.tries = 0; self.start(); }; self.getCachedFromServer = function() { $.ajax({ method: 'GET', url: self.url, beforeSend: $osf.setXHRAuthorization }).done(function(data) { if (data) { self.element.html(data); } else { self.handleRetry(); } }).fail(self.handleRetry); }; self.handleRetry = $osf.throttle(function() { self.tries += 1; if(self.tries > self.ALLOWED_RETRIES){ self.element.html('Timeout occurred while loading, please refresh the page'); } else { self.getCachedFromServer(); } }, 1000); } module.exports = FileRenderer;
/* * Refresh rendered file through mfr */ 'use strict'; var $ = require('jquery'); var $osf = require('js/osfHelpers'); var FileRenderer = { start: function(url, selector){ this.url = url; this.tries = 0; this.ALLOWED_RETRIES = 10; this.element = $(selector); this.getCachedFromServer(); }, getCachedFromServer: function() { var self = this; $.ajax({ method: 'GET', url: self.url, beforeSend: $osf.setXHRAuthorization }).done(function(data) { if (data) { self.element.html(data.rendered); } else { self.handleRetry(); } }).fail(self.handleRetry); }, handleRetry: $osf.throttle(function() { var self = FileRenderer; self.tries += 1; if(self.tries > self.ALLOWED_RETRIES){ self.element.html('Timeout occurred while loading, please refresh the page'); } else { self.getCachedFromServer(); } }, 1000) }; module.exports = FileRenderer;
Add gyro reset for drift correction
package team498.robot.commands; import edu.wpi.first.wpilibj.command.Command; import team498.robot.Helpers; import team498.robot.Operator; import team498.robot.subsystems.Drivetrain; import team498.robot.subsystems.Gyro; public class Drive extends Command { private static final double CORRECTION_GAIN = 0.03; private Operator operator = Operator.getOperator(); private Drivetrain drivetrain; private Gyro gyro; public Drive() { super("Drive"); // Acquire control of subsystems requires(this.drivetrain = Drivetrain.getDrivetrain()); requires(this.gyro = Gyro.getGyro()); } protected void initialize() { gyro.resetAngle(); } protected void execute() { // Get move and rotate input values from the controller double move = operator.getRightTriggerAxis(); double rotate = operator.getLeftXAxis(); // Apply drift correction when going straight if(rotate == 0) { // Calculate how much correction is need to move straight rotate = Helpers.rotateToTarget(gyro.getAngle(), 0, 0, CORRECTION_GAIN); } else { gyro.resetAngle(); } // Drive robot drivetrain.drive(move, rotate); } protected void interrupted() { end(); } @Override protected boolean isFinished() { return false; } protected void end() { drivetrain.stop(); } }
package team498.robot.commands; import edu.wpi.first.wpilibj.command.Command; import team498.robot.Helpers; import team498.robot.Operator; import team498.robot.subsystems.Drivetrain; import team498.robot.subsystems.Gyro; public class Drive extends Command { private static final double CORRECTION_GAIN = 0.03; private Operator operator = Operator.getOperator(); private Drivetrain drivetrain; private Gyro gyro; public Drive() { super("Drive"); // Acquire control of subsystems requires(this.drivetrain = Drivetrain.getDrivetrain()); requires(this.gyro = Gyro.getGyro()); } protected void initialize() { gyro.resetAngle(); } protected void execute() { // Get move and rotate input values from the controller double move = operator.getRightTriggerAxis(); double rotate = operator.getLeftXAxis(); // Apply drift correction when going straight if(rotate == 0) { // Calculate how much correction is need to move straight rotate = Helpers.rotateToTarget(gyro.getAngle(), 0, 0, CORRECTION_GAIN); } // Drive robot drivetrain.drive(move, rotate); } protected void interrupted() { end(); } @Override protected boolean isFinished() { return false; } protected void end() { drivetrain.stop(); } }
Add missing "new" when raising an InvaludArgumentException
<?php class CSRF { /** @var string */ const HMAC_ALGORITHM = 'sha1'; /** @var string */ const SESSION_KEY_NAME = '_csrf_key'; /** * Ensure that a CSRF token is valid for a given action. * * @param string $token * @param string $action * @return bool */ public static function verify($token = '', $action = null) { if (!is_string($token) || !is_string($action)) { return false; } $known = self::generate($action); return hash_equals($known, $token); } /** * Generate a CSRF token for a given action. * * @param string $action * @throws InvalidArgumentException * @return string */ public static function generate($action = null) { if (!is_string($action)) { throw new InvalidArgumentException('A valid action must be defined.'); } return hash_hmac(self::HMAC_ALGORITHM, $action, self::getKey()); } /** * Get HMAC key. * * @return string */ public static function getKey() { if (empty($_SESSION[self::SESSION_KEY_NAME])) { $_SESSION[self::SESSION_KEY_NAME] = random_bytes(16); } return $_SESSION[self::SESSION_KEY_NAME]; } }
<?php class CSRF { /** @var string */ const HMAC_ALGORITHM = 'sha1'; /** @var string */ const SESSION_KEY_NAME = '_csrf_key'; /** * Ensure that a CSRF token is valid for a given action. * * @param string $token * @param string $action * @return bool */ public static function verify($token = '', $action = null) { if (!is_string($token) || !is_string($action)) { return false; } $known = self::generate($action); return hash_equals($known, $token); } /** * Generate a CSRF token for a given action. * * @param string $action * @throws InvalidArgumentException * @return string */ public static function generate($action = null) { if (!is_string($action)) { throw InvalidArgumentException('A valid action must be defined.'); } return hash_hmac(self::HMAC_ALGORITHM, $action, self::getKey()); } /** * Get HMAC key. * * @return string */ public static function getKey() { if (empty($_SESSION[self::SESSION_KEY_NAME])) { $_SESSION[self::SESSION_KEY_NAME] = random_bytes(16); } return $_SESSION[self::SESSION_KEY_NAME]; } }
Update list of HTML5 tags shived by html5shiv
module.exports = function(options){ var page = options.page; var next = options.next; page.evaluate( function () { var tags = [ 'abbr', 'article', 'aside', 'bdi', 'canvas', 'data', 'datalist', 'details', 'dialog', 'figcaption', 'figure', 'footer', 'header', 'hgroup', 'main', 'mark', 'meter', 'nav', 'output', 'picture', 'progress', 'section', 'summary', 'template', 'time', 'video' ]; var found = tags.filter(function(el){ return !!document.getElementsByTagName(el).length; }); return found; }, function (result) { if(result){ next(null, { problem: 'Your page contains the following unsupported HTML5 tags: ' + result.join(', '), solution: 'Try using https://github.com/aFarkas/html5shiv' }); } else { next(null, null); } } ); };
module.exports = function(options){ var page = options.page; var next = options.next; page.evaluate( function () { var tags = [ 'article', 'aside', 'bdi', 'details', 'dialog', 'figcaption', 'figure', 'footer', 'header', 'main', 'mark', 'menuitem', 'meter', 'nav', 'progress', 'rp', 'rt', 'ruby', 'section', 'summary', 'time', 'wbr', 'datalist', 'keygen', 'output', 'canvas', 'svg', 'audio', 'embed', 'source', 'track', 'video' ]; var found = tags.filter(function(el){ return !!document.getElementsByTagName(el).length; }); return found; }, function (result) { if(result){ next(null, { problem: 'Your page contains the following unsupported HTML5 tags: ' + result.join(', '), solution: 'Try using https://github.com/aFarkas/html5shiv' }); } else { next(null, null); } } ); };
Fix WeDo extension chip wording
const EXTENSION_INFO = { microbit: { name: 'micro:bit', icon: 'extension-microbit.svg', hasStatus: true }, music: { l10nId: 'project.musicExtensionChip', icon: 'extension-music.svg' }, pen: { l10nId: 'project.penExtensionChip', icon: 'extension-pen.svg' }, videoSensing: { l10nId: 'project.videoMotionChip', icon: 'extension-videosensing.svg' }, text2speech: { l10nId: 'project.text2SpeechChip', icon: 'extension-text2speech.svg' }, translate: { l10nId: 'project.translateChip', icon: 'extension-translate.svg' }, wedo2: { name: 'WeDo 2.0', icon: 'extension-wedo2.svg', hasStatus: true }, ev3: { name: 'LEGO MINDSTORMS EV3', icon: 'extension-ev3.svg', hasStatus: true }, makeymakey: { name: 'Makey Makey', icon: 'extension-makeymakey.svg' } }; export default EXTENSION_INFO;
const EXTENSION_INFO = { microbit: { name: 'micro:bit', icon: 'extension-microbit.svg', hasStatus: true }, music: { l10nId: 'project.musicExtensionChip', icon: 'extension-music.svg' }, pen: { l10nId: 'project.penExtensionChip', icon: 'extension-pen.svg' }, videoSensing: { l10nId: 'project.videoMotionChip', icon: 'extension-videosensing.svg' }, text2speech: { l10nId: 'project.text2SpeechChip', icon: 'extension-text2speech.svg' }, translate: { l10nId: 'project.translateChip', icon: 'extension-translate.svg' }, wedo2: { name: 'LEGO WeDo 2.0', icon: 'extension-wedo2.svg', hasStatus: true }, ev3: { name: 'LEGO MINDSTORMS EV3', icon: 'extension-ev3.svg', hasStatus: true }, makeymakey: { name: 'Makey Makey', icon: 'extension-makeymakey.svg' } }; export default EXTENSION_INFO;
Create a circle or square
function(args) { /* is_app(true) control_type("VB") display_name("Shapes control") description("This will return the shapes control") base_component_id("shapes_control") load_once_from_file(true) visibility("PRIVATE") read_only(true) properties( [ { id: "text", name: "Text", type: "String" } , { id: "background_color", name: "Background color", default: "blue", type: "String" } , { id: "shape", name: "Shape", type: "Select", default: "square", values: [ {display: "Square", square: ""}, {display: "Circle", value: "circle"} ] } ] )//properties logo_url("/driver_icons/shapes.png") */ Vue.component("shapes_control",{ props: ["args"] , template: `<div v-bind:style='"height:100%;width:100%; border: 0px;" + "background-color: "+ args["background_color"] + ";"'> </div>` , data: function() { return { msg: "..." } }, }) }
function(args) { /* is_app(true) control_type("VB") display_name("Shapes control") description("This will return the shapes control") base_component_id("shapes_control") load_once_from_file(true) visibility("PRIVATE") read_only(true) properties( [ { id: "text", name: "Text", type: "String" } , { id: "background_color", name: "Background color", type: "String" } ] )//properties logo_url("/driver_icons/shapes.png") */ Vue.component("shapes_control",{ props: ["args"] , template: `<div v-bind:style='"height:100%;width:100%; border: 0px;" + "background-color: "+ args["background_color"] + ";"'> {{args.text}} </div>` , data: function() { return { msg: "..." } }, }) }
Fix pagination when fetching submission lists
"use strict"; const fs = require("fs"); const path = require("path"); const builder = require("xmlbuilder"); const settings = require("../../../settings"); const SUBMISSIONS_DIR = path.join(settings.dataDir, "submissions"); module.exports = (req, res, next) => { const formPath = path.join(SUBMISSIONS_DIR, req.query.formId); return fs.access(formPath, err => { if (err) { return res.sendStatus(404); } return fs.readdir(formPath, (err, files) => { if (err) { return next(err); } const offset = req.query.cursor | 0; const count = (req.query.numEntries || 100) | 0; res.contentType("application/xml"); const xml = builder .begin( { writer: { pretty: true } }, chunk => res.write(chunk) ) .ele("idChunk") .att({ xmlns: "http://opendatakit.org/submissions" }) .ele("idList"); files .slice(offset, offset + count) .forEach(uuid => xml.ele("id", `uuid:${uuid}`).up()); let resumptionCursor = req.query.cursor || null; if (files.length > offset + count) { resumptionCursor = offset + count; } xml.up().ele("resumptionCursor", resumptionCursor); return res.send(xml.end()); }); }); };
"use strict"; const fs = require("fs"); const path = require("path"); const builder = require("xmlbuilder"); const settings = require("../../../settings"); const SUBMISSIONS_DIR = path.join(settings.dataDir, "submissions"); module.exports = (req, res, next) => { const formPath = path.join(SUBMISSIONS_DIR, req.query.formId); return fs.access(formPath, err => { if (err) { return res.sendStatus(404); } return fs.readdir(formPath, (err, files) => { if (err) { return next(err); } const offset = req.query.cursor | 0; const count = (req.query.numEntries || 100) | 0; res.contentType("application/xml"); const xml = builder .begin( { writer: { pretty: true } }, chunk => res.write(chunk) ) .ele("idChunk") .att({ xmlns: "http://opendatakit.org/submissions" }) .ele("idList"); files .slice(offset, count) .forEach(uuid => xml.ele("id", `uuid:${uuid}`).up()); let resumptionCursor = req.query.cursor || null; if (files.length > offset + count) { resumptionCursor = offset + count; } xml.up().ele("resumptionCursor", resumptionCursor); return res.send(xml.end()); }); }); };
Fix SMS ES test after not-and rewrite
from django.test.testcases import SimpleTestCase from corehq.apps.es.sms import SMSES from corehq.apps.es.tests.utils import ElasticTestMixin from corehq.elastic import SIZE_LIMIT class TestSMSES(ElasticTestMixin, SimpleTestCase): def test_processed_or_incoming(self): json_output = { "query": { "filtered": { "filter": { "and": [ {"term": {"domain.exact": "demo"}}, { "or": ( { "not": {"term": {"direction": "o"}}, }, { "not": {"term": {"processed": False}}, } ), }, {"match_all": {}}, ] }, "query": {"match_all": {}} } }, "size": SIZE_LIMIT } query = SMSES().domain('demo').processed_or_incoming_messages() self.checkQuery(query, json_output)
from django.test.testcases import SimpleTestCase from corehq.apps.es.sms import SMSES from corehq.apps.es.tests.utils import ElasticTestMixin from corehq.elastic import SIZE_LIMIT class TestSMSES(ElasticTestMixin, SimpleTestCase): def test_processed_or_incoming(self): json_output = { "query": { "filtered": { "filter": { "and": [ {"term": {"domain.exact": "demo"}}, { "not": { "and": ( {"term": {"direction": "o"}}, {"term": {"processed": False}}, ) } }, {"match_all": {}}, ] }, "query": {"match_all": {}} } }, "size": SIZE_LIMIT } query = SMSES().domain('demo').processed_or_incoming_messages() self.checkQuery(query, json_output)
Add class comment for kafkaTransportDetails class
package org.wso2.carbon.sp.jobmanager.core.bean; import java.util.List; /** * Bean class for kafkaTransport Details. */ public class KafkaTransportDetails { private String appName; private String siddhiApp; private String deployedHost; private String deployedPort; private List<String> sourceList; private List<String> sinkList; public String getAppName() { return appName; } public void setAppName(String appName) { this.appName = appName; } public String getSiddhiApp() { return siddhiApp; } public void setSiddhiApp(String siddhiApp) { this.siddhiApp = siddhiApp; } public List<String> getSourceList() { return sourceList; } public void setSourceList(List<String> sourceList) { this.sourceList = sourceList; } public List<String> getSinkList() { return sinkList; } public void setSinkList(List<String> sinkList) { this.sinkList = sinkList; } public String getDeployedHost() { return deployedHost; } public void setDeployedHost(String deployedHost) { this.deployedHost = deployedHost; } public String getDeployedPort() { return deployedPort; } public void setDeployedPort(String deployedPort) { this.deployedPort = deployedPort; } }
package org.wso2.carbon.sp.jobmanager.core.bean; import java.util.List; /** * */ public class KafkaTransportDetails { private String appName; private String siddhiApp; private String deployedHost; private String deployedPort; private List<String> sourceList; private List<String> sinkList; public String getAppName() { return appName; } public void setAppName(String appName) { this.appName = appName; } public String getSiddhiApp() { return siddhiApp; } public void setSiddhiApp(String siddhiApp) { this.siddhiApp = siddhiApp; } public List<String> getSourceList() { return sourceList; } public void setSourceList(List<String> sourceList) { this.sourceList = sourceList; } public List<String> getSinkList() { return sinkList; } public void setSinkList(List<String> sinkList) { this.sinkList = sinkList; } public String getDeployedHost() { return deployedHost; } public void setDeployedHost(String deployedHost) { this.deployedHost = deployedHost; } public String getDeployedPort() { return deployedPort; } public void setDeployedPort(String deployedPort) { this.deployedPort = deployedPort; } }
Fix test to pass also with Firefox 13
function runTest() { FBTest.sysout("issue5525.START"); FBTest.openNewTab(basePath + "script/breakpoints/5525/issue5525.html", function(win) { FBTest.openFirebug(); FBTest.enableScriptPanel() FBTest.enableConsolePanel() FBTest.selectPanel("console"); var config = {tagName: "div", classes: "logRow logRow-errorMessage"}; FBTest.waitForDisplayedElement("console", config, function(row) { // Verify displayed text. var reTextContent = /\s*undefinedVariable is not defined\s*var test = undefinedVariable;\s*issue5525.html\s*\(line 10\)/; FBTest.compare(reTextContent, row.textContent, "Text content must match."); // Create error breakpoint var br = row.getElementsByClassName("errorBreak")[0]; FBTest.click(br); // Switch to the Script and Breakpoints panels. FBTest.selectPanel("script"); var panel = FBTest.selectSidePanel("breakpoints"); // Check content of the Breakpoints panel var panelNode = panel.panelNode; var rows = panelNode.getElementsByClassName("breakpointRow"); FBTest.compare(rows.length, 1, "There must be one breakpoint"); // Finish test FBTest.testDone("console.error.DONE"); }); FBTest.reload(); }); }
function runTest() { FBTest.sysout("issue5525.START"); FBTest.openNewTab(basePath + "script/breakpoints/5525/issue5525.html", function(win) { FBTest.openFirebug(); FBTest.enableScriptPanel() FBTest.enableConsolePanel() FBTest.selectPanel("console"); var config = {tagName: "div", classes: "logRow logRow-errorMessage"}; FBTest.waitForDisplayedElement("console", config, function(row) { // Verify displayed text. var reTextContent = /ReferenceError\:\s*undefinedVariable is not defined\s*var test = undefinedVariable;\s*issue5525.html\s*\(line 10\)/; FBTest.compare(reTextContent, row.textContent, "Text content must match."); // Create error breakpoint var br = row.getElementsByClassName("errorBreak")[0]; FBTest.click(br); // Switch to the Script and Breakpoints panels. FBTest.selectPanel("script"); var panel = FBTest.selectSidePanel("breakpoints"); // Check content of the Breakpoints panel var panelNode = panel.panelNode; var rows = panelNode.getElementsByClassName("breakpointRow"); FBTest.compare(rows.length, 1, "There must be one breakpoint"); // Finish test FBTest.testDone("console.error.DONE"); }); FBTest.reload(); }); }
Reduce white-space to trim down filesize
--- layout: null --- var store = [ {%- for c in site.collections -%} {%- if forloop.last -%} {%- assign l = true -%} {%- endif -%} {%- assign docs = c.docs | where_exp:'doc','doc.search != false' -%} {%- for doc in docs -%} {%- if doc.header.teaser -%} {%- capture teaser -%}{{ doc.header.teaser }}{%- endcapture -%} {%- else -%} {%- assign teaser = site.teaser -%} {%- endif -%} { "title": {{ doc.title | jsonify }}, "excerpt": {%- if site.search_full_content == true -%} {{ doc.content | strip_html | strip_newlines | jsonify }}, {%- else -%} {{ doc.content | strip_html | strip_newlines | truncatewords: 50 | jsonify }}, {%- endif -%} "categories": {{ doc.categories | jsonify }}, "tags": {{ doc.tags | jsonify }}, "url": {{ doc.url | absolute_url | jsonify }}, "teaser": {%- if teaser contains "://" -%} {{ teaser | jsonify }} {%- else -%} {{ teaser | absolute_url | jsonify }} {%- endif -%} }{%- unless forloop.last and l -%},{%- endunless -%} {%- endfor -%} {%- endfor -%}]
--- layout: null --- var store = [ {% for c in site.collections %} {% if forloop.last %} {% assign l = true %} {% endif %} {% assign docs = c.docs | where_exp:'doc','doc.search != false' %} {% for doc in docs %} {% if doc.header.teaser %} {% capture teaser %}{{ doc.header.teaser }}{% endcapture %} {% else %} {% assign teaser = site.teaser %} {% endif %} { "title": {{ doc.title | jsonify }}, "excerpt": {% if site.search_full_content == true %} {{ doc.content | strip_html | strip_newlines | jsonify }}, {% else %} {{ doc.content | strip_html | strip_newlines | truncatewords: 50 | jsonify }}, {% endif %} "categories": {{ doc.categories | jsonify }}, "tags": {{ doc.tags | jsonify }}, "url": {{ doc.url | absolute_url | jsonify }}, "teaser": {% if teaser contains "://" %} {{ teaser | jsonify }} {% else %} {{ teaser | absolute_url | jsonify }} {% endif %} }{% unless forloop.last and l %},{% endunless %} {% endfor %} {% endfor %}]
Change join button colour to blue.
import '../css/ListItem.css'; import React, { Component, PropTypes } from 'react'; import Button from './Button'; export default class ListItem extends Component { render() { const { id, title, right, peopleNames, outingJoined, onClickJoin, onClickLeave } = this.props; const people = peopleNames ? peopleNames.map(function(name, index) { return <li key={index} className="c-list__item">{name}</li>; }) : ''; return ( <div className="c-card c-card--accordion u-high"> <input type="checkbox" id={id} /> <label className="c-card__item" htmlFor={id}> {title} {outingJoined ? <Button customClasses="outing-leave-button" xsm="true" title="LEAVE" error="true" onClick={onClickLeave}/> : <Button customClasses="outing-join-button" xsm="true" title="JOIN" info="true" onClick={onClickJoin}/> } </label> <div className="c-card__item"> <ul className="c-list c-list--unstyled"> {people} </ul> </div> </div> ); } }; ListItem.prototypes = { id: PropTypes.string, title: PropTypes.string, right: PropTypes.bool, peopleNames: PropTypes.object, outingJoined: PropTypes.bool, onClickJoin: PropTypes.function, onClickLeave: PropTypes.function };
import '../css/ListItem.css'; import React, { Component, PropTypes } from 'react'; import Button from './Button'; export default class ListItem extends Component { render() { const { id, title, right, peopleNames, outingJoined, onClickJoin, onClickLeave } = this.props; const people = peopleNames ? peopleNames.map(function(name, index) { return <li key={index} className="c-list__item">{name}</li>; }) : ''; return ( <div className="c-card c-card--accordion u-high"> <input type="checkbox" id={id} /> <label className="c-card__item" htmlFor={id}> {title} {outingJoined ? <Button customClasses="outing-leave-button" xsm="true" title="LEAVE" error="true" onClick={onClickLeave}/> : <Button customClasses="outing-join-button" xsm="true" title="JOIN" success="true" onClick={onClickJoin}/> } </label> <div className="c-card__item"> <ul className="c-list c-list--unstyled"> {people} </ul> </div> </div> ); } }; ListItem.prototypes = { id: PropTypes.string, title: PropTypes.string, right: PropTypes.bool, peopleNames: PropTypes.object, outingJoined: PropTypes.bool, onClickJoin: PropTypes.function, onClickLeave: PropTypes.function };
Fix for missing username and clear the social_auth to force re-authentication at next login.
# -*- coding: utf-8 -*- import logging #import datetime from celery import task from django.contrib.auth import get_user_model LOGGER = logging.getLogger(__name__) User = get_user_model() #ftstamp = datetime.datetime.fromtimestamp #now = datetime.datetime.now @task def celery_beat_test(): LOGGER.info(u'testing celery beat scheduler…') @task def refresh_access_tokens(): """ Refresh all access_tokens in turn to avoid hitting http://dev.1flow.net/webapps/1flow/group/664/ """ users = User.objects.all() #count = users.count() #sleep_time = 1500 / count for user in users: # See http://django-social-auth.readthedocs.org/en/latest/use_cases.html#token-refreshing # NOQA #LOGGER.warning(u'Refreshing invalid access_token for user %s.', # user.username) social_accounts = user.social_auth.filter(provider='google-oauth2') if social_accounts.count() == 0: continue for social in social_accounts: try: social.refresh_token() except: LOGGER.error(u'Access token could not be refreshed for user ' u'%s, forcing re-authentication at next login.', user.username) social.delete()
# -*- coding: utf-8 -*- import logging #import datetime from celery import task from django.contrib.auth import get_user_model LOGGER = logging.getLogger(__name__) User = get_user_model() #ftstamp = datetime.datetime.fromtimestamp #now = datetime.datetime.now @task def celery_beat_test(): LOGGER.info(u'testing celery beat scheduler…') @task def refresh_access_tokens(): """ Refresh all access_tokens in turn to avoid hitting http://dev.1flow.net/webapps/1flow/group/664/ """ users = User.objects.all() #count = users.count() #sleep_time = 1500 / count for user in users: # See http://django-social-auth.readthedocs.org/en/latest/use_cases.html#token-refreshing # NOQA #LOGGER.warning(u'Refreshing invalid access_token for user %s.', # user.username) social_accounts = user.social_auth.filter(provider='google-oauth2') if social_accounts.count() == 0: continue for social in social_accounts: try: social.refresh_token() except: LOGGER.error(u'Access token could not be refreshed for user ' u'%s, forcing re-authentication at next login.') # TODO: force re-auth of user at next visit.
Check csrf token before restoring a deleted user
<?php namespace Backend\Modules\Users\Actions; use Backend\Core\Engine\Base\Action as BackendBaseAction; use Backend\Core\Engine\Model as BackendModel; use Backend\Core\Engine\User as BackendUser; use Backend\Modules\Users\Engine\Model as BackendUsersModel; /** * This is the undo-delete-action, it will restore a deleted user */ class UndoDelete extends BackendBaseAction { public function execute(): void { $this->checkToken(); $email = $this->getRequest()->query->get('email', ''); // does the user exist if ($email !== '') { parent::execute(); // delete item if (BackendUsersModel::undoDelete($email)) { // get user $user = new BackendUser(null, $email); // item was deleted, so redirect $this->redirect( BackendModel::createUrlForAction('edit') . '&id=' . $user->getUserId( ) . '&report=restored&var=' . $user->getSetting('nickname') . '&highlight=row-' . $user->getUserId() ); } else { // invalid user $this->redirect(BackendModel::createUrlForAction('index') . '&error=non-existing'); } } else { $this->redirect(BackendModel::createUrlForAction('index') . '&error=non-existing'); } } }
<?php namespace Backend\Modules\Users\Actions; use Backend\Core\Engine\Base\Action as BackendBaseAction; use Backend\Core\Engine\Model as BackendModel; use Backend\Core\Engine\User as BackendUser; use Backend\Modules\Users\Engine\Model as BackendUsersModel; /** * This is the undo-delete-action, it will restore a deleted user */ class UndoDelete extends BackendBaseAction { public function execute(): void { $email = $this->getRequest()->query->get('email', ''); // does the user exist if ($email !== '') { parent::execute(); // delete item if (BackendUsersModel::undoDelete($email)) { // get user $user = new BackendUser(null, $email); // item was deleted, so redirect $this->redirect( BackendModel::createUrlForAction('edit') . '&id=' . $user->getUserId( ) . '&report=restored&var=' . $user->getSetting('nickname') . '&highlight=row-' . $user->getUserId() ); } else { // invalid user $this->redirect(BackendModel::createUrlForAction('index') . '&error=non-existing'); } } else { $this->redirect(BackendModel::createUrlForAction('index') . '&error=non-existing'); } } }
Fix refresh session on navigate
<?php class Session { const SESSION_STARTED = TRUE; const SESSION_STOPED = FALSE; private $sessionStatus = self::SESSION_STOPED; private static $instance; private function __construct() {} public static function getInstance() { if (!isset(self::$instance)) { self::$instance = new self; } self::$instance->startSession(); return self::$instance; } public function startSession() { $this->sessionStatus = session_start(); return $this->sessionStatus; } public function __set( $name , $value ) { $_SESSION[$name] = $value; } public function __get( $name ) { if(isset($_SESSION[$name])) { return $_SESSION[$name]; } } public function __isset($name) { return isset($_SESSION[$name]); } public function __unset($name) { unset($_SESSION[$name]); } public function destroy() { if($this->sessionStatus == self::SESSION_STARTED) { $this->sessionStatus = session_destroy(); unset($_SESSION); return $this->sessionStatus; } return FALSE; } public function restart() { if(self::$instance->destroy()) { self::$instance->startSession(); } } public function reset() { session_reset(); } } ?>
<?php class Session { const SESSION_STARTED = TRUE; const SESSION_STOPED = FALSE; private $sessionStatus = self::SESSION_STOPED; private static $instance; private function __construct() {} public static function getInstance() { if (!isset(self::$instance)) { self::$instance = new self; } self::$instance->startSession(); return self::$instance; } public function startSession() { if($this->sessionStatus == self::SESSION_STOPED) { $this->sessionStatus = session_start(); } return $this->sessionStatus; } public function __set( $name , $value ) { $_SESSION[$name] = $value; } public function __get( $name ) { if(isset($_SESSION[$name])) { return $_SESSION[$name]; } } public function __isset($name) { return isset($_SESSION[$name]); } public function __unset($name) { unset($_SESSION[$name]); } public function destroy() { if($this->sessionStatus == self::SESSION_STARTED) { $this->sessionStatus = session_destroy(); unset($_SESSION); return $this->sessionStatus; } return FALSE; } public function restart() { if(self::$instance->destroy()) { self::$instance->startSession(); } } public function reset() { session_reset(); } } ?>
Fix of dummymovement form to use product.move instead of api.move
from __future__ import unicode_literals from django.core.urlresolvers import reverse_lazy from django.views.generic import FormView from braces.views import LoginRequiredMixin from ..mixins import BazaarPrefixMixin from . import api from .forms import MovementForm class MovementMixin(LoginRequiredMixin, BazaarPrefixMixin): def get_success_url(self): if "next" in self.request.GET: return self.request.GET.get("next") else: return super(MovementMixin, self).get_success_url() def get_initial(self): initial = super(MovementMixin, self).get_initial() product = self.request.GET.get("product") if product: initial["product"] = product return initial class MovementFormView(MovementMixin, FormView): form_class = MovementForm template_name = "warehouse/movement.html" success_url = reverse_lazy("bazaar:movement") def form_valid(self, form): product = form.cleaned_data["product"] from_location = form.cleaned_data["from_location"] to_location = form.cleaned_data["to_location"] quantity = form.cleaned_data["quantity"] unit_price = form.cleaned_data["unit_price"] note = form.cleaned_data["note"] price_multiplier = unit_price / product.price product.move(from_location, to_location, quantity=quantity, price_multiplier=price_multiplier, agent=self.request.user, note=note) return super(MovementFormView, self).form_valid(form)
from __future__ import unicode_literals from django.core.urlresolvers import reverse_lazy from django.views.generic import FormView from braces.views import LoginRequiredMixin from ..mixins import BazaarPrefixMixin from . import api from .forms import MovementForm class MovementMixin(LoginRequiredMixin, BazaarPrefixMixin): def get_success_url(self): if "next" in self.request.GET: return self.request.GET.get("next") else: return super(MovementMixin, self).get_success_url() def get_initial(self): initial = super(MovementMixin, self).get_initial() product = self.request.GET.get("product") if product: initial["product"] = product return initial class MovementFormView(MovementMixin, FormView): form_class = MovementForm template_name = "warehouse/movement.html" success_url = reverse_lazy("bazaar:movement") def form_valid(self, form): product = form.cleaned_data["product"] from_location = form.cleaned_data["from_location"] to_location = form.cleaned_data["to_location"] quantity = form.cleaned_data["quantity"] unit_price = form.cleaned_data["unit_price"] note = form.cleaned_data["note"] api.move(from_location, to_location, product, quantity, unit_price, agent=self.request.user, note=note) return super(MovementFormView, self).form_valid(form)
Clean out the _key from the data, no need to double entry
''' Create a stock database with a built in nesting key index ''' # Import maras libs import maras.database import maras.tree_index # We can likely build these out as mixins, making it easy to apply high level # constructs to multiple unerlying database implimentations class NestDB(maras.database.Database): ''' Create a high level database which translates entry keys into a higherarcical dict like structure ''' def __init__(self, path): maras.database.Database.__init__(self, path) self.__init_db() def __init_db(self): ''' Init the db, open it if it already exists, otherwise create it ''' try: self.open() except maras.database.DatabasePathException: self.create() def new_index(self, name): ''' Add a new named index ''' new = NestIndex(self.path, name) self.add_index(new) class NestIndex(maras.tree_index.TreeBasedIndex): ''' The index to manage higherarcical keys ''' def __init__(self, *args, **kwargs): kwargs['node_capacity'] = kwargs.get('node_capacity', 1000) maras.tree_index.TreeBasedIndex.__init__(self, *args, **kwargs) def make_key_value(self, data): if '_key' in data: return data.pop('_key') return 'None' def make_key(self, key): return key
''' Create a stock database with a built in nesting key index ''' # Import maras libs import maras.database import maras.tree_index # We can likely build these out as mixins, making it easy to apply high level # constructs to multiple unerlying database implimentations class NestDB(maras.database.Database): ''' Create a high level database which translates entry keys into a higherarcical dict like structure ''' def __init__(self, path): maras.database.Database.__init__(self, path) self.__init_db() def __init_db(self): ''' Init the db, open it if it already exists, otherwise create it ''' try: self.open() except maras.database.DatabasePathException: self.create() def new_index(self, name): ''' Add a new named index ''' new = NestIndex(self.path, name) self.add_index(new) class NestIndex(maras.tree_index.TreeBasedIndex): ''' The index to manage higherarcical keys ''' def __init__(self, *args, **kwargs): kwargs['node_capacity'] = kwargs.get('node_capacity', 1000) maras.tree_index.TreeBasedIndex.__init__(self, *args, **kwargs) def make_key_value(self, data): return data.get('_key', 'None') def make_key(self, key): return key
Fix kwargs usage to work with other auth backends.
from django.contrib.auth.backends import ModelBackend from django.contrib.auth.models import User from django.contrib.auth.tokens import default_token_generator from django.db.models import Q from django.utils.http import base36_to_int class MezzanineBackend(ModelBackend): """ Extends Django's ``ModelBackend`` to allow login via username, email, or verification token. Args are either ``username`` and ``password``, or ``uidb36`` and ``token``. In either case, ``is_active`` can also be given. For login, is_active is not given, so that the login form can raise a specific error for inactive users. For password reset, True is given for is_active. For signup verficiation, False is given for is_active. """ def authenticate(self, **kwargs): if kwargs: username = kwargs.pop("username", None) if username: username_or_email = Q(username=username) | Q(email=username) password = kwargs.pop("password") try: user = User.objects.get(username_or_email, **kwargs) except User.DoesNotExist: pass else: if user.check_password(password): return user else: if 'uidb36' not in kwargs: return kwargs["id"] = base36_to_int(kwargs.pop("uidb36")) token = kwargs.pop("token") try: user = User.objects.get(**kwargs) except User.DoesNotExist: pass else: if default_token_generator.check_token(user, token): return user
from django.contrib.auth.backends import ModelBackend from django.contrib.auth.models import User from django.contrib.auth.tokens import default_token_generator from django.db.models import Q from django.utils.http import base36_to_int class MezzanineBackend(ModelBackend): """ Extends Django's ``ModelBackend`` to allow login via username, email, or verification token. Args are either ``username`` and ``password``, or ``uidb36`` and ``token``. In either case, ``is_active`` can also be given. For login, is_active is not given, so that the login form can raise a specific error for inactive users. For password reset, True is given for is_active. For signup verficiation, False is given for is_active. """ def authenticate(self, **kwargs): if kwargs: username = kwargs.pop("username", None) if username: username_or_email = Q(username=username) | Q(email=username) password = kwargs.pop("password") try: user = User.objects.get(username_or_email, **kwargs) except User.DoesNotExist: pass else: if user.check_password(password): return user else: kwargs["id"] = base36_to_int(kwargs.pop("uidb36")) token = kwargs.pop("token") try: user = User.objects.get(**kwargs) except User.DoesNotExist: pass else: if default_token_generator.check_token(user, token): return user
Upgrade ldap3 1.0.2 => 1.0.3
import sys from setuptools import find_packages, setup VERSION = '2.0.dev0' install_requires = [ 'django-local-settings>=1.0a10', 'stashward', ] if sys.version_info[:2] < (3, 4): install_requires.append('enum34') setup( name='django-arcutils', version=VERSION, url='https://github.com/PSU-OIT-ARC/django-arcutils', author='PSU - OIT - ARC', author_email='[email protected]', description='Common utilities used in ARC Django projects', packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=install_requires, extras_require={ 'cas': [ 'django-cas-client>=1.2.0', ], 'ldap': [ 'certifi>=2015.11.20.1', 'ldap3>=1.0.3', ], 'dev': [ 'django>=1.7,<1.9', 'flake8', 'ldap3', 'mock', 'model_mommy', ], }, entry_points=""" [console_scripts] arcutils = arcutils.__main__:main """, classifiers=[ 'Development Status :: 3 - Alpha', 'Framework :: Django', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], )
import sys from setuptools import find_packages, setup VERSION = '2.0.dev0' install_requires = [ 'django-local-settings>=1.0a10', 'stashward', ] if sys.version_info[:2] < (3, 4): install_requires.append('enum34') setup( name='django-arcutils', version=VERSION, url='https://github.com/PSU-OIT-ARC/django-arcutils', author='PSU - OIT - ARC', author_email='[email protected]', description='Common utilities used in ARC Django projects', packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=install_requires, extras_require={ 'cas': [ 'django-cas-client>=1.2.0', ], 'ldap': [ 'certifi>=2015.11.20.1', 'ldap3>=1.0.2', ], 'dev': [ 'django>=1.7,<1.9', 'flake8', 'ldap3', 'mock', 'model_mommy', ], }, entry_points=""" [console_scripts] arcutils = arcutils.__main__:main """, classifiers=[ 'Development Status :: 3 - Alpha', 'Framework :: Django', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], )
Change requirement dateutil to python-dateutil.
#!/usr/bin/env python from setuptools import setup, find_packages setup( name = "py-trello", version = "0.2.3", description = 'Python wrapper around the Trello API', long_description = open('README.rst').read(), author = 'Richard Kolkovich', author_email = '[email protected]', url = 'https://trello.com/board/py-trello/4f145d87b2f9f15d6d027b53', keywords = 'python', license = 'BSD License', classifiers = [ "Development Status :: 4 - Beta", 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python 2', 'Programming Language :: Python 2.7', 'Programming Language :: Python 3', 'Programming Language :: Python 3.3', ], install_requires = ["requests", "requests-oauthlib >= 0.4.1", "python-dateutil"], packages = find_packages(), include_package_data = True, ) # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
#!/usr/bin/env python from setuptools import setup, find_packages setup( name = "py-trello", version = "0.2.3", description = 'Python wrapper around the Trello API', long_description = open('README.rst').read(), author = 'Richard Kolkovich', author_email = '[email protected]', url = 'https://trello.com/board/py-trello/4f145d87b2f9f15d6d027b53', keywords = 'python', license = 'BSD License', classifiers = [ "Development Status :: 4 - Beta", 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python 2', 'Programming Language :: Python 2.7', 'Programming Language :: Python 3', 'Programming Language :: Python 3.3', ], install_requires = ["requests", "requests-oauthlib >= 0.4.1", "dateutil"], packages = find_packages(), include_package_data = True, ) # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
Fix error on words beginning with '-'
import re from abc import abstractmethod from denite_gtags import GtagsBase # pylint: disable=locally-disabled, wrong-import-position class TagsBase(GtagsBase): TAG_PATTERN = re.compile('([^\t]+)\t(\\d+)\t(.*)') @abstractmethod def get_search_flags(self): return [] def get_search_word(self, context): args_count = len(context['args']) if args_count > 0: return context['args'][0] return context['input'] def gather_candidates(self, context): word = self.get_search_word(context) tags = self.exec_global(self.get_search_flags() + ['--', word], context) candidates = self._convert_to_candidates(tags) return candidates @classmethod def _convert_to_candidates(cls, tags): candidates = [] for tag in tags: path, line, text = cls._parse_tag(tag) col = text.find(text) -1 candidates.append({ 'word': tag, 'action__path': path, 'action__line': line, 'action__text': text, 'action__col': col }) return candidates @classmethod def _parse_tag(cls, tag): match = cls.TAG_PATTERN.match(tag) return match.groups()
import re from abc import abstractmethod from denite_gtags import GtagsBase # pylint: disable=locally-disabled, wrong-import-position class TagsBase(GtagsBase): TAG_PATTERN = re.compile('([^\t]+)\t(\\d+)\t(.*)') def __init__(self, vim): super().__init__(vim) @abstractmethod def get_search_flags(self): return [] def get_search_word(self, context): if len(context['args']) > 0: return context['args'][0] return context['input'] def gather_candidates(self, context): word = self.get_search_word(context) tags = self.exec_global(self.get_search_flags() + [word], context) candidates = self._convert_to_candidates(tags) return candidates @classmethod def _convert_to_candidates(cls, tags): candidates = [] for tag in tags: path, line, text = cls._parse_tag(tag) col = text.find(text) -1 candidates.append({ 'word': tag, 'action__path': path, 'action__line': line, 'action__text': text, 'action__col': col }) return candidates @classmethod def _parse_tag(cls, tag): match = cls.TAG_PATTERN.match(tag) return match.groups()
Set name explicitly in the command itself, too
<?php namespace Becklyn\AssetsBundle\Command; use Becklyn\AssetsBundle\Cache\CacheWarmer; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; class AssetsCacheCommand extends Command { public static $defaultName = "becklyn:assets:reset"; /** * @var CacheWarmer */ private $cacheWarmer; /** * @param CacheWarmer $cacheWarmer */ public function __construct (CacheWarmer $cacheWarmer) { $this->cacheWarmer = $cacheWarmer; parent::__construct(); } /** * @inheritdoc */ protected function configure () { $this ->setName(self::$defaultName) ->setDescription("Resets (clears and warms) the assets cache") ->addOption( "no-warmup", null, InputOption::VALUE_OPTIONAL, "Should be cache be automatically warmed up?", false ); } /** * @inheritdoc */ protected function execute (InputInterface $input, OutputInterface $output) { $io = new SymfonyStyle($input, $output); $io->title("Becklyn Assets: Reset"); $this->cacheWarmer->clearCache($io); if (!$input->getOption("no-warmup")) { $this->cacheWarmer->fillCache($io); } $io->success("finished"); } }
<?php namespace Becklyn\AssetsBundle\Command; use Becklyn\AssetsBundle\Cache\CacheWarmer; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; class AssetsCacheCommand extends Command { /** * @var CacheWarmer */ private $cacheWarmer; /** * @param CacheWarmer $cacheWarmer */ public function __construct (CacheWarmer $cacheWarmer) { $this->cacheWarmer = $cacheWarmer; parent::__construct(); } /** * @inheritdoc */ protected function configure () { $this ->setDescription("Resets (clears and warms) the assets cache") ->addOption( "no-warmup", null, InputOption::VALUE_OPTIONAL, "Should be cache be automatically warmed up?", false ); } /** * @inheritdoc */ protected function execute (InputInterface $input, OutputInterface $output) { $io = new SymfonyStyle($input, $output); $io->title("Becklyn Assets: Reset"); $this->cacheWarmer->clearCache($io); if (!$input->getOption("no-warmup")) { $this->cacheWarmer->fillCache($io); } $io->success("finished"); } }
Correct some issues with the stats methods
from django.template.defaultfilters import slugify from debug_toolbar.middleware import DebugToolbarMiddleware class DebugPanel(object): """ Base class for debug panels. """ # name = Base has_content = False # If content returns something, set to true in subclass # We'll maintain a local context instance so we can expose our template # context variables to panels which need them: context = {} # Panel methods def __init__(self, context={}): self.context.update(context) self.toolbar = DebugToolbarMiddleware.get_current() self.slug = slugify(self.name) def dom_id(self): return 'djDebug%sPanel' % (self.name.replace(' ', '')) def nav_title(self): """Title showing in toolbar""" raise NotImplementedError def nav_subtitle(self): """Subtitle showing until title in toolbar""" return '' def title(self): """Title showing in panel""" raise NotImplementedError def url(self): raise NotImplementedError def content(self): raise NotImplementedError def record_stats(self, stats): panel_stats = self.toolbar.stats.get(self.slug) if panel_stats: panel_stats.update(stats) else: self.toolbar.stats[self.slug] = stats def get_stats(self): return self.toolbar.stats.get(self.slug, {}) # Standard middleware methods def process_request(self, request): pass def process_view(self, request, view_func, view_args, view_kwargs): pass def process_response(self, request, response): pass
from django.template.defaultfilters import slugify from debug_toolbar.middleware import DebugToolbarMiddleware class DebugPanel(object): """ Base class for debug panels. """ # name = Base has_content = False # If content returns something, set to true in subclass # We'll maintain a local context instance so we can expose our template # context variables to panels which need them: context = {} # Panel methods def __init__(self, context={}): self.context.update(context) self.toolbar = DebugToolbarMiddleware.get_current() self.slug = slugify(self.name) def dom_id(self): return 'djDebug%sPanel' % (self.name.replace(' ', '')) def nav_title(self): """Title showing in toolbar""" raise NotImplementedError def nav_subtitle(self): """Subtitle showing until title in toolbar""" return '' def title(self): """Title showing in panel""" raise NotImplementedError def url(self): raise NotImplementedError def content(self): raise NotImplementedError def record_stats(self, stats): self.toolbar.stats[self.slug].update(stats) def get_stats(self): return self.toolbar.stats[self.slug] # Standard middleware methods def process_request(self, request): pass def process_view(self, request, view_func, view_args, view_kwargs): pass def process_response(self, request, response): pass
Set ember/no-jquery lint rule to warn as we upgrade Ember CLI to address it later
'use strict'; module.exports = { root: true, parser: 'babel-eslint', parserOptions: { ecmaVersion: 2018, sourceType: 'module', ecmaFeatures: { legacyDecorators: true, }, }, plugins: ['ember'], extends: [ 'eslint:recommended', 'plugin:ember/recommended', 'plugin:prettier/recommended', ], env: { browser: true, }, rules: { // Change these to warning for now as we migrate away from Jquery 'ember/no-jquery': 'warn', }, overrides: [ // node files { files: [ './.eslintrc.js', './.prettierrc.js', './.template-lintrc.js', './ember-cli-build.js', './index.js', './testem.js', './blueprints/*/index.js', './config/**/*.js', './tests/dummy/config/**/*.js', ], parserOptions: { sourceType: 'script', }, env: { browser: false, node: true, }, plugins: ['node'], extends: ['plugin:node/recommended'], }, { // Test files: files: ['tests/**/*-test.{js,ts}'], extends: ['plugin:qunit/recommended'], }, ], };
'use strict'; module.exports = { root: true, parser: 'babel-eslint', parserOptions: { ecmaVersion: 2018, sourceType: 'module', ecmaFeatures: { legacyDecorators: true, }, }, plugins: ['ember'], extends: [ 'eslint:recommended', 'plugin:ember/recommended', 'plugin:prettier/recommended', ], env: { browser: true, }, rules: {}, overrides: [ // node files { files: [ './.eslintrc.js', './.prettierrc.js', './.template-lintrc.js', './ember-cli-build.js', './index.js', './testem.js', './blueprints/*/index.js', './config/**/*.js', './tests/dummy/config/**/*.js', ], parserOptions: { sourceType: 'script', }, env: { browser: false, node: true, }, plugins: ['node'], extends: ['plugin:node/recommended'], }, { // Test files: files: ['tests/**/*-test.{js,ts}'], extends: ['plugin:qunit/recommended'], }, ], };
Fix to show 404 for deleted user
<?php namespace Concrete\Controller\SinglePage\Members; use Concrete\Core\Page\Controller\PublicProfilePageController; use Loader; use User; use UserInfo; use Exception; class Profile extends PublicProfilePageController { public function view($userID = 0) { $html = Loader::helper('html'); $canEdit = false; $u = new User(); if ($userID > 0) { $profile = UserInfo::getByID($userID); if (!is_object($profile)) { return $this->replace('/page_not_found'); } } elseif ($u->isRegistered()) { $profile = UserInfo::getByID($u->getUserID()); } else { $this->set('intro_msg', t('You must sign in order to access this page!')); return $this->replace('/login'); } if (is_object($profile) && $profile->getUserID() == $u->getUserID()) { $canEdit = true; } $this->set('profile', $profile); $this->set('badges', $profile->getUserBadges()); $this->set('av', Loader::helper('concrete/avatar')); $this->set('t', Loader::helper('text')); $this->set('canEdit', $canEdit); } }
<?php namespace Concrete\Controller\SinglePage\Members; use Concrete\Core\Page\Controller\PublicProfilePageController; use Loader; use User; use UserInfo; use Exception; class Profile extends PublicProfilePageController { public function view($userID = 0) { $html = Loader::helper('html'); $canEdit = false; $u = new User(); if ($userID > 0) { $profile = UserInfo::getByID($userID); if (!is_object($profile)) { throw new Exception('Invalid User ID.'); } } elseif ($u->isRegistered()) { $profile = UserInfo::getByID($u->getUserID()); } else { $this->set('intro_msg', t('You must sign in order to access this page!')); return $this->replace('/login'); } if (is_object($profile) && $profile->getUserID() == $u->getUserID()) { $canEdit = true; } $this->set('profile', $profile); $this->set('badges', $profile->getUserBadges()); $this->set('av', Loader::helper('concrete/avatar')); $this->set('t', Loader::helper('text')); $this->set('canEdit', $canEdit); } }
Fix authorisation checking when 'roles' is empty
<?php namespace Gl3n\SerializationGroupBundle; use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface; use Symfony\Component\Security\Core\Exception\AccessDeniedException; /** * Resolves groups and permissions */ class Resolver { /** * @var AuthorizationCheckerInterface */ private $authorizationChecker; /** * @var array */ private $groups; /** * Constructor * * @param AuthorizationCheckerInterface $authorizationChecker * @param array $groups */ public function __construct(AuthorizationCheckerInterface $authorizationChecker, array $groups) { $this->authorizationChecker = $authorizationChecker; $this->groups = $groups; } /** * Resolves group * * @param string $groupName * * @return array An array of group names */ public function resolve($groupName) { $groupNames = [$groupName]; if (isset($this->groups[$groupName])) { if (0 < count($this->groups[$groupName]['roles']) && !$this->authorizationChecker->isGranted($this->groups[$groupName]['roles'])) { throw new AccessDeniedException( sprintf('User has not the required role to use "%s" serialization group', $groupName) ); } foreach ($this->groups[$groupName]['include'] as $includedGroupName) { $groupNames = array_merge($groupNames, $this->resolve($includedGroupName)); } } return $groupNames; } }
<?php namespace Gl3n\SerializationGroupBundle; use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface; use Symfony\Component\Security\Core\Exception\AccessDeniedException; /** * Resolves groups and permissions */ class Resolver { /** * @var AuthorizationCheckerInterface */ private $authorizationChecker; /** * @var array */ private $groups; /** * Constructor * * @param AuthorizationCheckerInterface $authorizationChecker * @param array $groups */ public function __construct(AuthorizationCheckerInterface $authorizationChecker, array $groups) { $this->authorizationChecker = $authorizationChecker; $this->groups = $groups; } /** * Resolves group * * @param string $groupName * * @return array An array of group names */ public function resolve($groupName) { $groupNames = [$groupName]; if (isset($this->groups[$groupName])) { if (!$this->authorizationChecker->isGranted($this->groups[$groupName]['roles'])) { throw new AccessDeniedException( sprintf('User has not the required role to use "%s" serialization group', $groupName) ); } foreach ($this->groups[$groupName]['include'] as $includedGroupName) { $groupNames = array_merge($groupNames, $this->resolve($includedGroupName)); } } return $groupNames; } }
Fix “reload convrsation” button’s state
import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import { loadConversation } from 'redux/modules/conversationModule'; // COMPONENTS import CommentsList from './CommentsList'; import { LoadingScreen } from 'components'; const mappedState = ({ conversation }) => ({ conversationId: conversation.id, comments: conversation.comments, loadingConversation: conversation.loadingConversation, conversationLoaded: conversation.conversationLoaded, loadConversationError: conversation.loadConversationError }); const mappedActions = { loadConversation }; @connect(mappedState, mappedActions) class Conversation extends Component { static propTypes = { articleId: PropTypes.number.isRequired, conversationId: PropTypes.number, comments: PropTypes.array.isRequired, loadingConversation: PropTypes.bool.isRequired, conversationLoaded: PropTypes.bool.isRequired, loadConversationError: PropTypes.bool.isRequired, loadConversation: PropTypes.func.isRequired } componentWillMount() { this.loadComments(); } loadComments = () => { this.props.loadConversation(this.props.articleId); } render() { return ( <LoadingScreen loading={this.props.loadingConversation}> <div> <CommentsList comments={this.props.comments} showReloadList={this.props.loadConversationError} onReloadList={this.loadComments} /> </div> </LoadingScreen> ); } } export default Conversation;
import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import { loadConversation } from 'redux/modules/conversationModule'; // COMPONENTS import CommentsList from './CommentsList'; import { LoadingScreen } from 'components'; const mappedState = ({ conversation }) => ({ conversationId: conversation.id, comments: conversation.comments, loadingConversation: conversation.loadingConversation, conversationLoaded: conversation.conversationLoaded, loadConversationError: conversation.loadConversationError }); const mappedActions = { loadConversation }; @connect(mappedState, mappedActions) class Conversation extends Component { static propTypes = { articleId: PropTypes.number.isRequired, conversationId: PropTypes.number, comments: PropTypes.array.isRequired, loadingConversation: PropTypes.bool.isRequired, conversationLoaded: PropTypes.bool.isRequired, loadConversationError: PropTypes.bool.isRequired, loadConversation: PropTypes.func.isRequired } componentWillMount() { this.loadComments(); } loadComments = () => { this.props.loadConversation(this.props.articleId); } render() { return ( <LoadingScreen loading={this.props.loadingConversation}> <div> <CommentsList comments={this.props.comments} showReloadList={this.props.loadConversationError !== null} onReloadList={this.loadComments} /> </div> </LoadingScreen> ); } } export default Conversation;
Fix inverted longitude and latitude when saving the coordinates to the DB
<?php namespace geotime\helpers; use geotime\models\CalibrationPoint; use geotime\models\CoordinateLatLng; use geotime\models\CoordinateXY; use Logger; Logger::configure("lib/geotime/logger.xml"); class CalibrationPointHelper { /** @var \Logger */ static $log; /** * @param $calibrationPoint \stdClass * @return CalibrationPoint */ public static function generateFromStrings($calibrationPoint) { $bgPointCoordinates = new CoordinateLatLng($calibrationPoint->bgMap->lat, $calibrationPoint->bgMap->lng); $fgPointCoordinates = new CoordinateXY($calibrationPoint->fgMap->x, $calibrationPoint->fgMap->y); return new CalibrationPoint($bgPointCoordinates, $fgPointCoordinates); } /** * @param $calibrationPoint CalibrationPoint * @param $coordinates \stdClass */ public static function addCoordinatesForCalibrationPoint(&$calibrationPoint, $type, $coordinates) { if ($type === 'fgMap') { $calibrationPoint->setFgPoint(new CoordinateXY($coordinates->x, $coordinates->y)); } else if ($type === 'bgMap') { $calibrationPoint->setBgPoint(new CoordinateLatLng($coordinates->lat, $coordinates->lng)); } } } CalibrationPointHelper::$log = Logger::getLogger("main");
<?php namespace geotime\helpers; use geotime\models\CalibrationPoint; use geotime\models\CoordinateLatLng; use geotime\models\CoordinateXY; use Logger; Logger::configure("lib/geotime/logger.xml"); class CalibrationPointHelper { /** @var \Logger */ static $log; /** * @param $calibrationPoint \stdClass * @return CalibrationPoint */ public static function generateFromStrings($calibrationPoint) { $bgPointCoordinates = new CoordinateLatLng($calibrationPoint->bgMap->lat, $calibrationPoint->bgMap->lng); $fgPointCoordinates = new CoordinateXY($calibrationPoint->fgMap->x, $calibrationPoint->fgMap->y); return new CalibrationPoint($bgPointCoordinates, $fgPointCoordinates); } /** * @param $calibrationPoint CalibrationPoint * @param $coordinates \stdClass */ public static function addCoordinatesForCalibrationPoint(&$calibrationPoint, $type, $coordinates) { if ($type === 'fgMap') { $calibrationPoint->setFgPoint(new CoordinateXY($coordinates->x, $coordinates->y)); } else if ($type === 'bgMap') { $calibrationPoint->setBgPoint(new CoordinateLatLng($coordinates->lng, $coordinates->lat)); } } } CalibrationPointHelper::$log = Logger::getLogger("main");
Fix log spam for mute/unmute
module.exports = function (bot) { bot.on('modMute', function (data) { if (config.verboseLogging) { console.log('[EVENT] modMute ', JSON.stringify(data, null, 2)); } var duration = 'unknown'; switch (data.duration) { case 'Short': duration = '15'; break; case 'Medium': duration = '30'; break; case 'Long': duration = '45'; break; default: // maybe this is an unmute? break; } getDbUserFromUsername(data.user.username, function (dbUser) { var message; if (duration == 'unknown') { message = '[UNMUTE] ' + data.user.username + ' (ID: ' + data.user.id + ') was unmuted by ' + data.moderator.username; } else if (dbUser == null) { message = '[MUTE] ' + data.user.username + ' (ID: ' + data.user.id + ') was muted for ' + duration + ' minutes by ' + data.moderator.username; } else { message = '[MUTE] ' + data.user.username + ' (ID: ' + data.user.id + ', LVL: ' + dbUser.site_points + ') was muted for ' + duration + ' minutes by ' + data.moderator.username; } console.log(message); sendToSlack(message); }); }); };
module.exports = function (bot) { bot.on('modMute', function (data) { if (config.verboseLogging) { console.log('[EVENT] modMute ', JSON.stringify(data, null, 2)); } var duration = 'unknown'; switch (data.d) { case 's': duration = '15'; break; case 'm': duration = '30'; break; case 'l': duration = '45'; break; default: // maybe this is an unmute? break; } getDbUserFromUsername(data.t, function (dbUser) { var message; if (duration == 'unknown') { message = '[UNMUTE] ' + data.t + ' (ID:' + data.i + ') was unmuted by ' + data.m; } else if (dbUser == null) { message = '[MUTE] ' + data.t + ' (ID:' + data.i + ') was muted for ' + duration + ' minutes by ' + data.m; } else { message = '[MUTE] ' + data.t + ' (ID:' + data.i + ', LVL:' + dbUser.site_points + ') was muted for ' + duration + ' minutes by ' + data.m; } console.log(message + JSON.stringify(data, null, 2)); sendToSlack(message + JSON.stringify(data, null, 2)); }); }); };
Fix reading wrong keys from config form response
package com.speedledger.measure.jenkins; import hudson.Plugin; import hudson.model.Descriptor; import hudson.model.Items; import net.sf.json.JSONObject; import org.kohsuke.stapler.StaplerRequest; import javax.servlet.ServletException; import java.io.IOException; /** * Elasticsearch plugin to Jenkins. * Reports build information to Elasticsearch on build completion. * * This class only handles loading and saving the configuration of Elasticsearch, see {@link Config}. */ public class ElasticsearchPlugin extends Plugin { private Config config; @Override public void start() throws Exception { Items.XSTREAM.registerConverter(new Config.ConverterImpl()); load(); } @Override public void configure(StaplerRequest req, JSONObject jsonObject) throws IOException, ServletException, Descriptor.FormException { String url = jsonObject.getString("elasticsearchUrl"); String indexName = jsonObject.getString("elasticsearchIndexName"); String typeName = jsonObject.getString("elasticsearchTypeName"); config = new Config(url, indexName, typeName); save(); } public Config getConfig() { return config; } // Used by Jelly public String getUrl() { return config == null ? null : config.getUrl(); } // Used by Jelly public String getIndexName() { return config == null ? null : config.getIndexName(); } // Used by Jelly public String getTypeName() { return config == null ? null : config.getTypeName(); } }
package com.speedledger.measure.jenkins; import hudson.Plugin; import hudson.model.Descriptor; import hudson.model.Items; import net.sf.json.JSONObject; import org.kohsuke.stapler.StaplerRequest; import javax.servlet.ServletException; import java.io.IOException; /** * Elasticsearch plugin to Jenkins. * Reports build information to Elasticsearch on build completion. * * This class only handles loading and saving the configuration of Elasticsearch, see {@link Config}. */ public class ElasticsearchPlugin extends Plugin { private Config config; @Override public void start() throws Exception { Items.XSTREAM.registerConverter(new Config.ConverterImpl()); load(); } @Override public void configure(StaplerRequest req, JSONObject jsonObject) throws IOException, ServletException, Descriptor.FormException { String url = jsonObject.getString("url"); String indexName = jsonObject.getString("indexName"); String typeName = jsonObject.getString("typeName"); config = new Config(url, indexName, typeName); save(); } public Config getConfig() { return config; } // Used by Jelly public String getUrl() { return config == null ? null : config.getUrl(); } // Used by Jelly public String getIndexName() { return config == null ? null : config.getIndexName(); } // Used by Jelly public String getTypeName() { return config == null ? null : config.getTypeName(); } }
Remove fade effect for navbar
/*! * Start Bootstrap - Grayscale Bootstrap Theme (http://startbootstrap.com) * Code licensed under the Apache License v2.0. * For details, see http://www.apache.org/licenses/LICENSE-2.0. */ /*jslint browser: true*/ /*global $, jQuery, alert, google, init*/ /*jshint strict: true */ //jQuery to hide menu on load //$(document).ready(function () { // "use strict"; // hide .navbar first // $(".navbar").hide(); //}); // jQuery to unhide + collapse the navbar on scroll $(window).scroll(function () { "use strict"; if ($(".navbar").offset().top > 50) { //fade-in unhide // $(".navbar").fadeOut(); $(".navbar-fixed-top").addClass("top-nav-collapse"); } else { //fade-out hide // $(".navbar").fadeIn(); $(".navbar-fixed-top").removeClass("top-nav-collapse"); } }); // jQuery for page scrolling feature - requires jQuery Easing plugin $(function () { "use strict"; $('a.page-scroll').bind('click', function (event) { var $anchor = $(this); $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top }, 1500, 'easeInOutExpo'); event.preventDefault(); }); }); // Closes the Responsive Menu on Menu Item Click $('.navbar-collapse ul li a').click(function () { "use strict"; $('.navbar-toggle:visible').click(); });
/*! * Start Bootstrap - Grayscale Bootstrap Theme (http://startbootstrap.com) * Code licensed under the Apache License v2.0. * For details, see http://www.apache.org/licenses/LICENSE-2.0. */ /*jslint browser: true*/ /*global $, jQuery, alert, google, init*/ /*jshint strict: true */ //jQuery to hide menu on load //$(document).ready(function () { // "use strict"; // hide .navbar first // $(".navbar").hide(); //}); // jQuery to unhide + collapse the navbar on scroll $(window).scroll(function () { "use strict"; if ($(".navbar").offset().top > 50) { //fade-in unhide $(".navbar").fadeOut(); $(".navbar-fixed-top").addClass("top-nav-collapse"); } else { //fade-out hide $(".navbar").fadeIn(); $(".navbar-fixed-top").removeClass("top-nav-collapse"); } }); // jQuery for page scrolling feature - requires jQuery Easing plugin $(function () { "use strict"; $('a.page-scroll').bind('click', function (event) { var $anchor = $(this); $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top }, 1500, 'easeInOutExpo'); event.preventDefault(); }); }); // Closes the Responsive Menu on Menu Item Click $('.navbar-collapse ul li a').click(function () { "use strict"; $('.navbar-toggle:visible').click(); });
Use a hint for the suggested text
package com.google.code.quandary; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.code.quandary.quiz.JsonRemoteReader; import com.google.code.quandary.quiz.Quiz; public class QuizEntryActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final EditText et; final Button b; et = (EditText) findViewById(R.id.edittext); et.setHint(getResources().getString(R.string.QuizDefaultUrl)); b = (Button) findViewById(R.id.button); b.setOnClickListener(new OnClickListener() { public void onClick(View v) { String url = et.getText().toString(); if(url == null || url.trim().isEmpty()){ url=getResources().getString(R.string.QuizDefaultUrl); } Toast msg = Toast.makeText(getBaseContext(), "Loading ..." , Toast.LENGTH_LONG); msg.show(); new RunQuizTask(QuizEntryActivity.this).execute(url); } }); } }
package com.google.code.quandary; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.code.quandary.quiz.JsonRemoteReader; import com.google.code.quandary.quiz.Quiz; public class QuizEntryActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final EditText et; final Button b; et = (EditText) findViewById(R.id.edittext); et.setText(getResources().getString(R.string.QuizDefaultUrl)); b = (Button) findViewById(R.id.button); b.setOnClickListener(new OnClickListener() { public void onClick(View v) { String url = et.getText().toString(); if(url == null || url.trim().isEmpty()){ url=getResources().getString(R.string.QuizDefaultUrl); } Toast msg = Toast.makeText(getBaseContext(), "Loading ..." , Toast.LENGTH_LONG); msg.show(); new RunQuizTask(QuizEntryActivity.this).execute(url); } }); } }
Change title of designer index page.
@extends('layout.app', [ 'title' => 'Designers', 'body_id' => 'designer-index-page', 'body_class' => 'designer-index index', 'active_nav' => 'designer', ]) @section('main') <div class="container"> <div class="row"> @foreach ($designers as $designer) <article id="story-{{ $designer->id }}" class="story grid-item col-xs-12 col-sm-6 col-md-4 col-lg-3" data-id="{{ $designer->id }}"> <a href="{{ $designer->url }}"> @if ($image = $designer->image) <img class="featured-image" src="{{ $image->file_urls['thumb'] }}" /> @else <img class="featured-image" src="http://placehold.it/300x300?text=NO+IMAGE" /> @endif <div class="shadow"></div> <div class="text"> {{ $designer->text('name') }}: {{ $designer->text('tagline') }} </div> </a> </article> @endforeach </div><!-- .row --> {!! $designers->links() !!} </div><!-- .container --> @endsection
@extends('layout.app', [ 'title' => 'Design Stories', 'body_id' => 'designer-index-page', 'body_class' => 'designer-index index', 'active_nav' => 'designer', ]) @section('main') <div class="container"> <div class="row"> @foreach ($designers as $designer) <article id="story-{{ $designer->id }}" class="story grid-item col-xs-12 col-sm-6 col-md-4 col-lg-3" data-id="{{ $designer->id }}"> <a href="{{ $designer->url }}"> @if ($image = $designer->image) <img class="featured-image" src="{{ $image->file_urls['thumb'] }}" /> @else <img class="featured-image" src="http://placehold.it/300x300?text=NO+IMAGE" /> @endif <div class="shadow"></div> <div class="text"> {{ $designer->text('name') }}: {{ $designer->text('tagline') }} </div> </a> </article> @endforeach </div><!-- .row --> {!! $designers->links() !!} </div><!-- .container --> @endsection
Reduce overhead trying to shorten line
var angularMeteorTemplate = angular.module('angular-blaze-template', []); // blaze-template adds Blaze templates to Angular as directives angularMeteorTemplate.directive('blazeTemplate', [ '$compile', function ($compile) { return { restrict: 'AE', scope: false, link: function (scope, element, attributes) { // Check if templating and Blaze package exist, they won't exist in a // Meteor Client Side (https://github.com/idanwe/meteor-client-side) application if (Template && Package['blaze']){ var name = attributes.blazeTemplate || attributes.name; if (name && Template[name]) { var template = Template[name], viewHandler; if (typeof attributes['replace'] !== 'undefined') { viewHandler = Blaze. renderWithData(template, scope, element.parent()[0], element[0]); element.remove(); } else { viewHandler = Blaze.renderWithData(template, scope, element[0]); $compile(element.contents())(scope); element.find().unwrap(); } scope.$on('$destroy', function() { Blaze.remove(viewHandler); }); } else { console.error("meteorTemplate: There is no template with the name '" + name + "'"); } } } }; } ]); var angularMeteorModule = angular.module('angular-meteor'); angularMeteorModule.requires.push('angular-blaze-template');
var angularMeteorTemplate = angular.module('angular-blaze-template', []); // blaze-template adds Blaze templates to Angular as directives angularMeteorTemplate.directive('blazeTemplate', [ '$compile', function ($compile) { return { restrict: 'AE', scope: false, link: function (scope, element, attributes) { // Check if templating and Blaze package exist, they won't exist in a // Meteor Client Side (https://github.com/idanwe/meteor-client-side) application if (Template && Package['blaze']){ var name = attributes.blazeTemplate || attributes.name; if (name && Template[name]) { var template = Template[name], viewHandler; if (typeof attributes['replace'] !== 'undefined') { var _renderWithDataAttributes = [ template, scope, element.parent()[0], element[0] ]; viewHandler = Blaze.renderWithData.apply(null, _renderWithDataAttributes); element.remove(); } else { viewHandler = Blaze.renderWithData(template, scope, element[0]); $compile(element.contents())(scope); element.find().unwrap(); } scope.$on('$destroy', function() { Blaze.remove(viewHandler); }); } else { console.error("meteorTemplate: There is no template with the name '" + name + "'"); } } } }; } ]); var angularMeteorModule = angular.module('angular-meteor'); angularMeteorModule.requires.push('angular-blaze-template');
fix: Change 'dest' address for built css files concatenated and minified css files are saved in 'dist/css/' folder instead of 'dist' [ticket: #5]
module.exports = function(grunt) { // Do grunt-related things in here. grunt.initConfig({ // Project configuration pkg: grunt.file.readJSON('package.json'), jshint: { files: ['gruntfile.js'], }, concat: { css: { src: ['node_modules/normalize.css/normalize.css', 'src/css/style.css'], dest: 'dist/css/style.css' } }, cssmin: { target: { files: [{ expand: true, cwd: 'dist/css', src: '*.css', dest: 'dist/css', ext: '.min.css' }] } }, processhtml: { dist: { files: { 'dist/index.html': ['src/index.html'] } } } }); // Load the plugins that provides the tasks: grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.loadNpmTasks('grunt-processhtml'); // Default tasks: grunt.registerTask('default', ['jshint', 'concat', 'cssmin', 'processhtml']); };
module.exports = function(grunt) { // Do grunt-related things in here. grunt.initConfig({ // Project configuration pkg: grunt.file.readJSON('package.json'), jshint: { files: ['gruntfile.js'], }, concat: { css: { src: ['node_modules/normalize.css/normalize.css', 'src/css/style.css'], dest: 'dist/style.css' } }, cssmin: { target: { files: [{ expand: true, cwd: 'dist', src: '*.css', dest: 'dist', ext: '.min.css' }] } }, processhtml: { dist: { files: { 'dist/index.html': ['src/index.html'] } } } }); // Load the plugins that provides the tasks: grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.loadNpmTasks('grunt-processhtml'); // Default tasks: grunt.registerTask('default', ['jshint', 'concat', 'cssmin', 'processhtml']); };
Add check for images property length
(function (env) { 'use strict'; env.ddg_spice_spotify = function(api_result){ var query = DDG.get_query(); query = query.replace(/on spotify/, ''); if (!api_result || api_result.tracks.items.length === 0) { return Spice.failed('spotify'); } Spice.add({ id: 'spotify', name: 'Audio', data: api_result.tracks.items, meta: { sourceName: 'Spotify', sourceUrl: 'https://play.spotify.com/search/' + query.trim(), }, normalize: function(item) { if (!item.album.images.length) { return null; } return { title: item.name, album: item.album.name, image: item.album.images[1].url, /* ~300x300px */ streamURL: '/audio?u=' + item.preview_url, url: item.external_urls.spotify, duration: Math.min(30000, item.duration_ms) }; }, templates: { item: 'audio_item', detail: false, options: { footer: Spice.spotify.footer } } }); }; }(this));
(function (env) { 'use strict'; env.ddg_spice_spotify = function(api_result){ var query = DDG.get_query(); query = query.replace(/on spotify/, ''); if (!api_result || api_result.tracks.items.length === 0) { return Spice.failed('spotify'); } Spice.add({ id: 'spotify', name: 'Audio', data: api_result.tracks.items, meta: { sourceName: 'Spotify', sourceUrl: 'https://play.spotify.com/search/' + query.trim(), }, normalize: function(item) { return { title: item.name, album: item.album.name, image: item.album.images[1].url, /* ~300x300px */ streamURL: '/audio?u=' + item.preview_url, url: item.external_urls.spotify, duration: Math.min(30000, item.duration_ms) }; }, templates: { item: 'audio_item', detail: false, options: { footer: Spice.spotify.footer } } }); }; }(this));
Add dummy param to break caching
require.config({ paths: { jquery: "/static/js/libs/jquery-min", underscore: "/static/js/libs/underscore-min", backbone: "/static/js/libs/backbone-min", mustache: "/static/js/libs/mustache", }, shim: { jquery: { exports: "$" }, underscore: { exports: "_" }, backbone: { deps: ["underscore", "jquery"], exports: "Backbone" } }, // add dummy params to break caching urlArgs: "__nocache__=" + (new Date()).getTime() }); require(["jquery", "underscore","backbone", "mustache"], function ($, _, Backbone, Mustache) { $(function () { // the search bar var SearchBar = Backbone.Model.extend({ initialize: function () { this.bind("change:position", function () { // TODO: change CSS class console.log("position changed!"); }); }, defaults: { position: "center" // the current location of the search bar/box } }); var SearchBarView = Backbone.View.extend({ id: "search-bar", className: "search-bar-position-center" }); // a suggestion below the search bar var AutocompleteSuggestion = Backbone.Model.extend({ defaults: { originator: null, text: "" } }); var AutocompleteSuggestionCollection = Backbone.Collection.extend({ model: AutocompleteSuggestion }); // ** END ** }); });
require.config({ paths: { jquery: "/static/js/libs/jquery-min", underscore: "/static/js/libs/underscore-min", backbone: "/static/js/libs/backbone-min", mustache: "/static/js/libs/mustache", }, shim: { jquery: { exports: "$" }, underscore: { exports: "_" }, backbone: { deps: ["underscore", "jquery"], exports: "Backbone" } } }); require(["jquery", "underscore","backbone", "mustache"], function ($, _, Backbone, Mustache) { $(function () { // the search bar var SearchBar = Backbone.Model.extend({ initialize: function () { this.bind("change:position", function () { // TODO: change CSS class console.log("position changed!"); }); }, defaults: { position: "center" // the current location of the search bar/box } }); var SearchBarView = Backbone.View.extend({ id: "search-bar", className: "search-bar-position-center" }); // a suggestion below the search bar var AutocompleteSuggestion = Backbone.Model.extend({ defaults: { originator: null, text: "" } }); var AutocompleteSuggestionCollection = Backbone.Collection.extend({ model: AutocompleteSuggestion }); // ** END ** }); });
Validate the presence of CONTENT_STORE.
# -*- coding: utf-8 -*- from __future__ import print_function import argparse import sys import os from builder import DeconstJSONBuilder from sphinx.application import Sphinx from sphinx.builders import BUILTIN_BUILDERS def build(argv): """ Invoke Sphinx with locked arguments to generate JSON content. """ parser = argparse.ArgumentParser() parser.add_argument("-s", "--submit", help="Submit results to the content store.", action="store_true") args = parser.parse_args(argv[1:]) content_store_url = os.getenv("CONTENT_STORE") if args.submit and not content_store_url: print("Please set CONTENT_STORE if submitting results.", file=sys.stderr) sys.exit(1) # I am a terrible person BUILTIN_BUILDERS['deconst'] = DeconstJSONBuilder # Lock source and destination to the same paths as the Makefile. srcdir, destdir = '.', '_build/deconst' doctreedir = os.path.join(destdir, '.doctrees') app = Sphinx(srcdir=srcdir, confdir=srcdir, outdir=destdir, doctreedir=doctreedir, buildername="deconst", confoverrides={}, status=sys.stdout, warning=sys.stderr, freshenv=True, warningiserror=False, tags=[], verbosity=0, parallel=1) app.build(True, []) if app.statuscode != 0 or not args.submit: return app.statuscode print("submit active") return 0
# -*- coding: utf-8 -*- import argparse import sys from os import path from builder import DeconstJSONBuilder from sphinx.application import Sphinx from sphinx.builders import BUILTIN_BUILDERS def build(argv): """ Invoke Sphinx with locked arguments to generate JSON content. """ parser = argparse.ArgumentParser() parser.add_argument("-s", "--submit", help="Submit results to the content store.", action="store_true") args = parser.parse_args(argv[1:]) # I am a terrible person BUILTIN_BUILDERS['deconst'] = DeconstJSONBuilder # Lock source and destination to the same paths as the Makefile. srcdir, destdir = '.', '_build/deconst' doctreedir = path.join(destdir, '.doctrees') app = Sphinx(srcdir=srcdir, confdir=srcdir, outdir=destdir, doctreedir=doctreedir, buildername="deconst", confoverrides={}, status=sys.stdout, warning=sys.stderr, freshenv=True, warningiserror=False, tags=[], verbosity=0, parallel=1) app.build(True, []) if app.statuscode != 0 or not args.submit: return app.statuscode print("submit active") return 0
Fix property names to be related to response from riot valorant api
package no.stelar7.api.r4j.pojo.val.matchlist; import java.io.Serializable; import java.util.Objects; public class MatchReference implements Serializable { private static final long serialVersionUID = -5301457261872587385L; private String matchId; private Long gameStartTimeMillis; private String queueId; public String getMatchId() { return matchId; } public Long getGameStartTimeMillis() { return gameStartTimeMillis; } public String getQueueId() { return queueId; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MatchReference match = (MatchReference) o; return Objects.equals(matchId, match.matchId) && Objects.equals(gameStartTimeMillis, match.gameStartTimeMillis) && Objects.equals(queueId, match.queueId); } @Override public int hashCode() { return Objects.hash(matchId, gameStartTimeMillis, queueId); } @Override public String toString() { return "Match{" + "matchId='" + matchId + '\'' + ", gameStartTimeMillis=" + gameStartTimeMillis + ", queueId='" + queueId + '\'' + '}'; } }
package no.stelar7.api.r4j.pojo.val.matchlist; import java.io.Serializable; import java.util.Objects; public class MatchReference implements Serializable { private static final long serialVersionUID = -5301457261872587385L; private String matchId; private Long gameStartTime; private String teamId; public String getMatchId() { return matchId; } public Long getGameStartTime() { return gameStartTime; } public String getTeamId() { return teamId; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MatchReference match = (MatchReference) o; return Objects.equals(matchId, match.matchId) && Objects.equals(gameStartTime, match.gameStartTime) && Objects.equals(teamId, match.teamId); } @Override public int hashCode() { return Objects.hash(matchId, gameStartTime, teamId); } @Override public String toString() { return "Match{" + "matchId='" + matchId + '\'' + ", gameStartTime=" + gameStartTime + ", teamId='" + teamId + '\'' + '}'; } }
Set slider value when adding a new congestion battery This would work when editing an existing battery, but without triggering the event manually it would default to 0% when adding a new battery.
var BatteryTemplateUpdater = (function () { 'use strict'; var defaultPercentage = 20.0, batteryToggles = ".editable.profile", batteries = [ "congestion_battery", "households_flexibility_p2p_electricity" ], sliderSettings = { tooltip: 'hide', formatter: function (value) { return value + "%"; } }; function setSlideStopValue() { var sliderValue = $(this).val(); $(this).parents(".editable").find(".tick.value").text(sliderValue + "%"); } BatteryTemplateUpdater.prototype = { update: function () { var isBattery = (batteries.indexOf(this.data.type) > -1), isCongestionBattery = ("congestion_battery" === this.data.type), batterySlider = this.template.find(".battery-slider"), sliderInput = batterySlider.find("input"); this.template.find(batteryToggles).toggleClass("hidden", isBattery); batterySlider.toggleClass("hidden", !isCongestionBattery); if (isCongestionBattery) { sliderInput.slider(sliderSettings) .slider('setValue', defaultPercentage) .on('slide', setSlideStopValue) .trigger('slide'); this.template.set(sliderInput.data('type'), defaultPercentage); } return this.template; } }; function BatteryTemplateUpdater(context) { this.data = context.data; this.template = context.template; } return BatteryTemplateUpdater; }());
var BatteryTemplateUpdater = (function () { 'use strict'; var defaultPercentage = 20.0, batteryToggles = ".editable.profile", batteries = [ "congestion_battery", "households_flexibility_p2p_electricity" ], sliderSettings = { tooltip: 'hide', formatter: function (value) { return value + "%"; } }; function setSlideStopValue() { var sliderValue = $(this).val(); $(this).parents(".editable").find(".tick.value").text(sliderValue + "%"); } BatteryTemplateUpdater.prototype = { update: function () { var isBattery = (batteries.indexOf(this.data.type) > -1), isCongestionBattery = ("congestion_battery" === this.data.type), batterySlider = this.template.find(".battery-slider"), sliderInput = batterySlider.find("input"); this.template.find(batteryToggles).toggleClass("hidden", isBattery); batterySlider.toggleClass("hidden", !isCongestionBattery); if (isCongestionBattery) { sliderInput.slider(sliderSettings) .slider('setValue', defaultPercentage) .on('slide', setSlideStopValue); this.template.set(sliderInput.data('type'), defaultPercentage); } return this.template; } }; function BatteryTemplateUpdater(context) { this.data = context.data; this.template = context.template; } return BatteryTemplateUpdater; }());
Sort for testing. Fix for test failures introduced in r3557.
package edu.northwestern.bioinformatics.studycalendar.dao.reporting; import edu.northwestern.bioinformatics.studycalendar.dao.StudyCalendarDao; import gov.nih.nci.cabig.ctms.domain.DomainObject; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.criterion.Order; import org.springframework.orm.hibernate3.HibernateCallback; import java.util.Collections; import java.util.List; /** * @author John Dzak */ public abstract class ReportDao<F extends ReportFilters, R extends DomainObject> extends StudyCalendarDao<R> { @SuppressWarnings("unchecked") public List<R> search(final F filters) { return getHibernateTemplate().executeFind(new HibernateCallback() { @SuppressWarnings("unchecked") public Object doInHibernate(Session session) throws HibernateException { if (filters.isEmpty()) { logger.debug("No filters selected, skipping search: " + filters); return Collections.emptyList(); } else { Criteria criteria = session.createCriteria(domainClass()).addOrder(Order.asc("id")); filters.apply(session); return (List<R>) criteria.list(); } } }); } }
package edu.northwestern.bioinformatics.studycalendar.dao.reporting; import edu.northwestern.bioinformatics.studycalendar.dao.StudyCalendarDao; import gov.nih.nci.cabig.ctms.domain.DomainObject; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.Session; import org.springframework.orm.hibernate3.HibernateCallback; import java.util.Collections; import java.util.List; /** * @author John Dzak */ public abstract class ReportDao<F extends ReportFilters, R extends DomainObject> extends StudyCalendarDao<R> { @SuppressWarnings("unchecked") public List<R> search(final F filters) { return getHibernateTemplate().executeFind(new HibernateCallback() { @SuppressWarnings("unchecked") public Object doInHibernate(Session session) throws HibernateException { if (filters.isEmpty()) { logger.debug("No filters selected, skipping search: " + filters); return Collections.emptyList(); } else { Criteria criteria = session.createCriteria(domainClass()); filters.apply(session); return (List<R>) criteria.list(); } } }); } }
Set default-value in the testcontroller
from src.data.TestSuite import TestSuite from src.service.FileHandler import FileHandler from src.service.Runner import Runner from src.service.Evaluator import Evaluator from src.service.salt_api_wrapper import SaltApi class TestController: def __init__(self, test_file, max_iterations=25): self.test_suite = TestSuite("SuiteName") self.test_file = test_file self.file_handler = FileHandler(self.test_suite, self.test_file) self.runner = Runner(self.test_suite, SaltApi(), max_iterations=max_iterations) self.evaluator = Evaluator(self.test_suite) def logic(self): self.file_handler.read_file(self.test_file) self.run_tests() def run_tests(self): self.test_suite.print_all_test_cases() self.runner.run_all() self.evaluator.validate_all_results() if(self.test_suite.has_failed_tests()): if(self.check_re_run_failed_tests()): self.re_run_failed_tests() def re_run_failed_tests(self): self.test_suite.prepare_re_run() self.run_tests() def check_re_run_failed_tests(self): input_var = raw_input('Do you want to re-run the failed tests? \n' + 'Enter yes or y \n') return input_var.lower() == 'yes' or input_var.lower() == 'y'
from src.data.TestSuite import TestSuite from src.service.FileHandler import FileHandler from src.service.Runner import Runner from src.service.Evaluator import Evaluator from src.service.salt_api_wrapper import SaltApi class TestController: def __init__(self, test_file, max_iterations): self.test_suite = TestSuite("SuiteName") self.test_file = test_file self.file_handler = FileHandler(self.test_suite, self.test_file) self.runner = Runner(self.test_suite, SaltApi(), max_iterations=max_iterations) self.evaluator = Evaluator(self.test_suite) def logic(self): self.file_handler.read_file(self.test_file) self.run_tests() def run_tests(self): self.test_suite.print_all_test_cases() self.runner.run_all() self.evaluator.validate_all_results() if(self.test_suite.has_failed_tests()): if(self.check_re_run_failed_tests()): self.re_run_failed_tests() def re_run_failed_tests(self): self.test_suite.prepare_re_run() self.run_tests() def check_re_run_failed_tests(self): input_var = raw_input('Do you want to re-run the failed tests? \n' + 'Enter yes or y \n') return input_var.lower() == 'yes' or input_var.lower() == 'y'
Rename componentWillMount to componentDidMount for search page refreshing
import React, { PureComponent } from "react"; import PropTypes from "prop-types"; import { Button, NonIdealState } from "@blueprintjs/core"; import styled from "styled-components"; import SearchBar from "../containers/SearchBar.js"; import SearchResults from "../containers/SearchResults.js"; import DialogFrame from "./DialogFrame.js"; const BUTTERCUP_LOGO = require("../../../resources/buttercup-standalone.png"); class SearchPage extends PureComponent { static propTypes = { availableSources: PropTypes.number.isRequired, onPrepareFirstResults: PropTypes.func.isRequired, onUnlockAllArchives: PropTypes.func.isRequired }; componentDidMount() { this.props.onPrepareFirstResults(); } render() { return ( <DialogFrame> <Choose> <When condition={this.props.availableSources > 0}> <SearchBar /> <SearchResults /> </When> <Otherwise> <NonIdealState title="No unlocked vaults" description="No vaults are currently available or unlocked." icon={<img src={BUTTERCUP_LOGO} width="64" />} action={ this.props.availableSources === 0 ? ( <Button icon="unlock" onClick={::this.props.onUnlockAllArchives}> Unlock Vaults </Button> ) : null } /> </Otherwise> </Choose> </DialogFrame> ); } } export default SearchPage;
import React, { PureComponent } from "react"; import PropTypes from "prop-types"; import { Button, NonIdealState } from "@blueprintjs/core"; import styled from "styled-components"; import SearchBar from "../containers/SearchBar.js"; import SearchResults from "../containers/SearchResults.js"; import DialogFrame from "./DialogFrame.js"; const BUTTERCUP_LOGO = require("../../../resources/buttercup-standalone.png"); class SearchPage extends PureComponent { static propTypes = { availableSources: PropTypes.number.isRequired, onPrepareFirstResults: PropTypes.func.isRequired, onUnlockAllArchives: PropTypes.func.isRequired }; componentWillMount() { this.props.onPrepareFirstResults(); } render() { return ( <DialogFrame> <Choose> <When condition={this.props.availableSources > 0}> <SearchBar /> <SearchResults /> </When> <Otherwise> <NonIdealState title="No unlocked vaults" description="No vaults are currently available or unlocked." icon={<img src={BUTTERCUP_LOGO} width="64" />} action={ this.props.availableSources === 0 ? ( <Button icon="unlock" onClick={::this.props.onUnlockAllArchives}> Unlock Vaults </Button> ) : null } /> </Otherwise> </Choose> </DialogFrame> ); } } export default SearchPage;
Make it clearer when import could be a bad idea
from distutils.core import setup import skyfield # safe, because __init__.py contains no import statements setup( name='skyfield', version=skyfield.__version__, description=skyfield.__doc__.split('\n', 1)[0], long_description=open('README.rst').read(), license='MIT', author='Brandon Rhodes', author_email='[email protected]', url='http://github.com/brandon-rhodes/python-skyfield/', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: Education', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Scientific/Engineering :: Astronomy', ], packages=[ 'skyfield', 'skyfield.data', 'skyfield.tests', ], package_data = { 'skyfield': ['documentation/*.rst'], 'skyfield.data': ['*.npy', '*.txt'], }, install_requires=[ 'de421==2008.1', 'jplephem>=1.2', 'numpy', 'requests>=1.2.3', 'sgp4>=1.3', ])
from distutils.core import setup import skyfield # to learn the version setup( name='skyfield', version=skyfield.__version__, description=skyfield.__doc__.split('\n', 1)[0], long_description=open('README.rst').read(), license='MIT', author='Brandon Rhodes', author_email='[email protected]', url='http://github.com/brandon-rhodes/python-skyfield/', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: Education', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Scientific/Engineering :: Astronomy', ], packages=[ 'skyfield', 'skyfield.data', 'skyfield.tests', ], package_data = { 'skyfield': ['documentation/*.rst'], 'skyfield.data': ['*.npy', '*.txt'], }, install_requires=[ 'de421==2008.1', 'jplephem>=1.2', 'numpy', 'requests>=1.2.3', 'sgp4>=1.3', ])
Remove form delete_empty legacy BC
<?php namespace EasyCorp\Bundle\EasyAdminBundle\Form\Type\Configurator; use EasyCorp\Bundle\EasyAdminBundle\Form\Util\LegacyFormHelper; use Symfony\Component\Form\FormConfigInterface; /** * This configurator is applied to any form field of type 'collection' and is * used to allow adding/removing elements from the collection. * * @author Maxime Steinhausser <[email protected]> */ class CollectionTypeConfigurator implements TypeConfiguratorInterface { /** * {@inheritdoc} */ public function configure($name, array $options, array $metadata, FormConfigInterface $parentConfig) { if (!isset($options['allow_add'])) { $options['allow_add'] = true; } if (!isset($options['allow_delete'])) { $options['allow_delete'] = true; } if (!isset($options['delete_empty'])) { $options['delete_empty'] = true; } // allow using short form types as the 'entry_type' of the collection if (isset($options['entry_type'])) { $options['entry_type'] = LegacyFormHelper::getType($options['entry_type']); } return $options; } /** * {@inheritdoc} */ public function supports($type, array $options, array $metadata) { return in_array($type, array('collection', 'Symfony\Component\Form\Extension\Core\Type\CollectionType'), true); } }
<?php namespace EasyCorp\Bundle\EasyAdminBundle\Form\Type\Configurator; use EasyCorp\Bundle\EasyAdminBundle\Form\Util\LegacyFormHelper; use Symfony\Component\Form\FormConfigInterface; /** * This configurator is applied to any form field of type 'collection' and is * used to allow adding/removing elements from the collection. * * @author Maxime Steinhausser <[email protected]> */ class CollectionTypeConfigurator implements TypeConfiguratorInterface { /** * {@inheritdoc} */ public function configure($name, array $options, array $metadata, FormConfigInterface $parentConfig) { if (!isset($options['allow_add'])) { $options['allow_add'] = true; } if (!isset($options['allow_delete'])) { $options['allow_delete'] = true; } // The "delete_empty" option exists as of Sf >= 2.5 if (class_exists('Symfony\\Component\\Form\\FormErrorIterator')) { if (!isset($options['delete_empty'])) { $options['delete_empty'] = true; } } // allow using short form types as the 'entry_type' of the collection if (isset($options['entry_type'])) { $options['entry_type'] = LegacyFormHelper::getType($options['entry_type']); } return $options; } /** * {@inheritdoc} */ public function supports($type, array $options, array $metadata) { return in_array($type, array('collection', 'Symfony\Component\Form\Extension\Core\Type\CollectionType'), true); } }
Remove post start as TOSCA agreed to remove it.
package alien4cloud.paas.plan; import static alien4cloud.paas.plan.ToscaNodeLifecycleConstants.*; import static alien4cloud.paas.plan.ToscaRelationshipLifecycleConstants.*; import alien4cloud.paas.model.PaaSNodeTemplate; /** * Generates the default tosca build plan. */ public class BuildPlanGenerator extends AbstractPlanGenerator { @Override protected void generateNodeWorkflow(PaaSNodeTemplate node) { state(node.getId(), INITIAL); call(node, STANDARD, CREATE); state(node.getId(), CREATED); waitTarget(node, DEPENDS_ON, STARTED); waitSource(node, DEPENDS_ON, CREATED); callRelations(node, ToscaRelationshipLifecycleConstants.CONFIGURE, PRE_CONFIGURE_SOURCE, PRE_CONFIGURE_TARGET); call(node, STANDARD, ToscaNodeLifecycleConstants.CONFIGURE); state(node.getId(), CONFIGURED); callRelations(node, ToscaRelationshipLifecycleConstants.CONFIGURE, POST_CONFIGURE_SOURCE, POST_CONFIGURE_TARGET); call(node, STANDARD, START); state(node.getId(), STARTED); waitTarget(node, DEPENDS_ON, AVAILABLE); // synchronous add source / target implementation. callRelations(node, ToscaRelationshipLifecycleConstants.CONFIGURE, ADD_SOURCE, ADD_TARGET); state(node.getId(), AVAILABLE); // process child nodes. parallel(node.getChildren()); } }
package alien4cloud.paas.plan; import static alien4cloud.paas.plan.ToscaNodeLifecycleConstants.*; import static alien4cloud.paas.plan.ToscaRelationshipLifecycleConstants.*; import alien4cloud.paas.model.PaaSNodeTemplate; /** * Generates the default tosca build plan. */ public class BuildPlanGenerator extends AbstractPlanGenerator { @Override protected void generateNodeWorkflow(PaaSNodeTemplate node) { state(node.getId(), INITIAL); call(node, STANDARD, CREATE); state(node.getId(), CREATED); waitTarget(node, DEPENDS_ON, STARTED); waitSource(node, DEPENDS_ON, CREATED); callRelations(node, ToscaRelationshipLifecycleConstants.CONFIGURE, PRE_CONFIGURE_SOURCE, PRE_CONFIGURE_TARGET); call(node, STANDARD, ToscaNodeLifecycleConstants.CONFIGURE); state(node.getId(), CONFIGURED); callRelations(node, ToscaRelationshipLifecycleConstants.CONFIGURE, POST_CONFIGURE_SOURCE, POST_CONFIGURE_TARGET); call(node, STANDARD, START); state(node.getId(), STARTED); waitTarget(node, DEPENDS_ON, AVAILABLE); // synchronous add source / target implementation. callRelations(node, ToscaRelationshipLifecycleConstants.CONFIGURE, ADD_SOURCE, ADD_TARGET); call(node, STANDARD, POST_START); state(node.getId(), AVAILABLE); // process child nodes. parallel(node.getChildren()); } }
Fix encryption issue when creating new nodes
<?php namespace Pterodactyl\Services\Nodes; use Illuminate\Support\Str; use Pterodactyl\Models\Node; use Illuminate\Encryption\Encrypter; use Pterodactyl\Contracts\Repository\NodeRepositoryInterface; class NodeCreationService { /** * @var \Pterodactyl\Contracts\Repository\NodeRepositoryInterface */ protected $repository; /** * @var \Illuminate\Encryption\Encrypter */ private $encrypter; /** * CreationService constructor. * * @param \Illuminate\Encryption\Encrypter $encrypter * @param \Pterodactyl\Contracts\Repository\NodeRepositoryInterface $repository */ public function __construct(Encrypter $encrypter, NodeRepositoryInterface $repository) { $this->repository = $repository; $this->encrypter = $encrypter; } /** * Create a new node on the panel. * * @param array $data * @return \Pterodactyl\Models\Node * * @throws \Pterodactyl\Exceptions\Model\DataValidationException */ public function handle(array $data) { $data['daemon_token'] = $this->encrypter->encrypt(Str::random(Node::DAEMON_TOKEN_LENGTH)); $data['daemon_token_id'] = Str::random(Node::DAEMON_TOKEN_ID_LENGTH); return $this->repository->create($data, true, true); } }
<?php namespace Pterodactyl\Services\Nodes; use Illuminate\Support\Str; use Pterodactyl\Models\Node; use Illuminate\Encryption\Encrypter; use Pterodactyl\Contracts\Repository\NodeRepositoryInterface; class NodeCreationService { /** * @var \Pterodactyl\Contracts\Repository\NodeRepositoryInterface */ protected $repository; /** * @var \Illuminate\Encryption\Encrypter */ private $encrypter; /** * CreationService constructor. * * @param \Illuminate\Encryption\Encrypter $encrypter * @param \Pterodactyl\Contracts\Repository\NodeRepositoryInterface $repository */ public function __construct(Encrypter $encrypter, NodeRepositoryInterface $repository) { $this->repository = $repository; $this->encrypter = $encrypter; } /** * Create a new node on the panel. * * @param array $data * @return \Pterodactyl\Models\Node * * @throws \Pterodactyl\Exceptions\Model\DataValidationException */ public function handle(array $data) { $data['daemon_token'] = Str::random(Node::DAEMON_TOKEN_LENGTH); $data['daemon_token_id'] = $this->encrypter->encrypt(Str::random(Node::DAEMON_TOKEN_ID_LENGTH)); return $this->repository->create($data, true, true); } }
Add Secure Info to Domain Index
@extends('layouts.app') @section('pageTitle', 'Current Domains') @section('content') <h1>Current Domains&nbsp; &nbsp; &nbsp;<a class="btn btn-success" href="{{ route('domain.create') }}"><span class="glyphicon glyphicon-plus"></span></a></h1> <table class="table table-bordered table-responsive"> <thead> <tr> <th>ID</th> <th>Domain Name</th> <th>WordPress</th> <th>Secure</th> <th>Status</th> </tr> </thead> <tbody> @if (isset($domains)) @foreach ($domains as $domain) <tr> <td class="text-center">{{ $domain->id }}</td> <td><a href="http://{{ $domain->name }}" target="_blank">{{ $domain->name }}</a></td> <td class="text-center">{{ $domain->is_word_press ? 'Yes' : 'No' }}</td> <td class="text-center">{{ $domain->is_secure ? 'Yes' : 'No' }}</td> <td class="text-center">{{ $domain->trashed() ? 'Completed' : 'Queued' }}</td> </tr> @endforeach @else <tr> <td colspan="7">There are currently no domains created.</td> </tr> @endif </tbody> </table> @endsection
@extends('layouts.app') @section('pageTitle', 'Current Domains') @section('content') <h1>Current Domains&nbsp; &nbsp; &nbsp;<a class="btn btn-success" href="{{ route('domain.create') }}"><span class="glyphicon glyphicon-plus"></span></a></h1> <table class="table table-bordered table-responsive"> <thead> <tr> <th>ID</th> <th>Domain Name</th> <th>WordPress</th> <th>Status</th> </tr> </thead> <tbody> @if (isset($domains)) @foreach ($domains as $domain) <tr> <td class="text-center">{{ $domain->id }}</td> <td><a href="http://{{ $domain->name }}" target="_blank">{{ $domain->name }}</a></td> <td class="text-center">{{ $domain->is_word_press == 1 ? 'Yes' : 'No' }}</td> <td class="text-center">{{ $domain->trashed() ? 'Completed' : 'Queued' }}</td> </tr> @endforeach @else <tr> <td colspan="7">There are currently no domains created.</td> </tr> @endif </tbody> </table> @endsection
Use new pymongo API in MongoDBStorage
# -*- coding: utf-8 -*- from werobot.session import SessionStorage from werobot.utils import json_loads, json_dumps class MongoDBStorage(SessionStorage): """ MongoDBStorage 会把你的 Session 数据储存在一个 MongoDB Collection 中 :: import pymongo import werobot from werobot.session.mongodbstorage import MongoDBStorage collection = pymongo.MongoClient()["wechat"]["session"] session_storage = MongoDBStorage(collection) robot = werobot.WeRoBot(token="token", enable_session=True, session_storage=session_storage) 你需要安装 ``pymongo`` 才能使用 MongoDBStorage 。 :param collection: 一个 MongoDB Collection。 """ def __init__(self, collection): self.collection = collection collection.create_index("wechat_id") def _get_document(self, id): return self.collection.find_one({"wechat_id": id}) def get(self, id): document = self._get_document(id) if document: session_json = document["session"] return json_loads(session_json) return {} def set(self, id, value): session = json_dumps(value) self.collection.replace_one({ "wechat_id": id }, { "wechat_id": id, "session": session }, upsert=True) def delete(self, id): self.collection.delete_one({ "wechat_id": id })
# -*- coding: utf-8 -*- from werobot.session import SessionStorage from werobot.utils import json_loads, json_dumps class MongoDBStorage(SessionStorage): """ MongoDBStorage 会把你的 Session 数据储存在一个 MongoDB Collection 中 :: import pymongo import werobot from werobot.session.mongodbstorage import MongoDBStorage collection = pymongo.MongoClient()["wechat"]["session"] session_storage = MongoDBStorage(collection) robot = werobot.WeRoBot(token="token", enable_session=True, session_storage=session_storage) 你需要安装 ``pymongo`` 才能使用 MongoDBStorage 。 :param collection: 一个 MongoDB Collection。 """ def __init__(self, collection): import pymongo assert isinstance(collection, pymongo.collection.Collection) self.collection = collection collection.create_index("wechat_id") def _get_document(self, id): return self.collection.find_one({"wechat_id": id}) def get(self, id): document = self._get_document(id) if document: session_json = document["session"] return json_loads(session_json) return {} def set(self, id, value): document = self._get_document(id) session = json_dumps(value) if document: document["session"] = session self.collection.save(document) else: self.collection.insert({ "wechat_id": id, "session": session }) def delete(self, id): document = self._get_document(id) if document: self.collection.remove(document["_id"])
Upgrade boto3facade: not setting signature version v4 globally
"""Setuptools entrypoint.""" import codecs import os from setuptools import setup from s3keyring import __version__, __author__ dirname = os.path.dirname(__file__) long_description = ( codecs.open(os.path.join(dirname, "README.rst"), encoding="utf-8").read() + "\n" + # noqa codecs.open(os.path.join(dirname, "AUTHORS.rst"), encoding="utf-8").read() + "\n" + # noqa codecs.open(os.path.join(dirname, "CHANGES.rst"), encoding="utf-8").read() ) setup( name="s3keyring", include_package_data=True, package_data={"s3keyring": ["s3keyring.ini"]}, packages=["s3keyring"], version=__version__, license="MIT", author=__author__, author_email="[email protected]", url="http://github.com/findhotel/s3keyring", description="S3 backend for Python's keyring module", long_description=long_description, install_requires=[ "click>=5.1", "keyring", "boto3facade>=0.2.8", "awscli", ], classifiers=[ "Programming Language :: Python :: 2", "Programming Language :: Python :: 3" ], zip_safe=False, entry_points={ "console_scripts": [ "s3keyring = s3keyring.cli:main", ] } )
"""Setuptools entrypoint.""" import codecs import os from setuptools import setup from s3keyring import __version__, __author__ dirname = os.path.dirname(__file__) long_description = ( codecs.open(os.path.join(dirname, "README.rst"), encoding="utf-8").read() + "\n" + # noqa codecs.open(os.path.join(dirname, "AUTHORS.rst"), encoding="utf-8").read() + "\n" + # noqa codecs.open(os.path.join(dirname, "CHANGES.rst"), encoding="utf-8").read() ) setup( name="s3keyring", include_package_data=True, package_data={"s3keyring": ["s3keyring.ini"]}, packages=["s3keyring"], version=__version__, license="MIT", author=__author__, author_email="[email protected]", url="http://github.com/findhotel/s3keyring", description="S3 backend for Python's keyring module", long_description=long_description, install_requires=[ "click>=5.1", "keyring", "boto3facade>=0.2.5", "awscli", ], classifiers=[ "Programming Language :: Python :: 2", "Programming Language :: Python :: 3" ], zip_safe=False, entry_points={ "console_scripts": [ "s3keyring = s3keyring.cli:main", ] } )
fix(form): Update placeholder language in location field to reflect new mouse/tap interaction Refs conveyal/trimet-mod-otp#131
import React, { Component } from 'react' import PropTypes from 'prop-types' import LocationField from './location-field' import SwitchButton from './switch-button' import TabbedFormPanel from './tabbed-form-panel' export default class DefaultSearchForm extends Component { static propTypes = { icons: PropTypes.object, mobile: PropTypes.bool } static defaultProps = { showFrom: true, showTo: true } constructor () { super() this.state = { desktopDateTimeExpanded: false, desktopSettingsExpanded: false } } render () { const { icons, mobile } = this.props const actionText = mobile ? 'tap' : 'click' return ( <div> <div className='locations'> <LocationField type='from' label={`Enter start location or ${actionText} on map...`} showClearButton /> <LocationField type='to' label={`Enter destination or ${actionText} on map...`} showClearButton={!mobile} /> <div className='switch-button-container'> <SwitchButton content={<i className='fa fa-exchange fa-rotate-90' />} /> </div> </div> <TabbedFormPanel icons={icons} /> </div> ) } }
import React, { Component } from 'react' import PropTypes from 'prop-types' import LocationField from './location-field' import SwitchButton from './switch-button' import TabbedFormPanel from './tabbed-form-panel' export default class DefaultSearchForm extends Component { static propTypes = { icons: PropTypes.object, mobile: PropTypes.bool } static defaultProps = { showFrom: true, showTo: true } constructor () { super() this.state = { desktopDateTimeExpanded: false, desktopSettingsExpanded: false } } render () { const { icons, mobile } = this.props const actionText = mobile ? 'long press' : 'right-click' return ( <div> <div className='locations'> <LocationField type='from' label={`Enter start location or ${actionText} on map...`} showClearButton /> <LocationField type='to' label={`Enter destination or ${actionText} on map...`} showClearButton={!mobile} /> <div className='switch-button-container'> <SwitchButton content={<i className='fa fa-exchange fa-rotate-90' />} /> </div> </div> <TabbedFormPanel icons={icons} /> </div> ) } }
Fix a bug - tests pass
# -*- coding: utf-8 -*- from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from __future__ import print_function from ...trajectories import Trajectories __all__ = [] class AbstractSolver(object): """ Parameters ---------- trajs : :class:`sktracker.trajectories.Trajectories` The trajectories """ def __init__(self, trajs): self.trajs = Trajectories(trajs) def check_cost_function_type(self, obj, cost_funtion_type): """Check wether an object inherit from another one. Parameters ---------- obj : object cost_funtion_type : class name Raises ------ TypeError : `obj` type does not inherit from `cost_funtion_type` """ error_mess = '''The cost function {} doesn't inherit from {}''' if not isinstance(obj, cost_funtion_type): raise TypeError(error_mess.format(obj, cost_funtion_type.__name__)) def relabel_trajs(self, new_labels=None): """ Sets the trajectory index `label` to new values. Parameters ---------- new_labels: :class:`numpy.ndarray` or None, default None The new label. If it is not provided, the function wil look for will look for a column named "new_label" in `trajs` and use this as the new label index """ self.trajs.relabel(new_labels=new_labels)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from __future__ import print_function from ...trajectories import Trajectories __all__ = [] class AbstractSolver(object): """ Parameters ---------- trajs : :class:`sktracker.trajectories.Trajectories` The trajectories """ def __init__(self, trajs): self.trajs = Trajectories(trajs) def check_cost_function_type(self, obj, cost_funtion_type): """Check wether an object inherit from another one. Parameters ---------- obj : object cost_funtion_type : class name Raises ------ TypeError : `obj` type does not inherit from `cost_funtion_type` """ error_mess = '''The cost function {} doesn't inherit from {}''' if not isinstance(obj, cost_funtion_type): raise TypeError(error_mess.format(obj, cost_funtion_type.__name__)) def relabel_trajs(self, new_labels=None): """ Sets the trajectory index `label` to new values. Parameters ---------- new_labels: :class:`numpy.ndarray` or None, default None The new label. If it is not provided, the function wil look for will look for a column named "new_label" in `trajs` and use this as the new label index """ self.trajs.relabel(self, new_labels=new_labels)
Use `id` instead of `lake_guid` for asset import [WEB-1870]
<?php namespace App\Transformers\Inbound\Collections; use App\Transformers\Datum; use App\Transformers\Inbound\CollectionsTransformer; class Asset extends CollectionsTransformer { protected function getIds(Datum $datum) { return [ 'lake_guid' => $datum->id, ]; } protected function getDates(Datum $datum) { $dates = parent::getDates($datum); return array_merge($dates, [ 'content_modified_at' => $datum->date('content_modified_at'), ]); } protected function getSync(Datum $datum, $test = false) { return [ 'imagedArtworks' => $this->getSyncAssetOf($datum, 'rep_of_artworks'), 'imagedExhibitions' => $this->getSyncAssetOf($datum, 'rep_of_exhibitions'), 'documentedArtworks' => $this->getSyncAssetOf($datum, 'doc_of_artworks'), 'documentedExhibitions' => $this->getSyncAssetOf($datum, 'doc_of_exhibitions'), ]; } private function getSyncAssetOf(Datum $datum, string $pivot_field) { return $this->getSyncPivots($datum, $pivot_field, 'related_id', function ($pivot) { return [ $pivot->related_id => [ 'preferred' => $pivot->is_preferred, 'is_doc' => $pivot->is_doc, ], ]; }); } }
<?php namespace App\Transformers\Inbound\Collections; use App\Transformers\Datum; use App\Transformers\Inbound\CollectionsTransformer; class Asset extends CollectionsTransformer { protected function getIds(Datum $datum) { return [ 'lake_guid' => $datum->lake_guid, ]; } protected function getDates(Datum $datum) { $dates = parent::getDates($datum); return array_merge($dates, [ 'content_modified_at' => $datum->date('content_modified_at'), ]); } protected function getSync(Datum $datum, $test = false) { return [ 'imagedArtworks' => $this->getSyncAssetOf($datum, 'rep_of_artworks'), 'imagedExhibitions' => $this->getSyncAssetOf($datum, 'rep_of_exhibitions'), 'documentedArtworks' => $this->getSyncAssetOf($datum, 'doc_of_artworks'), 'documentedExhibitions' => $this->getSyncAssetOf($datum, 'doc_of_exhibitions'), ]; } private function getSyncAssetOf(Datum $datum, string $pivot_field) { return $this->getSyncPivots($datum, $pivot_field, 'related_id', function ($pivot) { return [ $pivot->related_id => [ 'preferred' => $pivot->is_preferred, 'is_doc' => $pivot->is_doc, ], ]; }); } }
Modify round-trip test to use new function name. We've temporarily settled on `fromdap()` for importing from `__distarray__` interfaces.
import unittest import distarray as da from distarray.mpi.mpibase import create_comm_of_size, InvalidCommSizeError class TestDistributedArrayProtocol(unittest.TestCase): def setUp(self): try: comm = create_comm_of_size(4) except InvalidCommSizeError: raise unittest.SkipTest('Must run with comm size > 4.') else: self.larr = da.LocalArray((16,16), grid_shape=(4,), comm=comm, buf=None, offset=0) def test_has_export(self): self.assertTrue(hasattr(self.larr, '__distarray__')) def test_export_keys(self): required_keys = set(("buffer", "dimdata")) export_data = self.larr.__distarray__() exported_keys = set(export_data.keys()) self.assertEqual(required_keys, exported_keys) def test_export_buffer(self): """See if we actually export a buffer.""" export_data = self.larr.__distarray__() memoryview(export_data['buffer']) @unittest.skip("Import not yet implemented.") def test_round_trip(self): new_larr = da.fromdap(self.larr) self.assertIs(new_larr.local_array, self.larr.local_array) if __name__ == '__main__': try: unittest.main() except SystemExit: pass
import unittest import distarray as da from distarray.mpi.mpibase import create_comm_of_size, InvalidCommSizeError class TestDistributedArrayProtocol(unittest.TestCase): def setUp(self): try: comm = create_comm_of_size(4) except InvalidCommSizeError: raise unittest.SkipTest('Must run with comm size > 4.') else: self.larr = da.LocalArray((16,16), grid_shape=(4,), comm=comm, buf=None, offset=0) def test_has_export(self): self.assertTrue(hasattr(self.larr, '__distarray__')) def test_export_keys(self): required_keys = set(("buffer", "dimdata")) export_data = self.larr.__distarray__() exported_keys = set(export_data.keys()) self.assertEqual(required_keys, exported_keys) def test_export_buffer(self): """See if we actually export a buffer.""" export_data = self.larr.__distarray__() memoryview(export_data['buffer']) def test_round_trip(self): new_larr = da.localarray(self.larr) self.assertEqual(new_larr.local_array, self.larr.local_array) if __name__ == '__main__': try: unittest.main() except SystemExit: pass
Change main thread to support upstart
package org.endeavourhealth.hl7receiver; import org.endeavourhealth.core.data.config.ConfigManagerException; import org.endeavourhealth.hl7receiver.hl7.HL7Service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Main { private static final String PROGRAM_DISPLAY_NAME = "EDS HL7 receiver"; private static final Logger LOG = LoggerFactory.getLogger(Main.class); private static HL7Service serviceManager; public static void main(String[] args) { try { Configuration configuration = Configuration.getInstance(); LOG.info("--------------------------------------------------"); LOG.info(PROGRAM_DISPLAY_NAME); LOG.info("--------------------------------------------------"); HL7Service serviceManager = new HL7Service(configuration); serviceManager.start(); LOG.info("Started succesfully..."); Runtime.getRuntime().addShutdownHook(new Thread(() -> shutdown())); } catch (ConfigManagerException cme) { printToErrorConsole("Fatal exception occurred initializing ConfigManager", cme); LOG.error("Fatal exception occurred initializing ConfigManager", cme); System.exit(-2); } catch (Exception e) { LOG.error("Fatal exception occurred", e); System.exit(-1); } } private static void shutdown() { try { LOG.info("Shutting down..."); if (serviceManager != null) serviceManager.stop(); } catch (Exception e) { printToErrorConsole("Exception occurred during shutdown", e); LOG.error("Exception occurred during shutdown", e); } } private static void printToErrorConsole(String message, Exception e) { System.err.println(message + " [" + e.getClass().getName() + "] " + e.getMessage()); } }
package org.endeavourhealth.hl7receiver; import org.endeavourhealth.core.data.config.ConfigManagerException; import org.endeavourhealth.hl7receiver.hl7.HL7Service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Main { private static final String PROGRAM_DISPLAY_NAME = "EDS HL7 receiver"; private static final Logger LOG = LoggerFactory.getLogger(Main.class); public static void main(String[] args) { try { Configuration configuration = Configuration.getInstance(); LOG.info("--------------------------------------------------"); LOG.info(PROGRAM_DISPLAY_NAME); LOG.info("--------------------------------------------------"); HL7Service serviceManager = new HL7Service(configuration); serviceManager.start(); LOG.info("Press any key to exit..."); System.in.read(); LOG.info("Shutting down..."); serviceManager.stop(); LOG.info("Shutdown"); System.exit(0); } catch (ConfigManagerException cme) { System.err.println("Fatal exception occurred initializing ConfigManager [" + cme.getClass().getName() + "] " + cme.getMessage()); LOG.error("Fatal exception occurred initializing ConfigManager", cme); System.exit(-2); } catch (Exception e) { LOG.error("Fatal exception occurred", e); System.exit(-1); } } }
Make sure config merging takes place
<?php namespace Laravel\Tinker; use Illuminate\Foundation\Application as LaravelApplication; use Illuminate\Support\ServiceProvider; use Laravel\Lumen\Application as LumenApplication; use Laravel\Tinker\Console\TinkerCommand; class TinkerServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Boot the service provider. * * @return void */ public function boot() { $source = realpath($raw = __DIR__ . '/../config/tinker.php') ?: $raw; if ($this->app instanceof LaravelApplication && $this->app->runningInConsole()) { $this->publishes([$source => config_path('tinker.php')]); } elseif ($this->app instanceof LumenApplication) { $this->app->configure('tinker'); } $this->mergeConfigFrom($source, 'tinker'); } /** * Register the service provider. * * @return void */ public function register() { $this->app->singleton('command.tinker', function () { return new TinkerCommand; }); $this->commands(['command.tinker']); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return ['command.tinker']; } }
<?php namespace Laravel\Tinker; use Illuminate\Foundation\Application as LaravelApplication; use Illuminate\Support\ServiceProvider; use Laravel\Lumen\Application as LumenApplication; use Laravel\Tinker\Console\TinkerCommand; class TinkerServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Boot the service provider. * * @return void */ public function boot() { $source = realpath($raw = __DIR__ . '/../config/tinker.php') ?: $raw; if ($this->app instanceof LaravelApplication && $this->app->runningInConsole()) { $this->publishes([$source => config_path('tinker.php')]); } elseif ($this->app instanceof LumenApplication) { $this->app->configure('tinker'); } } /** * Register the service provider. * * @return void */ public function register() { $this->app->singleton('command.tinker', function () { return new TinkerCommand; }); $this->commands(['command.tinker']); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return ['command.tinker']; } }
Include DB and JoinClause in the template factory generator view
<?= '<?php' ?> namespace {{$namespace}}; use Chalcedonyt\QueryBuilderTemplate\Templates\Factory\AbstractTemplateFactory; use DB; use Illuminate\Database\Query\JoinClause; class {{$classname}} extends AbstractTemplateFactory { @if (count($parameters)) @foreach( $parameters as $param) /** * @var {{$param['class']}} */ protected ${{camel_case($param['name'])}}; @endforeach @endif /** * @if (!count($parameters)) * Set properties here for a parameterized factory. @else @foreach( $parameters as $param) * @param {{$param['class']}} ${{camel_case($param['name'])}} @endforeach @endif * */ public function __construct({{$parameter_string}}) { @if (count($parameters)) @foreach( $parameters as $param) $this -> {{camel_case($param['name'])}} = ${{$param['name']}}; @endforeach @endif } /** * The base query. DB::table and ::select should be set here * @return Builder */ protected function getBaseQuery() { //return DB::table('users') -> select('users.*'); } /** * Possible Joins to make depending on the ScopeInterface objects added. * @return Array of Illuminate\Database\Query\JoinClause */ protected function getAvailableJoinClauses(){ /*join with the survey table $post_join = new JoinClause('inner','posts'); $post_join -> on('post.user_id','=','users.id'); return [ $post_join ];*/ return []; } } ?>
<?= '<?php' ?> namespace {{$namespace}}; use Chalcedonyt\QueryBuilderTemplate\Templates\Factory\AbstractTemplateFactory; class {{$classname}} extends AbstractTemplateFactory { @if (count($parameters)) @foreach( $parameters as $param) /** * @var {{$param['class']}} */ protected ${{camel_case($param['name'])}}; @endforeach @endif /** * @if (!count($parameters)) * Set properties here for a parameterized factory. @else @foreach( $parameters as $param) * @param {{$param['class']}} ${{camel_case($param['name'])}} @endforeach @endif * */ public function __construct({{$parameter_string}}) { @if (count($parameters)) @foreach( $parameters as $param) $this -> {{camel_case($param['name'])}} = ${{$param['name']}}; @endforeach @endif } /** * The base query. DB::table and ::select should be set here * @return Builder */ protected function getBaseQuery() { //return DB::table('users') -> select('users.*'); } /** * Possible Joins to make depending on the ScopeInterface objects added. * @return Array of Illuminate\Database\Query\JoinClause */ protected function getAvailableJoinClauses(){ /*join with the survey table $post_join = new JoinClause('inner','posts'); $post_join -> on('post.user_id','=','users.id'); return [ $post_join ];*/ return []; } } ?>
Tidy up this test - still quite bad & useless.
''' System tests for `jenkinsapi.jenkins` module. ''' import re import time import unittest from jenkinsapi_tests.systests.base import BaseSystemTest from jenkinsapi_tests.systests.job_configs import MATRIX_JOB from jenkinsapi_tests.test_utils.random_strings import random_string class TestMatrixJob(BaseSystemTest): def test_invoke_matrix_job(self): job_name = 'create_%s' % random_string() job = self.jenkins.create_job(job_name, MATRIX_JOB) job.invoke(block=True) build = job.get_last_build() while build.is_running(): time.sleep(1) set_of_groups = set() for run in build.get_matrix_runs(): self.assertEquals(run.get_number(), build.get_number()) self.assertEquals(run.get_upstream_build(), build) match_result = re.search(u'\xbb (.*) #\\d+$', run.name) self.assertIsNotNone(match_result) set_of_groups.add(match_result.group(1)) build.get_master_job_name() # This is a bad test, it simply verifies that this function does # not crash on a build from a matrix job. self.assertFalse(build.get_master_job_name()) self.assertEqual(set_of_groups, set(['one', 'two', 'three'])) if __name__ == '__main__': unittest.main()
''' System tests for `jenkinsapi.jenkins` module. ''' import re import time import unittest from jenkinsapi_tests.systests.base import BaseSystemTest from jenkinsapi_tests.systests.job_configs import MATRIX_JOB from jenkinsapi_tests.test_utils.random_strings import random_string class TestMatrixJob(BaseSystemTest): def test_invoke_matrix_job(self): job_name = 'create_%s' % random_string() job = self.jenkins.create_job(job_name, MATRIX_JOB) job.invoke(block=True) b = job.get_last_build() while b.is_running(): time.sleep(1) s = set() for r in b.get_matrix_runs(): self.assertEquals(r.get_number(), b.get_number()) self.assertEquals(r.get_upstream_build(), b) m = re.search(u'\xbb (.*) #\\d+$', r.name) self.assertIsNotNone(m) s.add(m.group(1)) # This is a bad test, it simply verifies that this function does # not crash on a build from a matrix job. self.assertFalse(b.get_master_job_name()) self.assertEqual(s, set(['one', 'two', 'three'])) if __name__ == '__main__': unittest.main()
Change xrange for range for py3
# From http://stackoverflow.com/questions/2687173/django-how-can-i-get-a-block-from-a-template from django.template import Context from django.template.loader_tags import BlockNode, ExtendsNode class BlockNotFound(Exception): pass def _iter_nodes(template, context, name, block_lookups): for node in template.template.nodelist: if isinstance(node, BlockNode) and node.name == name: # Rudimentary handling of extended templates, for issue #3 for i in range(len(node.nodelist)): n = node.nodelist[i] if isinstance(n, BlockNode) and n.name in block_lookups: node.nodelist[i] = block_lookups[n.name] context.template = template.template return node.render(context) elif isinstance(node, ExtendsNode): lookups = { n.name: n for n in node.nodelist if isinstance(n, BlockNode) } lookups.update(block_lookups) return _get_node(node.get_parent(context), context, name, lookups) raise BlockNotFound("Node '%s' could not be found in template." % name) def _get_node(template, context=Context(), name='subject', block_lookups={}): try: return _iter_nodes(template, context, name, block_lookups) except TypeError: context.template = template.template return _iter_nodes(template.template, context, name, block_lookups)
# From http://stackoverflow.com/questions/2687173/django-how-can-i-get-a-block-from-a-template from django.template import Context from django.template.loader_tags import BlockNode, ExtendsNode class BlockNotFound(Exception): pass def _iter_nodes(template, context, name, block_lookups): for node in template.template.nodelist: if isinstance(node, BlockNode) and node.name == name: # Rudimentary handling of extended templates, for issue #3 for i in xrange(len(node.nodelist)): n = node.nodelist[i] if isinstance(n, BlockNode) and n.name in block_lookups: node.nodelist[i] = block_lookups[n.name] context.template = template.template return node.render(context) elif isinstance(node, ExtendsNode): lookups = { n.name: n for n in node.nodelist if isinstance(n, BlockNode) } lookups.update(block_lookups) return _get_node(node.get_parent(context), context, name, lookups) raise BlockNotFound("Node '%s' could not be found in template." % name) def _get_node(template, context=Context(), name='subject', block_lookups={}): try: return _iter_nodes(template, context, name, block_lookups) except TypeError: context.template = template.template return _iter_nodes(template.template, context, name, block_lookups)
Use new jquery jqXHR API.
define([ 'jquery' ], function($) { var Auth = function () {}; Auth.prototype = { init: function (authconfig) { navigator.id.watch({ loggedInUser: authconfig.currentUser, onlogin: function (assertion) { $.ajax({ type: 'POST', url: '/login', data: { assertion: assertion } }) .done(function(data) { window.location.href = data.accountUrl; }) .fail(function(jqXHR, textStatus, errorThrown) { console.error('onlogin fail', jqXHR, textStatus, errorThrown, jqXHR.responseText); navigator.id.logout(); // TODO translate string alert("Login failure"); }); }, onlogout: function () { if (window.location.pathname == '/logout') { window.location.href = '/'; } else { $.ajax({ type: 'POST', url: '/logout' }) .done(function() { window.location.reload(); }) .fail(function(jqXHR, textStatus, errorThrown) { console.error('onlogout fail', jqXHR, textStatus, errorThrown, jqXHR.responseText); // TODO translate string alert("Logout failure"); }); } } }); $(document).on('click', '.sign-in', function () { navigator.id.request(); }); $(document).on('click', '.sign-out', function() { navigator.id.logout(); }); } }; var auth = new Auth(); return auth; });
define([ 'jquery' ], function($) { var Auth = function () {}; Auth.prototype = { init: function (authconfig) { navigator.id.watch({ loggedInUser: authconfig.currentUser, onlogin: function (assertion) { $.ajax({ type: 'POST', url: '/login', data: { assertion: assertion }, success: function(res, status, xhr) { window.location.href = res.accountUrl; }, error: function(xhr, status, err) { navigator.id.logout(); // TODO translate string alert("Login failure: " + err); } }); }, onlogout: function () { if (window.location.pathname == '/logout') { window.location.href = '/'; } else { $.ajax({ type: 'POST', url: '/logout', success: function(res, status, xhr) { window.location.reload(); }, error: function(xhr, status, err) { // TODO translate string alert("Logout failure: " + err); } }); } } }); $(document).on('click', '.sign-in', function () { navigator.id.request(); }); $(document).on('click', '.sign-out', function() { navigator.id.logout(); }); } }; var auth = new Auth(); return auth; });
Add the possibility to follow or not a symlink
const fs = require('fs') const util = require('util') const path = require('path') class FsUtils { static get chmod() { return util.promisify(fs.chmod) } static get readFile() { return util.promisify(fs.readFile) } static get symlink() { return util.promisify(fs.symlink) } static get writeFile() { return util.promisify(fs.writeFile) } static get mkdir() { return util.promisify(fs.mkdir) } static get rename() { return util.promisify(fs.rename) } static fileExist(filename = '', followLink = true) { try { if (followLink) { fs.accessSync(filename) } else { fs.lstatSync(filename) } } catch (e) { return false } return true } static mkdirp(pathname = '') { const pathParts = pathname.split('/') return pathParts.reduce((promise, part) => promise .then(previousPath => { const newPath = path.join(previousPath, part) if (FsUtils.fileExist(newPath)) { return newPath } return FsUtils.mkdir(newPath) .catch(error => { if (error.code !== 'EEXIST') { throw new Error('dir_create_failed') } }) .then(() => newPath) }), Promise.resolve(pathname[0] === '/' ? '/' : '')) } } module.exports = exports = { FsUtils }
const fs = require('fs') const util = require('util') const path = require('path') class FsUtils { static get chmod() { return util.promisify(fs.chmod) } static get readFile() { return util.promisify(fs.readFile) } static get symlink() { return util.promisify(fs.symlink) } static get writeFile() { return util.promisify(fs.writeFile) } static get mkdir() { return util.promisify(fs.mkdir) } static get rename() { return util.promisify(fs.rename) } static fileExist(filename = '') { try { fs.lstatSync(filename) } catch (e) { return false } return true } static mkdirp(pathname = '') { const pathParts = pathname.split('/') return pathParts.reduce((promise, part) => promise .then(previousPath => { const newPath = path.join(previousPath, part) if (FsUtils.fileExist(newPath)) { return newPath } return FsUtils.mkdir(newPath) .catch(error => { if (error.code !== 'EEXIST') { throw new Error('dir_create_failed') } }) .then(() => newPath) }), Promise.resolve(pathname[0] === '/' ? '/' : '')) } } module.exports = exports = { FsUtils }
Fix typo in console message
import React from 'react'; export let IntercomAPI = window.Intercom || function() { console.warn('Intercom not initialized yet') }; export default class Intercom extends React.Component { static propTypes = { appID: React.PropTypes.string.isRequired } static displayName = 'Intercom' constructor(props) { super(props); if (typeof window.Intercom === "function" || !props.appID) { return; } (function(w, d, id, s, x) { function i() { i.c(arguments); } i.q = []; i.c = function(args) { i.q.push(args); }; w.Intercom = i; s = d.createElement('script'); s.onload = function() { IntercomAPI = window.Intercom }; s.async = 1; s.src = 'https://widget.intercom.io/widget/' + id; x = d.getElementsByTagName('script')[0]; x.parentNode.insertBefore(s, x); })(window, document, props.appID); window.intercomSettings = props; if (typeof window.Intercom === 'function') { window.Intercom('boot', props); } } componentWillReceiveProps(nextProps) { window.intercomSettings = nextProps; window.Intercom('update'); } shouldComponentUpdate() { return false; } componentWillUnmount() { window.Intercom('shudown'); } render() { return false; } }
import React from 'react'; export let IntercomAPI = window.Intercom || function() { console.warn('Intercome not initialized yet') }; export default class Intercom extends React.Component { static propTypes = { appID: React.PropTypes.string.isRequired } static displayName = 'Intercom' constructor(props) { super(props); if (typeof window.Intercom === "function" || !props.appID) { return; } (function(w, d, id, s, x) { function i() { i.c(arguments); } i.q = []; i.c = function(args) { i.q.push(args); }; w.Intercom = i; s = d.createElement('script'); s.onload = function() { IntercomAPI = window.Intercom }; s.async = 1; s.src = 'https://widget.intercom.io/widget/' + id; x = d.getElementsByTagName('script')[0]; x.parentNode.insertBefore(s, x); })(window, document, props.appID); window.intercomSettings = props; if (typeof window.Intercom === 'function') { window.Intercom('boot', props); } } componentWillReceiveProps(nextProps) { window.intercomSettings = nextProps; window.Intercom('update'); } shouldComponentUpdate() { return false; } componentWillUnmount() { window.Intercom('shudown'); } render() { return false; } }