text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Fix script addition to package.son
'use strict'; var generators = require('yeoman-generator'); var extend = require('deep-extend'); module.exports = generators.Base.extend({ constructor: function () { generators.Base.apply(this, arguments); this.option('coveralls', { required: false, defaults: false, desc: 'Use React syntax' }); this.option('testRunner', { required: true, defaults: 'gulp', desc: 'Test runner' }); }, writing: { travisyml: function () { this.fs.copyTpl( this.templatePath('travis.yml'), this.destinationPath('.travis.yml'), { coveralls: this.options.coveralls, testRunner: this.options.testRunner, } ); }, packageJson: function () { var pkg = this.fs.readJSON(this.destinationPath('package.json'), {}); if (this.options.testRunner === 'karma') { extend(pkg, { scripts: { "test-travis": "karma start --single-run", } }); } else if (this.options.testRunner === 'gulp') { extend(pkg, { scripts: { "test-travis": "gulp test-travis", } }); } this.fs.writeJSON(this.destinationPath('package.json'), pkg); } } });
'use strict'; var generators = require('yeoman-generator'); var extend = require('deep-extend'); module.exports = generators.Base.extend({ constructor: function () { generators.Base.apply(this, arguments); this.option('coveralls', { required: false, defaults: false, desc: 'Use React syntax' }); this.option('testRunner', { required: true, defaults: 'gulp', desc: 'Test runner' }); }, writing: { travisyml: function () { this.fs.copyTpl( this.templatePath('travis.yml'), this.destinationPath('.travis.yml'), { coveralls: this.options.coveralls, testRunner: this.options.testRunner, } ); }, package: function () { var pkg = this.fs.readJSON(this.destinationPath('package.json'), {}); if (this.options.testRunner === 'karma') { extend(pkg, { devDependencies: { scripts: { "test-travis": "karma start --browsers Firefox --single-run", } } }); } else if (this.options.testRunner === 'gulp') { extend(pkg, { devDependencies: { scripts: { "test-travis": "gulp test-travis", } } }); } this.fs.writeJSON(this.destinationPath('package.json'), pkg); } } });
Clean up Travis CI/JSHint gripes.
'use strict'; angular.module('confRegistrationWebApp') .controller('AdminDataCtrl', function ($scope, registrations, conference) { $scope.conference = conference; $scope.blocks = []; $scope.reversesort = false; angular.forEach(conference.registrationPages, function (page) { angular.forEach(page.blocks, function (block) { if (block.type.indexOf('Content') === -1) { $scope.blocks.push(block); } }); }); $scope.findAnswer = function (registration, blockId) { return _.find(registration.answers, function (answer) { return angular.equals(answer.blockId, blockId); }); }; $scope.getSelectedCheckboxes = function (choices) { var selectedKeys = []; for (var key in choices) { if (choices[key]) { selectedKeys.push(key); } } return selectedKeys; }; $scope.answerSort = function (registration) { if (angular.isDefined($scope.order)) { if (angular.isDefined($scope.findAnswer(registration, $scope.order))) { return $scope.findAnswer(registration, $scope.order).value; } } else { return 0; } }; $scope.setOrder = function (order) { if (order === $scope.order) { $scope.reversesort = !$scope.reversesort; } else { $scope.reversesort = false; } $scope.order = order; }; $scope.registrations = registrations; });
'use strict'; angular.module('confRegistrationWebApp') .controller('AdminDataCtrl', function ($scope, registrations, conference) { $scope.conference = conference; $scope.blocks = []; $scope.reversesort = false; angular.forEach(conference.registrationPages, function (page) { angular.forEach(page.blocks, function (block) { if (block.type.indexOf('Content') === -1) { $scope.blocks.push(block); } }); }); $scope.findAnswer = function (registration, blockId) { return _.find(registration.answers, function (answer) { return angular.equals(answer.blockId, blockId); }); }; $scope.getSelectedCheckboxes = function(choices){ var selectedKeys = []; for (var key in choices) { if(choices[key]){ selectedKeys.push(key); } } return selectedKeys; }; $scope.answerSort = function (registration) { if (angular.isDefined($scope.order)) { if (angular.isDefined($scope.findAnswer(registration, $scope.order))) { return $scope.findAnswer(registration, $scope.order).value; } } else { return 0; } }; $scope.setOrder = function (order) { if (order === $scope.order) { $scope.reversesort = !$scope.reversesort; } else { $scope.reversesort = false; } $scope.order = order; }; $scope.registrations = registrations; });
Add updateTaskImplementationCode() method to TaskImplService
package pingis.services; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import pingis.entities.TaskImplementation; import pingis.repositories.TaskImplementationRepository; import pingis.repositories.TaskRepository; import pingis.repositories.UserRepository; @Service public class TaskImplementationService { @Autowired private TaskRepository taskRepository; @Autowired private TaskImplementationRepository taskImplementationRepository; @Autowired private UserRepository userRepository; public TaskImplementation getCorrespondingTestTaskImplementation( TaskImplementation implTaskImplementation) { return taskImplementationRepository. findByTaskAndUser( taskRepository. findByIndexAndChallenge(implTaskImplementation.getTask().getIndex()-1, implTaskImplementation.getTask().getChallenge()), userRepository.findOne(0l)); } public TaskImplementation getCorrespondingImplTaskImplementation(TaskImplementation testTaskImplementation) { return taskImplementationRepository. findByTaskAndUser( taskRepository.findByIndexAndChallenge(testTaskImplementation.getTask().getIndex()+1, testTaskImplementation.getTask().getChallenge()), userRepository.findOne(0l)); } public TaskImplementation findOne(long taskImplementationId) { return taskImplementationRepository.findOne(taskImplementationId); } @Transactional public TaskImplementation updateTaskImplementationCode(Long taskImplementationId, String taskImplementationCode) { TaskImplementation taskImplementationToUpdate = taskImplementationRepository.findOne(taskImplementationId); taskImplementationToUpdate.setCode(taskImplementationCode); return taskImplementationToUpdate; } }
package pingis.services; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import pingis.entities.TaskImplementation; import pingis.repositories.TaskImplementationRepository; import pingis.repositories.TaskRepository; import pingis.repositories.UserRepository; @Service public class TaskImplementationService { @Autowired private TaskRepository taskRepository; @Autowired private TaskImplementationRepository taskImplementationRepository; @Autowired private UserRepository userRepository; public TaskImplementation getCorrespondingTestTaskImplementation( TaskImplementation implTaskImplementation) { return taskImplementationRepository. findByTaskAndUser( taskRepository. findByIndexAndChallenge(implTaskImplementation.getTask().getIndex()-1, implTaskImplementation.getTask().getChallenge()), userRepository.findOne(0l)); } public TaskImplementation getCorrespondingImplTaskImplementation(TaskImplementation testTaskImplementation) { return taskImplementationRepository. findByTaskAndUser( taskRepository.findByIndexAndChallenge(testTaskImplementation.getTask().getIndex()+1, testTaskImplementation.getTask().getChallenge()), userRepository.findOne(0l)); } public TaskImplementation findOne(long taskImplementationId) { return taskImplementationRepository.findOne(taskImplementationId); } }
Add universal_newlines paramter to run call
import discord import asyncio import os import signal import sys from subprocess import run #Set up Client State CLIENT_TOKEN=os.environ['TOKEN'] #Create Discord client client = discord.Client() #Handle shutdown gracefully def sigterm_handler(signum, frame): print('Logging out...', flush=True) raise KeyboardInterrupt print('Shutting down...') sys.exit(0) #Register SIGTERM Handler signal.signal(signal.SIGTERM, sigterm_handler) @client.event async def on_ready(): print('Logged in as') print(client.user.name) print(client.user.id) print('------') @client.event async def on_message(message): #Look at DMs for special commands if message.channel.type == discord.ChannelType.private: if message.content.startswith('!update'): tmp = await client.send_message(message.channel, 'Updating my code via git...') process = run(["sh", "control.sh", "refresh"], universal_newlines=True) tmp = await client.send_message(message.channel, process.stdout) if message.content.startswith('!test'): counter = 0 tmp = await client.send_message(message.channel, 'Calculating messages...') async for log in client.logs_from(message.channel, limit=100): if log.author == message.author: counter += 1 await client.edit_message(tmp, 'You have {} messages.'.format(counter)) #Start event loop client.run(CLIENT_TOKEN)
import discord import asyncio import os import signal import sys from subprocess import run #Set up Client State CLIENT_TOKEN=os.environ['TOKEN'] #Create Discord client client = discord.Client() #Handle shutdown gracefully def sigterm_handler(signum, frame): print('Logging out...', flush=True) raise KeyboardInterrupt print('Shutting down...') sys.exit(0) #Register SIGTERM Handler signal.signal(signal.SIGTERM, sigterm_handler) @client.event async def on_ready(): print('Logged in as') print(client.user.name) print(client.user.id) print('------') @client.event async def on_message(message): #Look at DMs for special commands if message.channel.type == discord.ChannelType.private: if message.content.startswith('!update'): tmp = await client.send_message(message.channel, 'Updating my code via git...') process = run(["sh", "control.sh", "refresh"]) tmp = await client.send_message(message.channel, process.stdout) if message.content.startswith('!test'): counter = 0 tmp = await client.send_message(message.channel, 'Calculating messages...') async for log in client.logs_from(message.channel, limit=100): if log.author == message.author: counter += 1 await client.edit_message(tmp, 'You have {} messages.'.format(counter)) #Start event loop client.run(CLIENT_TOKEN)
Remove the shadow below status bar that occurs in version greater than M.
package com.githang.statusbar; import android.annotation.TargetApi; import android.os.Build; import android.view.View; import android.view.Window; import android.view.WindowManager; /** * 兼容M版本 * * @author 黄浩杭 ([email protected]) * @version 2016-06-20 * @since 2016-06-20 */ class StatusBarCompatM { @TargetApi(Build.VERSION_CODES.M) static void setStatusBarColor(Window window, int color, boolean lightStatusBar) { //取消设置透明状态栏,使 ContentView 内容不再覆盖状态栏 window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色 window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); //设置状态栏颜色 window.setStatusBarColor(color); // 设置浅色状态栏时的界面显示 View decor = window.getDecorView(); int ui = decor.getSystemUiVisibility(); if (lightStatusBar) { ui |=View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR; } else { ui &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR; } decor.setSystemUiVisibility(ui); // 去掉系统状态栏下的windowContentOverlay View v = window.findViewById(android.R.id.content); if (v != null) { v.setForeground(null); } } }
package com.githang.statusbar; import android.annotation.TargetApi; import android.os.Build; import android.view.View; import android.view.Window; import android.view.WindowManager; /** * 兼容M版本 * * @author 黄浩杭 ([email protected]) * @version 2016-06-20 * @since 2016-06-20 */ class StatusBarCompatM { @TargetApi(Build.VERSION_CODES.M) static void setStatusBarColor(Window window, int color, boolean lightStatusBar) { //取消设置透明状态栏,使 ContentView 内容不再覆盖状态栏 window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色 window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); //设置状态栏颜色 window.setStatusBarColor(color); View decor = window.getDecorView(); int ui = decor.getSystemUiVisibility(); if (lightStatusBar) { ui |=View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR; } else { ui &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR; } decor.setSystemUiVisibility(ui); } }
Remove entry point mecodesktop script MacroecoDesktop is now called using the python -c syntax instead of an entry script.
from setuptools import setup, find_packages setup( name = 'macroeco', version = 1.0, packages = find_packages(), # entry_points = {'console_scripts': ['mecodesktop=macroeco:mecodesktop',],}, package_data = {'': ['*.txt', '*.csv']}, author = 'Justin Kitzes and Mark Wilber', author_email = '[email protected]', description = 'Ecological pattern analysis in Python', long_description = open('README.rst').read(), license = 'BSD', keywords = ('ecology biology environment conservation biodiversity ' 'informatics data science'), url = 'http://github.com/jkitzes/macroeco', classifiers = [ "Topic :: Scientific/Engineering :: Bio-Informatics", "Development Status :: 4 - Beta", "Intended Audience :: Science/Research", "License :: OSI Approved :: BSD License", ], install_requires = [ 'numpy>=1.6', 'scipy>=0.12', 'pandas>=0.14', 'matplotlib>=1.3', 'mpmath>=0.19', 'configparser', 'decorator', # 'shapely', # Do not force install if user doesn't have # 'wxpython', ], ) # python setup.py sdist bdist_egg upload -r https://testpypi.python.org/pypi
from setuptools import setup, find_packages setup( name = 'macroeco', version = 1.0, packages = find_packages(), entry_points = {'console_scripts': ['mecodesktop=macroeco:mecodesktop',],}, package_data = {'': ['*.txt', '*.csv']}, author = 'Justin Kitzes and Mark Wilber', author_email = '[email protected]', description = 'Ecological pattern analysis in Python', long_description = open('README.rst').read(), license = 'BSD', keywords = ('ecology biology environment conservation biodiversity ' 'informatics data science'), url = 'http://github.com/jkitzes/macroeco', classifiers = [ "Topic :: Scientific/Engineering :: Bio-Informatics", "Development Status :: 4 - Beta", "Intended Audience :: Science/Research", "License :: OSI Approved :: BSD License", ], install_requires = [ 'numpy>=1.6', 'scipy>=0.12', 'pandas>=0.14', 'matplotlib>=1.3', 'mpmath>=0.19', 'configparser', 'decorator', # 'shapely', # Do not force install if user doesn't have # 'wxpython', ], ) # python setup.py sdist bdist_egg upload -r https://testpypi.python.org/pypi
QS-1341: Make report optional in CardContent
import React, { PropTypes, Component } from 'react'; import CardContent from '../ui/CardContent'; export default class CardContentList extends Component { static propTypes = { contents : PropTypes.array.isRequired, userId : PropTypes.number.isRequired, otherUserId : PropTypes.number, onReport : PropTypes.func, }; constructor(props) { super(props); this.onReport = this.onReport.bind(this); } onReport(contentId, reason) { this.props.onReport(contentId, reason); } render() { const {contents, userId, otherUserId} = this.props; return ( <div className="content-list"> {contents.map((content, index) => <CardContent key={index} hideLikeButton={false} {...content} loggedUserId={userId} otherUserId={otherUserId} embed_id={content.embed ? content.embed.id : null} embed_type={content.embed ? content.embed.type : null} fixedHeight={true} onReport={this.props.onReport ? this.onReport : null}/>)} </div> ); } }
import React, { PropTypes, Component } from 'react'; import CardContent from '../ui/CardContent'; export default class CardContentList extends Component { static propTypes = { contents : PropTypes.array.isRequired, userId : PropTypes.number.isRequired, otherUserId : PropTypes.number, onReport : PropTypes.func, }; constructor(props) { super(props); this.onReport = this.onReport.bind(this); } onReport(contentId, reason) { if (this.props.onReport) { this.props.onReport(contentId, reason); } } render() { const {contents, userId, otherUserId, onClickHandler} = this.props; return ( <div className="content-list"> {contents.map((content, index) => <CardContent key={index} hideLikeButton={false} {...content} loggedUserId={userId} otherUserId={otherUserId} embed_id={content.embed ? content.embed.id : null} embed_type={content.embed ? content.embed.type : null} fixedHeight={true} onReport={this.onReport}/>)} </div> ); } }
Add a test on failed arg introspection in chained decorators This is a consequence of not preserving function signature. So this could be fixed by preserving signature or by some workaround.
import pytest from funcy.decorators import * def test_decorator_no_args(): @decorator def inc(call): return call() + 1 @inc def ten(): return 10 assert ten() == 11 def test_decorator_with_args(): @decorator def add(call, n): return call() + n @add(2) def ten(): return 10 assert ten() == 12 def test_decorator_access_arg(): @decorator def multiply(call): return call() * call.n @multiply def square(n): return n assert square(5) == 25 def test_decorator_access_nonexistent_arg(): @decorator def return_x(call): return call.x @return_x def f(): pass with pytest.raises(AttributeError): f() def test_decorator_with_method(): @decorator def inc(call): return call() + 1 class A(object): def ten(self): return 10 @classmethod def ten_cls(cls): return 10 @staticmethod def ten_static(): return 10 assert inc(A().ten)() == 11 assert inc(A.ten_cls)() == 11 assert inc(A.ten_cls)() == 11 assert inc(A.ten_static)() == 11 @pytest.mark.xfail def test_chain_arg_access(): @decorator def decor(call): return call.x + call() @decor @decor def func(x): return x assert func(2) == 6
import pytest from funcy.decorators import * def test_decorator_no_args(): @decorator def inc(call): return call() + 1 @inc def ten(): return 10 assert ten() == 11 def test_decorator_with_args(): @decorator def add(call, n): return call() + n @add(2) def ten(): return 10 assert ten() == 12 def test_decorator_access_arg(): @decorator def multiply(call): return call() * call.n @multiply def square(n): return n assert square(5) == 25 def test_decorator_access_nonexistent_arg(): @decorator def return_x(call): return call.x @return_x def f(): pass with pytest.raises(AttributeError): f() def test_decorator_with_method(): @decorator def inc(call): return call() + 1 class A(object): def ten(self): return 10 @classmethod def ten_cls(cls): return 10 @staticmethod def ten_static(): return 10 assert inc(A().ten)() == 11 assert inc(A.ten_cls)() == 11 assert inc(A.ten_cls)() == 11 assert inc(A.ten_static)() == 11
Add path_only support to URLArgument
from __future__ import absolute_import import string import urlparse from pale.arguments.string import StringArgument from pale.errors import ArgumentError class URLArgument(StringArgument): path_only = False def validate_url(self, original_string): """Returns the original string if it was valid, raises an argument error if it's not. """ # nipped from stack overflow: http://stackoverflow.com/questions/827557/how-do-you-validate-a-url-with-a-regular-expression-in-python # I preferred this to the thorough regex approach for simplicity and # readability pieces = urlparse.urlparse(original_string) try: if self.path_only: assert not any([pieces.scheme, pieces.netloc]) assert pieces.path else: assert all([pieces.scheme, pieces.netloc]) valid_chars = set(string.letters + string.digits + ":-_.") assert set(pieces.netloc) <= valid_chars assert pieces.scheme in ['http', 'https'] except AssertionError as e: raise ArgumentError(self.item_name, "The input you've provided is not a valid URL.") return original_string def validate(self, item, item_name): self.item_name = item_name item = super(URLArgument, self).validate(item, item_name) if item is not None: item = self.validate_url(item) return item
from __future__ import absolute_import import string import urlparse from pale.arguments.string import StringArgument from pale.errors import ArgumentError class URLArgument(StringArgument): def validate_url(self, original_string): """Returns the original string if it was valid, raises an argument error if it's not. """ # nipped from stack overflow: http://stackoverflow.com/questions/827557/how-do-you-validate-a-url-with-a-regular-expression-in-python # I preferred this to the thorough regex approach for simplicity and # readability pieces = urlparse.urlparse(original_string) try: assert all([pieces.scheme, pieces.netloc]) valid_chars = set(string.letters + string.digits + ":-_.") assert set(pieces.netloc) <= valid_chars assert pieces.scheme in ['http', 'https'] except AssertionError as e: raise ArgumentError(self.item_name, "The input you've provided is not a valid URL.") return original_string def validate(self, item, item_name): self.item_name = item_name item = super(URLArgument, self).validate(item, item_name) if item is not None: item = self.validate_url(item) return item
Make the automatic object transformer able to transform doctrine collections
<?php namespace FOQ\ElasticaBundle\Transformer; use RuntimeException; use Traversable; use ArrayAccess; /** * AutomaticObjectToArrayTransformer * Tries to convert objects by generating getters * based on the required keys */ class ObjectToArrayAutomaticTransformer implements ObjectToArrayTransformerInterface { /** * Transforms an object into an array having the required keys * * @param object $object the object to convert * @param array $requiredKeys the keys we want to have in the returned array * @return array **/ public function transform($object, array $requiredKeys) { $class = get_class($object); $array = array(); foreach ($requiredKeys as $key) { $getter = 'get'.ucfirst($key); if (!method_exists($class, $getter)) { throw new RuntimeException(sprintf('The getter %s::%s does not exist', $class, $getter)); } $array[$key] = $this->normalizeValue($object->$getter()); } return array_filter($array); } public function normalizeValue($value) { if (is_array($value) || $value instanceof Traversable || $value instanceof ArrayAccess) { $values = array(); foreach ($value as $v) { $values[] = (string) $v; } $value = implode(', ', $values); } return (string) $value; } }
<?php namespace FOQ\ElasticaBundle\Transformer; use RuntimeException; use Traversable; /** * AutomaticObjectToArrayTransformer * Tries to convert objects by generating getters * based on the required keys */ class ObjectToArrayAutomaticTransformer implements ObjectToArrayTransformerInterface { /** * Transforms an object into an array having the required keys * * @param object $object the object to convert * @param array $requiredKeys the keys we want to have in the returned array * @return array **/ public function transform($object, array $requiredKeys) { $class = get_class($object); $array = array(); foreach ($requiredKeys as $key) { $getter = 'get'.ucfirst($key); if (!method_exists($class, $getter)) { throw new RuntimeException(sprintf('The getter %s::%s does not exist', $class, $getter)); } $array[$key] = $this->normalizeValue($object->$getter()); } return array_filter($array); } public function normalizeValue($value) { if (is_array($value) || $value instanceof Traversable) { $normalized = ''; foreach ($value as $v) { $normalized .= (string) $v; } } else { $value = (string) $value; } return $value; } }
Use "submission_id" instead of "instance_id" parameter to send to KPI for RESTservice
# coding: utf-8 import logging import re import requests from django.conf import settings from onadata.apps.restservice.RestServiceInterface import RestServiceInterface from onadata.apps.logger.models import Instance class ServiceDefinition(RestServiceInterface): id = 'kpi_hook' verbose_name = 'KPI Hook POST' def send(self, endpoint, data): # Will be used internally by KPI to fetch data with KoBoCatBackend post_data = { 'submission_id': data.get('instance_id') } headers = {'Content-Type': 'application/json'} # Verify if endpoint starts with `/assets/` before sending # the request to KPI pattern = r'{}'.format(settings.KPI_HOOK_ENDPOINT_PATTERN.replace( '{asset_uid}', '[^/]*')) # Match v2 and v1 endpoints. if re.match(pattern, endpoint) or re.match(pattern[7:], endpoint): # Build the url in the service to avoid saving hardcoded # domain name in the DB url = f'{settings.KOBOFORM_INTERNAL_URL}{endpoint}' response = requests.post(url, headers=headers, json=post_data) response.raise_for_status() # Save successful Instance.objects.filter(pk=data.get('instance_id')).update( posted_to_kpi=True ) else: logging.warning( f'This endpoint: `{endpoint}` is not valid for `KPI Hook`' )
# coding: utf-8 import logging import re import requests from django.conf import settings from onadata.apps.restservice.RestServiceInterface import RestServiceInterface from onadata.apps.logger.models import Instance class ServiceDefinition(RestServiceInterface): id = 'kpi_hook' verbose_name = 'KPI Hook POST' def send(self, endpoint, data): # Will be used internally by KPI to fetch data with KoBoCatBackend post_data = { 'instance_id': data.get('instance_id') } headers = {'Content-Type': 'application/json'} # Verify if endpoint starts with `/assets/` before sending # the request to KPI pattern = r'{}'.format(settings.KPI_HOOK_ENDPOINT_PATTERN.replace( '{asset_uid}', '[^/]*')) # Match v2 and v1 endpoints. if re.match(pattern, endpoint) or re.match(pattern[7:], endpoint): # Build the url in the service to avoid saving hardcoded # domain name in the DB url = f'{settings.KOBOFORM_INTERNAL_URL}{endpoint}' response = requests.post(url, headers=headers, json=post_data) response.raise_for_status() # Save successful Instance.objects.filter(pk=data.get('instance_id')).update( posted_to_kpi=True ) else: logging.warning( f'This endpoint: `{endpoint}` is not valid for `KPI Hook`' )
Use finally to clean up (hello @sunesimonsen).
var mockfs = require('mock-fs'); var fs = require('fs'); var MountFs = require('mountfs'); var rewriteMockFsOptions = require('./lib/rewriteMockFsOptions'); module.exports = { name: 'unexpected-fs', installInto: function (expect) { expect.addAssertion('with fs mocked out', function (expect, subject, value) { this.errorMode = 'bubble'; var extraArgs = Array.prototype.slice.call(arguments, 3); var mockFileSystems = Object.keys(value).map(function (key) { var mockFsConfig = rewriteMockFsOptions(value[key]); return { mountPath: /\/$/.test(key) ? key : key + '/', fileSystem: mockfs.fs(mockFsConfig) }; }); return expect.promise(function () { MountFs.patchInPlace(); mockFileSystems.forEach(function (mockFileSystem) { fs.mount(mockFileSystem.mountPath, mockFileSystem.fileSystem); }); return expect.apply(expect, [subject].concat(extraArgs)); }).finally(function () { mockFileSystems.forEach(function (mockFs) { fs.unmount(mockFs.mountPath); }); fs.unpatch(); }); }); } };
var mockfs = require('mock-fs'); var fs = require('fs'); var MountFs = require('mountfs'); var rewriteMockFsOptions = require('./lib/rewriteMockFsOptions'); module.exports = { name: 'unexpected-fs', installInto: function (expect) { expect.addAssertion('with fs mocked out', function (expect, subject, value) { this.errorMode = 'bubble'; var extraArgs = Array.prototype.slice.call(arguments, 3); var mockFileSystems = Object.keys(value).map(function (key) { var mockFsConfig = rewriteMockFsOptions(value[key]); return { mountPath: /\/$/.test(key) ? key : key + '/', fileSystem: mockfs.fs(mockFsConfig) }; }); var unmountAllMocks = function () { mockFileSystems.forEach(function (mockFs) { fs.unmount(mockFs.mountPath); }); fs.unpatch(); }; return expect.promise(function () { MountFs.patchInPlace(); mockFileSystems.forEach(function (mockFileSystem) { fs.mount(mockFileSystem.mountPath, mockFileSystem.fileSystem); }); return expect.apply(expect, [subject].concat(extraArgs)); }).then(function () { unmountAllMocks(); }).caught(function (err) { unmountAllMocks(); throw err; }); }); } };
Throw separate exception for each failed doc Sentry will `{clipped}` your exception if it's too long.
<?php namespace App; use Exception; use ScoutEngines\Elasticsearch\ElasticsearchEngine as BaseEngine; class ElasticsearchEngine extends BaseEngine { /** * Update the given model in the index. * * @param Collection $models * @return void */ public function update($models) { $params['body'] = []; $models->each(function($model) use (&$params) { $params['body'][] = [ 'update' => $this->getIdIndexType($model) ]; $params['body'][] = [ 'doc' => $model->toSearchableArray(), 'doc_as_upsert' => true ]; }); $result = $this->elastic->bulk($params); // TODO: Requeue only the models that failed? if (isset($result['errors']) && $result['errors'] === true) { $failedDocs = array_values(array_filter($result['items'], function($item) { return isset($item['update']['error']); })); foreach ($failedDocs as $doc) { try { throw new Exception(json_encode($doc)); } catch (Exception $e) { // https://laravel.com/docs/5.7/errors - The `report` Helper report($e); } } } } }
<?php namespace App; use Exception; use ScoutEngines\Elasticsearch\ElasticsearchEngine as BaseEngine; class ElasticsearchEngine extends BaseEngine { /** * Update the given model in the index. * * @param Collection $models * @return void */ public function update($models) { $params['body'] = []; $models->each(function($model) use (&$params) { $params['body'][] = [ 'update' => $this->getIdIndexType($model) ]; $params['body'][] = [ 'doc' => $model->toSearchableArray(), 'doc_as_upsert' => true ]; }); $result = $this->elastic->bulk($params); // TODO: Requeue only the models that failed? if (isset($result['errors']) && $result['errors'] === true) { try { // Filter out docs that succeeded throw new Exception(json_encode(array_values(array_filter($result['items'], function($item) { return isset($item['update']['error']); })))); } catch (Exception $e) { // https://laravel.com/docs/5.7/errors - The `report` Helper report($e); } } } }
Handle stack variation in Node v0.8
var tape = require('../'); var tap = require('tap'); var concat = require('concat-stream'); var stripFullStack = require('./common').stripFullStack; var testWrapper = require('./anonymous-fn/test-wrapper'); tap.test('inside anonymous functions', function (tt) { tt.plan(1); var test = tape.createHarness(); var tc = function (rows) { var body = stripFullStack(rows.toString('utf8')); // Handle stack trace variation in Node v0.8 body = body.replace( 'at Test.module.exports', 'at Test.<anonymous>' ); tt.same(body, [ 'TAP version 13', '# wrapped test failure', 'not ok 1 fail', ' ---', ' operator: fail', ' at: <anonymous> ($TEST/anonymous-fn.js:$LINE:$COL)', ' stack: |-', ' Error: fail', ' [... stack stripped ...]', ' at $TEST/anonymous-fn.js:$LINE:$COL', ' at Test.<anonymous> ($TEST/anonymous-fn/test-wrapper.js:$LINE:$COL)', ' [... stack stripped ...]', ' ...', '', '1..1', '# tests 1', '# pass 0', '# fail 1' ].join('\n') + '\n'); }; test.createStream().pipe(concat(tc)); test('wrapped test failure', testWrapper(function (t) { t.fail('fail'); t.end(); })); });
var tape = require('../'); var tap = require('tap'); var concat = require('concat-stream'); var stripFullStack = require('./common').stripFullStack; var testWrapper = require('./anonymous-fn/test-wrapper'); tap.test('inside anonymous functions', function (tt) { tt.plan(1); var test = tape.createHarness(); var tc = function (rows) { tt.same(stripFullStack(rows.toString('utf8')), [ 'TAP version 13', '# wrapped test failure', 'not ok 1 fail', ' ---', ' operator: fail', ' at: <anonymous> ($TEST/anonymous-fn.js:$LINE:$COL)', ' stack: |-', ' Error: fail', ' [... stack stripped ...]', ' at $TEST/anonymous-fn.js:$LINE:$COL', ' at Test.<anonymous> ($TEST/anonymous-fn/test-wrapper.js:$LINE:$COL)', ' [... stack stripped ...]', ' ...', '', '1..1', '# tests 1', '# pass 0', '# fail 1' ].join('\n') + '\n'); }; test.createStream().pipe(concat(tc)); test('wrapped test failure', testWrapper(function (t) { t.fail('fail'); t.end(); })); });
Select complete textbox content on click
document.addEventListener("DOMContentLoaded", function () { var qr_cellsize = 8; var qr_margin = 2 * qr_cellsize; var qr_levels = ["M", "L"]; var createImage = function(payload) { for (var levelIndex in qr_levels) { for (var typeNum = 1; typeNum <= 10; typeNum++) { try { var qr = qrcode(typeNum, qr_levels[levelIndex]); qr.addData(payload); qr.make(); return qr.createImgTag(qr_cellsize, qr_margin); } catch(e) { if (strStartsWith(e.message, "code length overflow")) { // ignore and try to use bigger QR code format } else { throw e; } } } } }; var updateImage = function() { payload = document.getElementById("textbox").value; document.getElementById("insert-qrcode-here").innerHTML = createImage(payload) || "Error. URL too long?"; }; var strStartsWith = function(string, prefix) { return !string.indexOf(prefix); }; document.getElementById("close").onclick = function() { window.close(); }; document.getElementById("textbox").onchange = function() { updateImage(); }; document.getElementById("textbox").onclick = function() { this.select(); }; chrome.tabs.getSelected(null, function(tab) { document.getElementById("textbox").value = tab.url; document.getElementById("textbox").select(); updateImage(); }); });
document.addEventListener("DOMContentLoaded", function () { var qr_cellsize = 8; var qr_margin = 2 * qr_cellsize; var qr_levels = ["M", "L"]; var createImage = function(payload) { for (var levelIndex in qr_levels) { for (var typeNum = 1; typeNum <= 10; typeNum++) { try { var qr = qrcode(typeNum, qr_levels[levelIndex]); qr.addData(payload); qr.make(); return qr.createImgTag(qr_cellsize, qr_margin); } catch(e) { if (strStartsWith(e.message, "code length overflow")) { // ignore and try to use bigger QR code format } else { throw e; } } } } }; var updateImage = function() { payload = document.getElementById("textbox").value; document.getElementById("insert-qrcode-here").innerHTML = createImage(payload) || "Error. URL too long?"; }; var strStartsWith = function(string, prefix) { return !string.indexOf(prefix); }; document.getElementById("close").onclick = function() { window.close(); }; document.getElementById("textbox").onchange = function() { updateImage(); }; chrome.tabs.getSelected(null, function(tab) { document.getElementById("textbox").value = tab.url; document.getElementById("textbox").select(); updateImage(); }); });
Stop sending request immediately, instead, sending the request if user stops changing the value for some time.
import React, { Component } from 'react'; import UserList from './UserList'; import LocationBox from './LocationBox'; import $ from 'jquery'; module.exports = React.createClass({ getInitialState: function() { return { location: 'Shanghai', pendingSearch: null, users: [] }; }, searchUsers: function(location) { this.setState({pendingSearch: null}); //var url = `https://api.github.com/search/users?q=location:${location}+repos:>=10`; var url = `/assets/${location}.json`; console.log('event=search_users url=%s', url); $.ajax({ url: url, dataType: 'json', cache: false, username: this.props.username, password: this.props.password, success: function(data) { this.setState({users: data.items}); }.bind(this), error: function(xhr, status, err) { console.error(url, status, err.toString()); }.bind(this) }); }, componentDidMount: function() { this.searchUsers(this.state.location); }, handleLocationChange: function(location) { if(this.state.pendingSearch) { clearTimeout(this.state.pendingSearch); } var that = this; var pendingSearch = setTimeout(function() {that.searchUsers(location)}, 500); this.setState({location: location, pendingSearch: pendingSearch}); }, render: function() { return ( <div> <LocationBox location={this.state.location} onUserInput={this.handleLocationChange}/> <UserList users={this.state.users} /> </div> ); } });
import React, { Component } from 'react'; import UserList from './UserList'; import LocationBox from './LocationBox'; import $ from 'jquery'; module.exports = React.createClass({ getInitialState: function() { return { location: 'Shanghai', users: [] }; }, searchUsers: function(location) { var url = `https://api.github.com/search/users?q=location:${location}+repos:>=10`; //var url = `/assets/${location}.json`; console.log('event=search_users url=%s', url); $.ajax({ url: url, dataType: 'json', cache: false, username: this.props.username, password: this.props.password, success: function(data) { this.setState({users: data.items}); }.bind(this), error: function(xhr, status, err) { console.error(url, status, err.toString()); }.bind(this) }); }, componentDidMount: function() { this.searchUsers(this.state.location); }, handleLocationChange: function(location) { this.setState({location: location}); this.searchUsers(this.state.location); }, render: function() { return ( <div> <LocationBox location={this.state.location} onUserInput={this.handleLocationChange}/> <UserList users={this.state.users} /> </div> ); } });
Fix typo in sandbox attribute name.
import logging logger = logging.getLogger(__name__) # Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#attr-sandbox allowable_sandbox_tokens = set( [ "allow-downloads-without-user-activation", "allow-forms", "allow-modals", "allow-orientation-lock", "allow-pointer-lock", "allow-popups", "allow-popups-to-escape-sandbox", "allow-presentation", "allow-same-origin", "allow-scripts", "allow-storage-access-by-user-activation", "allow-top-navigation", "allow-top-navigation-by-user-activation", ] ) def clean_sandbox(sandbox_string): """ Clean up sandbox string to ensure it only contains valid items. """ sandbox_tokens = [] illegal_tokens = [] for token in sandbox_string.split(" "): if token in allowable_sandbox_tokens: sandbox_tokens.append(token) else: illegal_tokens.append(token) if illegal_tokens: logger.warn( "Invalid sandbox token passed to options {}".format( " ".join(illegal_tokens) ) ) return " ".join(sandbox_tokens) option_spec = { "HTML5": { "SANDBOX": { "type": "string", "default": "allow-scripts", "envvars": ("KOLIBRI_HTML5_SANDBOX",), "clean": clean_sandbox, } } }
import logging logger = logging.getLogger(__name__) # Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#attr-sandbox allowable_sandbox_tokens = set( [ "allow-downloads-without-user-activation", "allow-forms", "allow-modals", "allow-orientation-lock", "allow-pointer-lock", "allow-popups", "allow-popups-to-escape-sandbox", "allow-presentation", "allow-same-origin", "allow-scripts", "allow-storage-access-by-user-activation ", "allow-top-navigation", "allow-top-navigation-by-user-activation", ] ) def clean_sandbox(sandbox_string): """ Clean up sandbox string to ensure it only contains valid items. """ sandbox_tokens = [] illegal_tokens = [] for token in sandbox_string.split(" "): if token in allowable_sandbox_tokens: sandbox_tokens.append(token) else: illegal_tokens.append(token) if illegal_tokens: logger.warn( "Invalid sandbox token passed to options {}".format( " ".join(illegal_tokens) ) ) return " ".join(sandbox_tokens) option_spec = { "HTML5": { "SANDBOX": { "type": "string", "default": "allow-scripts", "envvars": ("KOLIBRI_HTML5_SANDBOX",), "clean": clean_sandbox, } } }
Fix css and fix small typo in installer
define(function(require, exports, module) { main.consumes = ["Plugin", "installer", "c9"]; main.provides = ["installer.darwin"]; return main; function main(options, imports, register) { var Plugin = imports.Plugin; var installer = imports.installer; var c9 = imports.c9; var bashBin = options.bashBin || "bash"; var plugin = new Plugin("Ajax.org", main.consumes); /** * Installs a .deb package */ function execute(task, options, onData, callback) { installer.ptyExec({ name: "Darwin", bash: bashBin, code: require("text!./darwin.sh"), args: [task], cwd: options.cwd, }, onData, callback); } function isAvailable(callback){ return callback(c9.platform == "darwin"); } plugin.on("load", function() { installer.addPackageManager("darwin", plugin); installer.addPackageManagerAlias("darwin", "osx"); }); plugin.on("unload", function() { installer.removePackageManager("darwin"); }); plugin.freezePublicAPI({ execute: execute, isAvailable: isAvailable }); register(null, { "installer.darwin": plugin }); } });
define(function(require, exports, module) { main.consumes = ["Plugin", "installer", "c9"]; main.provides = ["installer.darwin"]; return main; function main(options, imports, register) { var Plugin = imports.Plugin; var installer = imports.installer; var c9 = imports.c9; var bashBin = options.bashBin || "bash"; var plugin = new Plugin("Ajax.org", main.consumes); /** * Installs a .deb package */ function execute(task, options, onData, callback) { installer.ptyExec({ name: "Darwin", bash: bashBin, code: require("text!./brew.sh"), args: [task], cwd: options.cwd, }, onData, callback); } function isAvailable(callback){ return callback(c9.platform == "darwin"); } plugin.on("load", function() { installer.addPackageManager("darwin", plugin); installer.addPackageManagerAlias("darwin", "osx"); }); plugin.on("unload", function() { installer.removePackageManager("darwin"); }); plugin.freezePublicAPI({ execute: execute, isAvailable: isAvailable }); register(null, { "installer.darwin": plugin }); } });
Add a fix for Safari to the default config Uglifying ES6 doesn't work currently with Safari due to a webkit bug. Adding this mangle option fixes that.
'use strict'; module.exports = { name: 'ember-cli-uglify', included(app) { this._super.included.apply(this, arguments); const defaults = require('lodash.defaultsdeep'); let defaultOptions = { enabled: app.env === 'production', uglify: { compress: { // this is adversely affects heuristics for IIFE eval 'negate_iife': false, // limit sequences because of memory issues during parsing sequences: 30, }, mangle: { safari10: true }, output: { // no difference in size and much easier to debug semicolons: false, }, } }; if (app.options.sourcemaps && !this._sourceMapsEnabled(app.options.sourcemaps)) { defaultOptions.uglify.sourceMap = false; } this._options = defaults(app.options['ember-cli-uglify'] || {}, defaultOptions); }, _sourceMapsEnabled(options) { if (options.enabled === false) { return false; } let extensions = options.extensions || []; if (extensions.indexOf('js') === -1) { return false; } return true; }, postprocessTree(type, tree) { if (this._options.enabled === true && type === 'all') { return require('broccoli-uglify-sourcemap')(tree, this._options); } else { return tree; } } };
'use strict'; module.exports = { name: 'ember-cli-uglify', included(app) { this._super.included.apply(this, arguments); const defaults = require('lodash.defaultsdeep'); let defaultOptions = { enabled: app.env === 'production', uglify: { compress: { // this is adversely affects heuristics for IIFE eval 'negate_iife': false, // limit sequences because of memory issues during parsing sequences: 30, }, output: { // no difference in size and much easier to debug semicolons: false, }, } }; if (app.options.sourcemaps && !this._sourceMapsEnabled(app.options.sourcemaps)) { defaultOptions.uglify.sourceMap = false; } this._options = defaults(app.options['ember-cli-uglify'] || {}, defaultOptions); }, _sourceMapsEnabled(options) { if (options.enabled === false) { return false; } let extensions = options.extensions || []; if (extensions.indexOf('js') === -1) { return false; } return true; }, postprocessTree(type, tree) { if (this._options.enabled === true && type === 'all') { return require('broccoli-uglify-sourcemap')(tree, this._options); } else { return tree; } } };
Use triple equals for argument sniffing in proxy function; this lets "null" clear a style on when using 2 arguments
// From jQuery (src/css.js) var cssNumber = { boxFlex: true, columnCount: true, fillOpacity: true, fontWeight: true, lineHeight: true, opacity: true, orphans: true, widows: true, zIndex: true, zoom: true }; function camelCase(prop){ return prop.replace(/-[a-z]/g, function(match){ return match[1].toUpperCase(); }); } function Style(el){ var computed; function read(prop){ if (computed == undefined) computed = root.getComputedStyle(el); var value = computed.getPropertyValue(prop); return value === '' || value === null ? undefined : value; } function write(prop, value){ if (!cssNumber[prop] && typeof value == 'number') value += 'px'; // pixelify value el.style[prop] = value; computed = null; // clear computed cache } function proxy(prop, rules){ if (rules === undefined) { if (typeof prop == 'string') return read(prop); else for (var i in prop) write(camelCase(i), prop[i]); } else { write(camelCase(prop), rules); } }; proxy.unitless = proxy.u = function(prop){ return parseFloat(read(prop), 10) || 0; }; return proxy; } Style.VERSION = '0.0.1'; root.Style = root.S = Style;
// From jQuery (src/css.js) var cssNumber = { boxFlex: true, columnCount: true, fillOpacity: true, fontWeight: true, lineHeight: true, opacity: true, orphans: true, widows: true, zIndex: true, zoom: true }; function camelCase(prop){ return prop.replace(/-[a-z]/g, function(match){ return match[1].toUpperCase(); }); } function Style(el){ var computed; function read(prop){ if (computed == undefined) computed = root.getComputedStyle(el); var value = computed.getPropertyValue(prop); return value === '' || value === null ? undefined : value; } function write(prop, value){ if (!cssNumber[prop] && typeof value == 'number') value += 'px'; // pixelify value el.style[prop] = value; computed = null; // clear computed cache } function proxy(prop, rules){ if (rules == undefined) { if (typeof prop == 'string') return read(prop); else for (var i in prop) write(camelCase(i), prop[i]); } else { write(camelCase(prop), rules); } }; proxy.unitless = proxy.u = function(prop){ return parseFloat(read(prop), 10) || 0; }; return proxy; } Style.VERSION = '0.0.1'; root.Style = root.S = Style;
ZON-3409: Update to version with celery.
from setuptools import setup, find_packages setup( name='zeit.campus', version='1.6.4.dev0', author='Zeit Online', author_email='[email protected]', url='http://www.zeit.de/', description="vivi section Campus", packages=find_packages('src'), package_dir={'': 'src'}, include_package_data=True, zip_safe=False, license='BSD', namespace_packages=['zeit'], install_requires=[ 'grokcore.component', 'gocept.httpserverlayer', 'gocept.selenium', 'mock', 'plone.testing', 'setuptools', 'zeit.cms >= 3.0.dev0', 'zeit.content.article', 'zeit.content.cp', 'zeit.content.gallery', 'zeit.content.infobox', 'zeit.content.link', 'zeit.edit', 'zeit.push>=1.13.0.dev0', 'zope.component', 'zope.interface', 'zope.schema', ], entry_points={ 'fanstatic.libraries': [ 'zeit_campus=zeit.campus' '.browser.resources:lib', ], }, )
from setuptools import setup, find_packages setup( name='zeit.campus', version='1.6.4.dev0', author='Zeit Online', author_email='[email protected]', url='http://www.zeit.de/', description="vivi section Campus", packages=find_packages('src'), package_dir={'': 'src'}, include_package_data=True, zip_safe=False, license='BSD', namespace_packages=['zeit'], install_requires=[ 'grokcore.component', 'gocept.httpserverlayer', 'gocept.selenium', 'mock', 'plone.testing', 'setuptools', 'zeit.cms>=2.88.0.dev0', 'zeit.content.article', 'zeit.content.cp', 'zeit.content.gallery', 'zeit.content.infobox', 'zeit.content.link', 'zeit.edit', 'zeit.push>=1.13.0.dev0', 'zope.component', 'zope.interface', 'zope.schema', ], entry_points={ 'fanstatic.libraries': [ 'zeit_campus=zeit.campus' '.browser.resources:lib', ], }, )
Clarify current model of time series scoring
package macrobase.analysis.outlier; import java.util.List; import macrobase.conf.MacroBaseConf; import macrobase.conf.MacroBaseDefaults; import macrobase.datamodel.Datum; public abstract class TimeSeriesOutlierDetector extends OutlierDetector { protected final int tupleWindowSize; private int currentTupleWindowSize; public TimeSeriesOutlierDetector(MacroBaseConf conf) { super(conf); this.tupleWindowSize = conf.getInt(MacroBaseConf.TUPLE_WINDOW, MacroBaseDefaults.TUPLE_WINDOW); assert tupleWindowSize > 1; } public abstract void addToWindow(Datum datum); public abstract void removeLastFromWindow(); /** * Use the current window to build a model and then score the latest datum. */ public abstract double scoreWindow(); @Override public void train(List<Datum> data) { // Just sanity checks - we don't actually compute anything in train, // since we train as we go while scoring. assert data.size() >= tupleWindowSize; assert data.get(0).getTime() != null; } @Override public double score(Datum datum) { /* * Note: we assume score is called with data in order - this is true for * batch analysis. Somewhat hacky but allows us to maintain * compatibility with OutlierDetector. */ if (currentTupleWindowSize == tupleWindowSize) { currentTupleWindowSize--; removeLastFromWindow(); } currentTupleWindowSize++; addToWindow(datum); return scoreWindow(); } @Override public double getZScoreEquivalent(double zscore) { return 0; } }
package macrobase.analysis.outlier; import java.util.List; import macrobase.conf.MacroBaseConf; import macrobase.conf.MacroBaseDefaults; import macrobase.datamodel.Datum; public abstract class TimeSeriesOutlierDetector extends OutlierDetector { protected final int tupleWindowSize; private int currentTupleWindowSize; public TimeSeriesOutlierDetector(MacroBaseConf conf) { super(conf); this.tupleWindowSize = conf.getInt(MacroBaseConf.TUPLE_WINDOW, MacroBaseDefaults.TUPLE_WINDOW); assert tupleWindowSize > 1; } public abstract void addToWindow(Datum datum); public abstract void removeLastFromWindow(); // Score current window. public abstract double scoreWindow(); @Override public void train(List<Datum> data) { // Just sanity checks - we don't actually compute anything in train, // since we train as we go while scoring. assert data.size() >= tupleWindowSize; assert data.get(0).getTime() != null; } @Override public double score(Datum datum) { /* * Note: we assume score is called with data in order - this is true for * batch analysis. Somewhat hacky but allows us to maintain * compatibility with OutlierDetector. */ if (currentTupleWindowSize == tupleWindowSize) { currentTupleWindowSize--; removeLastFromWindow(); } currentTupleWindowSize++; addToWindow(datum); return scoreWindow(); } @Override public double getZScoreEquivalent(double zscore) { return 0; } }
Call session_write_close() when saving session
<?php declare(strict_types=1); namespace Vision\Session\Extension; use Vision\Session\SessionInterface; use SessionHandlerInterface; use RuntimeException; class NativeExtension implements ExtensionInterface { private $started = false; public function __construct(SessionHandlerInterface $handler = null) { if (isset($handler)) { session_set_save_handler($handler, true); } } /** * @throws RuntimeException */ public function start(SessionInterface $session): void { if ($this->started && $this->isActive()) { return; } if (!session_start()) { throw new RuntimeException('Session could not be started.'); } $session->exchangeArray($_SESSION); $this->started = true; } public function save(SessionInterface $session) { $this->start($session); $_SESSION = $session->getArrayCopy(); session_write_close(); } public function isStarted(): bool { return $this->started; } public function isActive(): bool { return $this->getStatus() === PHP_SESSION_ACTIVE; } public function getStatus(): int { return session_status(); } public function getId(): string { return session_id(); } public function regenerateId(bool $deleteOldSession = true): bool { return session_regenerate_id($deleteOldSession); } }
<?php declare(strict_types=1); namespace Vision\Session\Extension; use Vision\Session\SessionInterface; use SessionHandlerInterface; use RuntimeException; class NativeExtension implements ExtensionInterface { private $started = false; public function __construct(SessionHandlerInterface $handler = null) { if (isset($handler)) { session_set_save_handler($handler, true); } } /** * @throws RuntimeException */ public function start(SessionInterface $session): void { if ($this->started && $this->isActive()) { return; } if (!session_start()) { throw new RuntimeException('Session could not be started.'); } $session->exchangeArray($_SESSION); $this->started = true; } public function save(SessionInterface $session) { $this->start($session); $_SESSION = $session->getArrayCopy(); } public function isStarted(): bool { return $this->started; } public function isActive(): bool { return $this->getStatus() === PHP_SESSION_ACTIVE; } public function getStatus(): int { return session_status(); } public function getId(): string { return session_id(); } public function regenerateId(bool $deleteOldSession = true): bool { return session_regenerate_id($deleteOldSession); } }
Fix self.model is not set.
import importlib import logging from volttron.platform.agent import utils _log = logging.getLogger(__name__) utils.setup_logging() __version__ = "0.1" __all__ = ['Model'] class Model(object): def __init__(self, config, **kwargs): self.model = None config = self.store_model_config(config) if not config: return base_module = "volttron.pnnl.models." try: model_type = config["model_type"] except KeyError as e: _log.exception("Missing Model Type key: {}".format(e)) raise e _file, model_type = model_type.split(".") module = importlib.import_module(base_module + _file) self.model_class = getattr(module, model_type) self.model = self.model_class(config, self) def get_q(self, _set, sched_index, market_index, occupied): q = self.model.predict(_set, sched_index, market_index, occupied) return q def store_model_config(self, _config): try: config = self.vip.config.get("model") except KeyError: config = {} try: self.vip.config.set("model", _config, send_update=False) except RuntimeError: _log.debug("Cannot change config store on config callback!") _config.update(config) return _config
import importlib import logging from volttron.platform.agent import utils _log = logging.getLogger(__name__) utils.setup_logging() __version__ = "0.1" __all__ = ['Model'] class Model(object): def __init__(self, config, **kwargs): self.model = None config = self.store_model_config(config) if not config: return base_module = "volttron.pnnl.models." try: model_type = config["model_type"] except KeyError as e: _log.exception("Missing Model Type key: {}".format(e)) raise e _file, model_type = model_type.split(".") module = importlib.import_module(base_module + _file) self.model_class = getattr(module, model_type) def get_q(self, _set, sched_index, market_index, occupied): q = self.model.predict(_set, sched_index, market_index, occupied) return q def store_model_config(self, _config): try: config = self.vip.config.get("model") except KeyError: config = {} try: self.vip.config.set("model", _config, send_update=False) except RuntimeError: _log.debug("Cannot change config store on config callback!") _config.update(config) return _config
Install requirements depending on python version
import sys from setuptools import setup, find_packages install_requires = [ 'prompt_toolkit', 'python-keystoneclient' ] test_requires = [] if sys.version_info[0] == 2: install_requires.append('pathlib') test_requires.append('mock') setup( name='contrail-api-cli', version='0.1a2', description="Simple CLI program to browse Contrail API server", long_description=open('README.md').read(), author="Jean-Philippe Braun", author_email="[email protected]", maintainer="Jean-Philippe Braun", maintainer_email="[email protected]", url="http://www.github.com/eonpatapon/contrail-api-cli", packages=find_packages(), include_package_data=True, install_requires=install_requires, scripts=[], license="MIT", entry_points={ 'console_scripts': [ 'contrail-api-cli = contrail_api_cli.prompt:main' ], 'keystoneclient.auth.plugin': [ 'http = contrail_api_cli.auth:HTTPAuth' ] }, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Software Development :: User Interfaces', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4' ], keywords='contrail api cli', tests_require=test_requires, test_suite="contrail_api_cli.tests" )
from setuptools import setup, find_packages install_requires = [ 'prompt_toolkit', 'pathlib', 'python-keystoneclient' ] test_requires = [ 'mock' ] setup( name='contrail-api-cli', version='0.1a2', description="Simple CLI program to browse Contrail API server", long_description=open('README.md').read(), author="Jean-Philippe Braun", author_email="[email protected]", maintainer="Jean-Philippe Braun", maintainer_email="[email protected]", url="http://www.github.com/eonpatapon/contrail-api-cli", packages=find_packages(), include_package_data=True, install_requires=install_requires, scripts=[], license="MIT", entry_points={ 'console_scripts': [ 'contrail-api-cli = contrail_api_cli.prompt:main' ], 'keystoneclient.auth.plugin': [ 'http = contrail_api_cli.auth:HTTPAuth' ] }, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Software Development :: User Interfaces', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4' ], keywords='contrail api cli', tests_require=test_requires, test_suite="contrail_api_cli.tests" )
Fix HTTP error code when bad authentication to 401 …instead of 400/404, so client can deal with it correctly (#537)
<?php namespace App\Http\Middleware; use Closure; use Tymon\JWTAuth\Exceptions\JWTException; use Tymon\JWTAuth\Exceptions\TokenExpiredException; class GetUserFromToken extends BaseMiddleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * * @return mixed */ public function handle($request, Closure $next) { if (!$token = $this->auth->setRequest($request)->getToken()) { return $this->respond('tymon.jwt.absent', 'token_not_provided', 401); } try { $user = $this->auth->authenticate($token); } catch (TokenExpiredException $e) { return $this->respond('tymon.jwt.expired', 'token_expired', $e->getStatusCode(), [$e]); } catch (JWTException $e) { return $this->respond('tymon.jwt.invalid', 'token_invalid', $e->getStatusCode(), [$e]); } if (!$user) { return $this->respond('tymon.jwt.user_not_found', 'user_not_found', 401); } $this->events->fire('tymon.jwt.valid', $user); return $next($request); } }
<?php namespace App\Http\Middleware; use Closure; use Tymon\JWTAuth\Exceptions\JWTException; use Tymon\JWTAuth\Exceptions\TokenExpiredException; class GetUserFromToken extends BaseMiddleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * * @return mixed */ public function handle($request, Closure $next) { if (!$token = $this->auth->setRequest($request)->getToken()) { return $this->respond('tymon.jwt.absent', 'token_not_provided', 400); } try { $user = $this->auth->authenticate($token); } catch (TokenExpiredException $e) { return $this->respond('tymon.jwt.expired', 'token_expired', $e->getStatusCode(), [$e]); } catch (JWTException $e) { return $this->respond('tymon.jwt.invalid', 'token_invalid', $e->getStatusCode(), [$e]); } if (!$user) { return $this->respond('tymon.jwt.user_not_found', 'user_not_found', 404); } $this->events->fire('tymon.jwt.valid', $user); return $next($request); } }
Change config security pass env variable to meet standard naming convention
package com.hpe.caf.cipher.jasypt; import com.hpe.caf.api.BootstrapConfiguration; import com.hpe.caf.api.Cipher; import com.hpe.caf.api.CipherException; import com.hpe.caf.api.ConfigurationException; import org.jasypt.util.text.BasicTextEncryptor; /** * Implementation of a SecurityProvider that uses Jasypt to provide basic * text encryption/decryption capabilities. The strong encryptor is not used * to avoid licensing/export issues. */ public class JasyptCipher implements Cipher { /** * The keyword used to encrypt and decrypt data. */ public static final String CONFIG_SECURITY_PASS = "CIPHER_PASS"; /** * This is PBE with MD5 and DES encryption. */ private final BasicTextEncryptor codec = new BasicTextEncryptor(); /** * {@inheritDoc} * * The cipher.pass variable must be present in the bootstrap configuration for this provider to init. */ public JasyptCipher(final BootstrapConfiguration bootstrap) throws CipherException { try { codec.setPassword(bootstrap.getConfiguration(CONFIG_SECURITY_PASS)); } catch (ConfigurationException e) { throw new CipherException("Configuration " + CONFIG_SECURITY_PASS + " not set", e); } } @Override public String decrypt(final String input) { return codec.decrypt(input); } @Override public String encrypt(final String input) { return codec.encrypt(input); } }
package com.hpe.caf.cipher.jasypt; import com.hpe.caf.api.BootstrapConfiguration; import com.hpe.caf.api.Cipher; import com.hpe.caf.api.CipherException; import com.hpe.caf.api.ConfigurationException; import org.jasypt.util.text.BasicTextEncryptor; /** * Implementation of a SecurityProvider that uses Jasypt to provide basic * text encryption/decryption capabilities. The strong encryptor is not used * to avoid licensing/export issues. */ public class JasyptCipher implements Cipher { /** * The keyword used to encrypt and decrypt data. */ public static final String CONFIG_SECURITY_PASS = "cipher.pass"; /** * This is PBE with MD5 and DES encryption. */ private final BasicTextEncryptor codec = new BasicTextEncryptor(); /** * {@inheritDoc} * * The cipher.pass variable must be present in the bootstrap configuration for this provider to init. */ public JasyptCipher(final BootstrapConfiguration bootstrap) throws CipherException { try { codec.setPassword(bootstrap.getConfiguration(CONFIG_SECURITY_PASS)); } catch (ConfigurationException e) { throw new CipherException("Configuration " + CONFIG_SECURITY_PASS + " not set", e); } } @Override public String decrypt(final String input) { return codec.decrypt(input); } @Override public String encrypt(final String input) { return codec.encrypt(input); } }
Add reference for phantomJSPath option In certain instances, it seems building the phantomjs server the path to the binary is not always correct and seems to default to /usr/local/bin. Setting the value exclusively should resolve this.
var path = require("path"), childProcess = require('child_process'), phantomjs = require('phantomjs'), fs = require("fs"); module.exports = function(options, html, id, cb) { var htmlFilePath = path.resolve(path.join(options.tmpDir, id + ".html")); fs.writeFile(htmlFilePath, html, function (err) { if (err) return cb(err); var childArgs = [ path.join(__dirname, "scripts", "standaloneScript.js"), htmlFilePath, '--ignore-ssl-errors=yes', '--web-security=false', '--ssl-protocol=any' ]; var isDone = false; var output = ""; var path2PhantomJS = options.phantomJSPath || phantomjs.path; var child = childProcess.execFile(path2PhantomJS, childArgs, { maxBuffer: 1024 * 50000 }, function (err, stdout, stderr) { if (isDone) return; isDone = true; if (err) { return cb(err); } cb(null, JSON.parse(output)); }); child.stdout.on("data", function(data) { output += data; }); setTimeout(function() { if (isDone) return; isDone = true; cb(new Error("Timeout when executing in phantom")); }, options.timeout); }); };
var path = require("path"), childProcess = require('child_process'), phantomjs = require('phantomjs'), fs = require("fs"); module.exports = function(options, html, id, cb) { var htmlFilePath = path.resolve(path.join(options.tmpDir, id + ".html")); fs.writeFile(htmlFilePath, html, function (err) { if (err) return cb(err); var childArgs = [ path.join(__dirname, "scripts", "standaloneScript.js"), htmlFilePath, '--ignore-ssl-errors=yes', '--web-security=false', '--ssl-protocol=any' ]; var isDone = false; var output = ""; var child = childProcess.execFile(phantomjs.path, childArgs, { maxBuffer: 1024 * 50000 }, function (err, stdout, stderr) { if (isDone) return; isDone = true; if (err) { return cb(err); } cb(null, JSON.parse(output)); }); child.stdout.on("data", function(data) { output += data; }); setTimeout(function() { if (isDone) return; isDone = true; cb(new Error("Timeout when executing in phantom")); }, options.timeout); }); };
Add link to 404 example page
import React, {Component, PropTypes} from 'react'; import {IndexLink, Link} from 'react-router'; import {connect} from 'react-redux'; @connect( state => ({ loggedIn: state.auth.loggedIn }) ) export default class Header extends Component { static propTypes = { loggedIn: PropTypes.bool } render() { let links = [ { to: '/trends', title: 'Github trends' }, { to: '/about', title: 'About' }, { to: '/404', title: 'Non-exists page' } ]; if (this.props.loggedIn) { links.push({ to: '/profile', title: 'Profile' }); links.push({ to: '/logout', title: 'Logout' }); } else { links.push({ to: '/login', title: 'Login' }); } return ( <div className="ui text container"> <h1 className="ui dividing header">Redux universal boilerplate</h1> <div className="ui secondary pointing menu"> <IndexLink to="/" className="item" activeClassName="active">Homepage</IndexLink> { links.map(function(link, i) { return <Link to={link.to} key={i} className="item" activeClassName="active">{link.title}</Link>; }) } </div> </div> ); } }
import React, {Component, PropTypes} from 'react'; import {IndexLink, Link} from 'react-router'; import {connect} from 'react-redux'; @connect( state => ({ loggedIn: state.auth.loggedIn }) ) export default class Header extends Component { static propTypes = { loggedIn: PropTypes.bool } render() { let links = [ { to: '/trends', title: 'Github trends' }, { to: '/about', title: 'About' } ]; if (this.props.loggedIn) { links.push({ to: '/profile', title: 'Profile' }); links.push({ to: '/logout', title: 'Logout' }); } else { links.push({ to: '/login', title: 'Login' }); } return ( <div className="ui text container"> <h1 className="ui dividing header">Redux universal boilerplate</h1> <div className="ui secondary pointing menu"> <IndexLink to="/" className="item" activeClassName="active">Homepage</IndexLink> { links.map(function(link, i) { return <Link to={link.to} key={i} className="item" activeClassName="active">{link.title}</Link>; }) } </div> </div> ); } }
Tweak example client for new board format
<? $board = json_decode($_POST['board']); if($_GET['strategy'] == 2) { foreach($board as $x => $col) { foreach($col as $y => $cell) { if($cell == 2) { $x1 = $x; $y1 = $y; } elseif($cell == 9) { $x2 = $x; $y2 = $y; } } } $dx = $x1 - $x2; $dy = $y1 - $y2; if(abs($dx) > abs($dy)) { if($dx > 0) { echo 2; } else { echo 0; } } else { if($dy > 0) { echo 3; } else { echo 1; } } } else { echo rand(0, 3); } ?>
<? $board = json_decode($_POST['board']); if($_POST['player'] == 2) { foreach($board as $x => $col) { foreach($col as $y => $cell) { if($cell == 1) { $x1 = $x; $y1 = $y; } elseif($cell == 2) { $x2 = $x; $y2 = $y; } } } $dx = $x1 - $x2; $dy = $y1 - $y2; if(abs($dx) > abs($dy)) { if($dx > 0) { echo 2; } else { echo 0; } } else { if($dy > 0) { echo 3; } else { echo 1; } } } else { echo rand(0, 3); } ?>
Put spaces between joined members in group updates
/* vim: ts=4:sw=4:expandtab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ (function () { 'use strict'; window.Whisper = window.Whisper || {}; Whisper.GroupUpdateView = Backbone.View.extend({ tagName: "div", className: "group-update", render: function() { //TODO l10n var messages = ['Updated the group.']; if (this.model.name) { messages.push("Title is now '" + this.model.name + "'."); } if (this.model.joined) { messages.push(this.model.joined.join(', ') + ' joined the group'); } this.$el.text(messages.join(' ')); return this; } }); })();
/* vim: ts=4:sw=4:expandtab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ (function () { 'use strict'; window.Whisper = window.Whisper || {}; Whisper.GroupUpdateView = Backbone.View.extend({ tagName: "div", className: "group-update", render: function() { //TODO l10n var messages = ['Updated the group.']; if (this.model.name) { messages.push("Title is now '" + this.model.name + "'."); } if (this.model.joined) { messages.push(this.model.joined + ' joined the group'); } this.$el.text(messages.join(' ')); return this; } }); })();
Add left padding to item decoration
package me.echeung.cdflabs.utils; import android.content.Context; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.support.v4.content.ContextCompat; import android.support.v7.widget.RecyclerView; import android.view.View; import me.echeung.cdflabs.R; public class DividerItemDecoration extends RecyclerView.ItemDecoration { private Drawable mDivider; private int mPaddingLeft; public DividerItemDecoration(Context context) { this.mDivider = ContextCompat.getDrawable(context, R.drawable.line_divider); this.mPaddingLeft = 2 * (int) context.getResources().getDimension(R.dimen.regular_margin) + (int) context.getResources().getDimension(R.dimen.free_size); } @Override public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) { final int left = parent.getPaddingLeft() + this.mPaddingLeft; final int right = parent.getWidth() - parent.getPaddingRight(); // Avoid last item and footer final int childCount = parent.getChildCount() - 2; if (childCount > 0) { for (int i = 0; i < childCount; i++) { final View child = parent.getChildAt(i); final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams(); final int top = child.getBottom() + params.bottomMargin; final int bottom = top + mDivider.getIntrinsicHeight(); mDivider.setBounds(left, top, right, bottom); mDivider.draw(c); } } } }
package me.echeung.cdflabs.utils; import android.content.Context; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.support.v4.content.ContextCompat; import android.support.v7.widget.RecyclerView; import android.view.View; import me.echeung.cdflabs.R; public class DividerItemDecoration extends RecyclerView.ItemDecoration { private Drawable mDivider; public DividerItemDecoration(Context context) { this.mDivider = ContextCompat.getDrawable(context, R.drawable.line_divider); } @Override public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) { final int left = parent.getPaddingLeft(); final int right = parent.getWidth() - parent.getPaddingRight(); // Avoid last item and footer final int childCount = parent.getChildCount() - 2; if (childCount > 0) { for (int i = 0; i < childCount; i++) { final View child = parent.getChildAt(i); final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams(); final int top = child.getBottom() + params.bottomMargin; final int bottom = top + mDivider.getIntrinsicHeight(); mDivider.setBounds(left, top, right, bottom); mDivider.draw(c); } } } }
BB-4106: Refactor ThemeExtension - add space
<?php namespace Oro\Component\Layout\Extension; use Oro\Component\Layout\Extension\Theme\PathProvider\PathProviderInterface; abstract class AbstractLayoutUpdateLoaderExtension extends AbstractExtension { /** @var array */ protected $resources; /** * Filters resources by paths * * @param array $paths * * @return array */ public function findApplicableResources(array $paths) { $result = []; foreach ($paths as $path) { $pathArray = explode(PathProviderInterface::DELIMITER, $path); $value = $this->resources; for ($i = 0, $length = count($pathArray); $i < $length; ++$i) { $value = $this->readValue($value, $pathArray[$i]); if (null === $value) { break; } } if ($value && is_array($value)) { $result = array_merge($result, array_filter($value, 'is_string')); } } return $result; } /** * @param array $array * @param string $property * * @return mixed */ public function readValue(&$array, $property) { if (is_array($array) && isset($array[$property])) { return $array[$property]; } return null; } }
<?php namespace Oro\Component\Layout\Extension; use Oro\Component\Layout\Extension\Theme\PathProvider\PathProviderInterface; abstract class AbstractLayoutUpdateLoaderExtension extends AbstractExtension { /** @var array */ protected $resources; /** * Filters resources by paths * * @param array $paths * * @return array */ public function findApplicableResources(array $paths) { $result = []; foreach ($paths as $path) { $pathArray = explode(PathProviderInterface::DELIMITER, $path); $value = $this->resources; for ($i = 0, $length = count($pathArray); $i < $length; ++$i) { $value = $this->readValue($value, $pathArray[$i]); if (null === $value) { break; } } if ($value && is_array($value)) { $result = array_merge($result, array_filter($value, 'is_string')); } } return $result; } /** * @param array $array * @param string $property * * @return mixed */ public function readValue(&$array, $property) { if (is_array($array) && isset($array[$property])) { return $array[$property]; } return null; } }
Move (back) to call-based jsonp
loadCommands([ // eslint-disable-line no-undef { Name: 'help', Info: 'Returns a help message to get you started with RemindMeBot.', Usage: 'r>help' }, { Name: 'remindme', Info: 'Creates a reminder. Pass without args to start a guided tour.', Usage: 'r>remindme [<time argument> "<message>"]', Example: 'r>remindme 12 hours "Buy groceries"' }, { Name: 'list', Info: ['Sends you your current reminders in DM.', 'Note: will send in channel if DMs are disabled.'], Usage: 'r>list' }, { Name: 'clear', Info: 'Starts a guided tour to clear all of your reminders.', Usage: 'r>clear' }, { Name: 'forget', Info: 'Starts a guided tour to forget one of your reminders.', Usage: 'r>forget' }, { Name: 'prefix', Info: 'Changes your prefix to the given argument.', Usage: 'r>prefix <desired prefix>', Example: 'r>prefix !!' }, { Name: 'invite', Info: 'Returns an invite for RemindMeBot.', Usage: 'r>invite' }, { Name: 'ping', Info: ' Returns the Websocket ping to the API servers in ms.', Usage: 'r>ping' }, { Name: 'stats', Info: 'Returns information and statistics about RemindMeBot.', Usage: 'r>stats' } ]);
(function () { // eslint-disable-line no-undef const commands = [ { Name: 'help', Info: 'Returns a help message to get you started with RemindMeBot.', Usage: 'r>help' }, { Name: 'remindme', Info: 'Creates a reminder. Pass without args to start a guided tour.', Usage: 'r>remindme [<time argument> "<message>"]', Example: 'r>remindme 12 hours "Buy groceries"' }, { Name: 'list', Info: ['Sends you your current reminders in DM.', 'Note: will send in channel if DMs are disabled.'], Usage: 'r>list' }, { Name: 'clear', Info: 'Starts a guided tour to clear all of your reminders.', Usage: 'r>clear' }, { Name: 'forget', Info: 'Starts a guided tour to forget one of your reminders.', Usage: 'r>forget' }, { Name: 'prefix', Info: 'Changes your prefix to the given argument.', Usage: 'r>prefix <desired prefix>', Example: 'r>prefix !!' }, { Name: 'invite', Info: 'Returns an invite for RemindMeBot.', Usage: 'r>invite' }, { Name: 'ping', Info: ' Returns the Websocket ping to the API servers in ms.', Usage: 'r>ping' }, { Name: 'stats', Info: 'Returns information and statistics about RemindMeBot.', Usage: 'r>stats' } ]; }();
Fix params in nested route
import Ember from 'ember'; import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin'; export default Ember.Route.extend(AuthenticatedRouteMixin, { model(params) { var parentParams = this.paramsFor('experiments.info'); return this.store.findRecord('experiment', parentParams.experiment_id).then((experiment) => { // When page loads, creates new session, but doesn't save to store var session = this.store.createRecord(experiment.get('sessionCollectionId'), { experimentId: experiment.id, profileId: 'tester0.prof1', // TODO fetch from service profileVersion: '', softwareVersion: '' }); experiment.getCurrentVersion().then(function(versionId) { session.set('experimentVersion', versionId); }); // TODO: May be an edge case where experimentVersion isn't set/ resolved before this hash returns return Ember.RSVP.hash({ experiment: experiment, session: session }); }); }, actions: { willTransition: function(transition) { // FIXME: This won't prevent back button or manual URL change. See https://guides.emberjs.com/v2.3.0/routing/preventing-and-retrying-transitions/#toc_preventing-transitions-via-code-willtransition-code if (this.controller.isDirty() && !confirm('Are you sure you want to exit the experiment?')) { transition.abort(); return false; } else { // Bubble this action to parent routes return true; } } } });
import Ember from 'ember'; export default Ember.Route.extend({ model(params) { return this.store.findRecord('experiment', params.experiment_id).then((experiment) => { // When page loads, creates new session, but doesn't save to store var session = this.store.createRecord(experiment.get('sessionCollectionId'), { experimentId: experiment.id, profileId: 'tester0.prof1', // TODO fetch from service profileVersion: '', softwareVersion: '' }); experiment.getCurrentVersion().then(function(versionId) { session.set('experimentVersion', versionId); }); // TODO: May be an edge case where experimentVersion isn't set/ resolved before this hash returns return Ember.RSVP.hash({ experiment: experiment, session: session }); }); }, actions: { willTransition: function(transition) { // FIXME: This won't prevent back button or manual URL change. See https://guides.emberjs.com/v2.3.0/routing/preventing-and-retrying-transitions/#toc_preventing-transitions-via-code-willtransition-code if (this.controller.isDirty() && !confirm('Are you sure you want to exit the experiment?')) { transition.abort(); return false; } else { // Bubble this action to parent routes return true; } } } });
Add canonical cases to test
import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.util.Arrays; import java.util.Collection; import static org.junit.Assert.assertEquals; @RunWith(Parameterized.class) public class BinaryTest { private String input; private int expectedOutput; @Parameters public static Collection<Object[]> data() { return Arrays.asList(new Object[][]{ {"1", 1}, {"10", 2}, {"11", 3}, {"100", 4}, {"1001", 9}, {"11010", 26}, {"10001101000", 1128}, {"2", 0}, {"5", 0}, {"9", 0}, {"134678", 0}, {"abc10", 0}, {"10z", 0}, {"10a10", 0}, {"011", 3} }); } public BinaryTest(String input, int expectedOutput) { this.input = input; this.expectedOutput = expectedOutput; } @Test public void test() { Binary binary = new Binary(input); assertEquals(expectedOutput, binary.getDecimal()); } }
import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.util.Arrays; import java.util.Collection; import static org.junit.Assert.assertEquals; @RunWith(Parameterized.class) public class BinaryTest { private String input; private int expectedOutput; @Parameters public static Collection<Object[]> data() { return Arrays.asList(new Object[][]{ {"1", 1}, {"10", 2}, {"11", 3}, {"100", 4}, {"1001", 9}, {"11010", 26}, {"10001101000", 1128}, {"2", 0}, {"5", 0}, {"9", 0}, {"134678", 0}, {"abc10z", 0}, {"011", 3} }); } public BinaryTest(String input, int expectedOutput) { this.input = input; this.expectedOutput = expectedOutput; } @Test public void test() { Binary binary = new Binary(input); assertEquals(expectedOutput, binary.getDecimal()); } }
Add a more informative error message when Dockerfile is unavailable during s2i
package io.quarkus.container.image.openshift.deployment; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Path; import io.dekorate.kubernetes.decorator.NamedResourceDecorator; import io.fabric8.kubernetes.api.model.ObjectMeta; import io.fabric8.openshift.api.model.BuildConfigSpecFluent; import io.quarkus.deployment.util.FileUtil; public class ApplyDockerfileToBuildConfigDecorator extends NamedResourceDecorator<BuildConfigSpecFluent<?>> { private final Path pathToDockerfile; public ApplyDockerfileToBuildConfigDecorator(String name, Path pathToDockerfile) { super(name); if (!pathToDockerfile.toFile().exists()) { throw new IllegalArgumentException( "Specified Dockerfile: '" + pathToDockerfile.toAbsolutePath().toString() + "' does not exist."); } if (!pathToDockerfile.toFile().isFile()) { throw new IllegalArgumentException( "Specified Dockerfile: '" + pathToDockerfile.toAbsolutePath().toString() + "' is not a normal file."); } this.pathToDockerfile = pathToDockerfile; } @Override public void andThenVisit(final BuildConfigSpecFluent<?> spec, ObjectMeta meta) { try (InputStream is = new FileInputStream(pathToDockerfile.toFile())) { spec.withNewSource() .withDockerfile(new String(FileUtil.readFileContents(is))) .endSource() .withNewStrategy() .withNewDockerStrategy() .endDockerStrategy() .endStrategy(); } catch (IOException e) { throw new RuntimeException(e); } } }
package io.quarkus.container.image.openshift.deployment; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Path; import io.dekorate.kubernetes.decorator.NamedResourceDecorator; import io.fabric8.kubernetes.api.model.ObjectMeta; import io.fabric8.openshift.api.model.BuildConfigSpecFluent; import io.quarkus.deployment.util.FileUtil; public class ApplyDockerfileToBuildConfigDecorator extends NamedResourceDecorator<BuildConfigSpecFluent<?>> { private final Path pathToDockerfile; public ApplyDockerfileToBuildConfigDecorator(String name, Path pathToDockerfile) { super(name); this.pathToDockerfile = pathToDockerfile; } @Override public void andThenVisit(final BuildConfigSpecFluent<?> spec, ObjectMeta meta) { try (InputStream is = new FileInputStream(pathToDockerfile.toFile())) { spec.withNewSource() .withDockerfile(new String(FileUtil.readFileContents(is))) .endSource() .withNewStrategy() .withNewDockerStrategy() .endDockerStrategy() .endStrategy(); } catch (IOException e) { throw new RuntimeException(e); } } }
Update test to ensure that default configuration values are available via getConfOpt
from synapse.tests.common import * import synapse.lib.config as s_config class ConfTest(SynTest): def test_conf_base(self): defs = ( ('fooval',{'type':'int','doc':'what is foo val?','defval':99}), ('enabled',{'type':'bool','doc':'is thing enabled?','defval':0}), ) data = {} def callback(v): data['woot'] = v with s_config.Config(defs=defs) as conf: self.eq(conf.getConfOpt('enabled'), 0) self.eq(conf.getConfOpt('fooval'), 99) conf.onConfOptSet('enabled',callback) conf.setConfOpt('enabled','true') self.eq(data.get('woot'), 1) conf.setConfOpts({'fooval':'0x20'}) self.eq(conf.getConfOpt('fooval'), 0x20) conf.setConfOpts({'fooval':0x30}) self.eq(conf.getConfOpt('fooval'), 0x30) self.assertRaises( NoSuchOpt, conf.setConfOpts, {'newp':'hehe'} ) def test_conf_asloc(self): with s_config.Config() as conf: conf.addConfDef('foo',type='int',defval=0,asloc='_foo_valu') self.eq( conf._foo_valu, 0 ) conf.setConfOpt('foo','0x20') self.eq( conf._foo_valu, 0x20)
from synapse.tests.common import * import synapse.lib.config as s_config class ConfTest(SynTest): def test_conf_base(self): defs = ( ('fooval',{'type':'int','doc':'what is foo val?','defval':99}), ('enabled',{'type':'bool','doc':'is thing enabled?','defval':0}), ) data = {} def callback(v): data['woot'] = v with s_config.Config(defs=defs) as conf: conf.onConfOptSet('enabled',callback) conf.setConfOpt('enabled','true') self.eq(data.get('woot'), 1) conf.setConfOpts({'fooval':'0x20'}) self.eq(conf.getConfOpt('fooval'), 0x20) conf.setConfOpts({'fooval':0x30}) self.eq(conf.getConfOpt('fooval'), 0x30) self.assertRaises( NoSuchOpt, conf.setConfOpts, {'newp':'hehe'} ) def test_conf_asloc(self): with s_config.Config() as conf: conf.addConfDef('foo',type='int',defval=0,asloc='_foo_valu') self.eq( conf._foo_valu, 0 ) conf.setConfOpt('foo','0x20') self.eq( conf._foo_valu, 0x20)
Replace occurences of 'startCode' with 'code'
var validator = require('validator'), iz = require('iz'); var assessmentValidator = {}; var validate = function (assessment) { var toReturn = true; var results = [ validator.isLength(assessment.id, 2), validator.isLength(assessment.title, 2), validator.isLength(assessment.instructions, 10), iz(assessment.providedCompilationUnits).anArray().required().valid, iz(assessment.compilationUnitsToSubmit).anArray().minLength(1).valid, iz(assessment.tests).anArray().minLength(1).valid, iz(assessment.tips).anArray().required().valid, iz(assessment.guides).anArray().required().valid ]; // TODO Validate each individual element in arrays // validator.contains(assessment.code, 'public class ' + assessment.className + ' {'), // validator.isLength(assessment.className, 2) results.forEach(function (result) { if (!result) { //console.log(results); toReturn = false; } }); return toReturn; }; assessmentValidator.validate = validate; assessmentValidator.validateAll = function (assessments) { var result = true; assessments.forEach(function (assessment) { if (!validate(assessment)) { result = false; } }); return result; }; module.exports = assessmentValidator;
var validator = require('validator'), iz = require('iz'); var assessmentValidator = {}; var validate = function (assessment) { var toReturn = true; var results = [ validator.isLength(assessment.id, 2), validator.isLength(assessment.title, 2), validator.isLength(assessment.instructions, 10), iz(assessment.providedCompilationUnits).anArray().required().valid, iz(assessment.compilationUnitsToSubmit).anArray().minLength(1).valid, iz(assessment.tests).anArray().minLength(1).valid, iz(assessment.tips).anArray().required().valid, iz(assessment.guides).anArray().required().valid ]; // TODO Validate each individual element in arrays // validator.contains(assessment.startCode, 'public class ' + assessment.className + ' {'), // validator.isLength(assessment.className, 2) results.forEach(function (result) { if (!result) { //console.log(results); toReturn = false; } }); return toReturn; }; assessmentValidator.validate = validate; assessmentValidator.validateAll = function (assessments) { var result = true; assessments.forEach(function (assessment) { if (!validate(assessment)) { result = false; } }); return result; }; module.exports = assessmentValidator;
Add rules to eslint config
// http://eslint.org/ module.exports = { "extends": "eslint:recommended", // http://eslint.org/docs/user-guide/configuring#specifying-environments "env": { "browser": true, }, // http://eslint.org/docs/user-guide/configuring#specifying-globals "globals": { // false means it shouldn't be overwritten "define": false, "hqDefine": false, "hqImport": false, "requirejs": false, "gettext": false, "ngettext": false, "assert": false, "sinon": false, "$": false, "ko": false, "_": false, "L": true, "it": false, "describe": false, "beforeEach": false, }, // http://eslint.org/docs/rules/ // http://eslint.org/docs/user-guide/configuring#configuring-rules "rules": { // First option can be off, warn, or error "comma-dangle": ["warn", "always-multiline"], "eqeqeq": ["error"], "indent": ["warn", 4, {"SwitchCase":1}], "linebreak-style": ["error", "unix"], "semi": ["error", "always"], "no-new-object": ["error"], "no-unneeded-ternary": ["error"], "no-throw-literal": ["error"], "no-use-before-define": ["error"], } };
// http://eslint.org/ module.exports = { "extends": "eslint:recommended", // http://eslint.org/docs/user-guide/configuring#specifying-environments "env": { "browser": true, }, // http://eslint.org/docs/user-guide/configuring#specifying-globals "globals": { // false means it shouldn't be overwritten "define": false, "hqDefine": false, "hqImport": false, "requirejs": false, "gettext": false, "ngettext": false, "assert": false, "sinon": false, "$": false, "ko": false, "_": false, "L": true, "it": false, "describe": false, "beforeEach": false, }, // http://eslint.org/docs/rules/ // http://eslint.org/docs/user-guide/configuring#configuring-rules "rules": { // First option can be off, warn, or error "comma-dangle": ["warn", "always-multiline"], "eqeqeq": ["error"], "indent": ["warn", 4, {"SwitchCase":1}], "linebreak-style": ["error", "unix"], "semi": ["error", "always"], } };
Add rollup and bundle options This enables inline sourcemaps
'use strict'; var rollup = require('rollup'); // @param args {Object} - Config object of custom preprocessor. // @param config {Object} - Config object of rollupPreprocessor. // @param logger {Object} - Karma's logger. // @helper helper {Object} - Karma's helper functions. function createPreprocessor (args, config, logger, helper) { var log = logger.create('preprocessor.rollup'); config = config || {}; var rollupConfig = config.rollup || {}; var bundleConfig = config.bundle || {}; function preprocess (content, file, done) { log.debug('Processing "%s".', file.originalPath); try { rollupConfig.entry = file.originalPath; rollup .rollup(rollupConfig) .then(function (bundle) { if (!bundleConfig.hasOwnProperty('format')) { bundleConfig.format = 'es6'; } var generated = bundle.generate(bundleConfig); var processed = generated.code; if (bundleConfig.sourceMap === 'inline') { var url = generated.map.toUrl(); processed += "\n" + '//# sourceMappingURL=' + url; } done(null, processed); }) .catch(function (error) { done(error, null) }); } catch (exception) { log.error('%s\n at %s', exception.message, file.originalPath); done(exception, null); } } return preprocess; } createPreprocessor.$inject = ['args', 'config.rollupPreprocessor', 'logger', 'helper']; module.exports = { 'preprocessor:rollup': ['factory', createPreprocessor] };
'use strict'; var rollup = require('rollup'); // @param args {Object} - Config object of custom preprocessor. // @param config {Object} - Config object of rollupPreprocessor. // @param logger {Object} - Karma's logger. // @helper helper {Object} - Karma's helper functions. function createPreprocessor (args, config, logger, helper) { var log = logger.create('preprocessor.rollup'); config = config || {}; function preprocess (content, file, done) { log.debug('Processing "%s".', file.originalPath); try { config.entry = file.originalPath; rollup .rollup(config) .then(function (bundle) { var processed = bundle.generate({format: 'es6'}).code; done(null, processed); }) .catch(function (error) { done(error, null) }); } catch (exception) { log.error('%s\n at %s', exception.message, file.originalPath); done(exception, null); } } return preprocess; } createPreprocessor.$inject = ['args', 'config.rollupPreprocessor', 'logger', 'helper']; module.exports = { 'preprocessor:rollup': ['factory', createPreprocessor] };
Remove extra bind from NoteForm submit button Already bound in the view events hash
var NoteForm = FormView.extend({ tagName: 'div', initialize: function() { // Supply the model with a reference to it's own view object, so it can // remove itself from the page when destroy() gets called. this.model.view = this; if (this.model.id) { this.id = this.el.id = this.model.id; } }, events: { "click input": "saveEdit" }, saveEdit: function() { this.model.set(this.changed_attributes); //this.disableForm(); var view = this; this.model.save(null, { success: function(model, response) { view.model.set({editing: false}); //view.enableForm(); }, error: function(model, response) { var json = $.parseJSON(response.responseText); model.set({editing: true, errors: json.note.errors}); App.notice({title: "Save error", text: model.errorMessages()}); //view.enableForm(); } }); }, render: function() { var view = this; div = this.make('div'); $(div).append(this.label("note", "Note")); $(div).append('<br/>'); $(div).append(this.textArea("note")); var submit = this.make('input', {id: 'note_submit', type: 'button', value: 'Add note'}); $(div).append(submit); $(this.el).html(div); return this; } });
var NoteForm = FormView.extend({ tagName: 'div', initialize: function() { // Supply the model with a reference to it's own view object, so it can // remove itself from the page when destroy() gets called. this.model.view = this; if (this.model.id) { this.id = this.el.id = this.model.id; } }, events: { "click input": "saveEdit" }, saveEdit: function() { console.debug(this.model); this.model.set(this.changed_attributes); //this.disableForm(); var view = this; this.model.save(null, { success: function(model, response) { view.model.set({editing: false}); //view.enableForm(); }, error: function(model, response) { var json = $.parseJSON(response.responseText); model.set({editing: true, errors: json.note.errors}); App.notice({title: "Save error", text: model.errorMessages()}); //view.enableForm(); } }); }, render: function() { var view = this; div = this.make('div'); $(div).append(this.label("note", "Note")); $(div).append('<br/>'); $(div).append(this.textArea("note")); var submit = this.make('input', {id: 'note_submit', type: 'button', value: 'Add note'}); $(submit).bind('click', function() { view.saveEdit(); }); $(div).append(submit); $(this.el).html(div); return this; } });
Add rel="noopener" for external anchors Recommended by Lighthouse https://developers.google.com/web/tools/lighthouse/audits/noopener
import React, {PureComponent} from 'react'; import classNames from 'classnames'; import {Link as RoutedLink} from 'react-router-dom'; import styles from './Link.scss'; export default class Link extends PureComponent { static defaultProps = { selected: false, }; routedLink() { const {url, selected, className} = this.props; return ( <RoutedLink className={classNames(styles.Link, selected && styles.Selected, className)} to={url} > {this.props.children} </RoutedLink> ); } btnLink() { const {onClick} = this.props; return ( <button className={classNames(styles.Link)} onClick={onClick} > {this.props.children} </button> ); } render() { const {url, external, onClick, selected, className, routed, button} = this.props; if (routed) { return this.routedLink(); } if (button) { return this.btnLink(); } return ( <a className={classNames(styles.Link, selected && styles.Selected, className)} onClick={onClick} onTouchStart={onClick} target={external ? '_blank' : null} rel={external ? 'noopener' : null} href={url} > {this.props.children} </a> ); } }
import React, {PureComponent} from 'react'; import classNames from 'classnames'; import {Link as RoutedLink} from 'react-router-dom'; import styles from './Link.scss'; export default class Link extends PureComponent { static defaultProps = { selected: false, }; routedLink() { const {url, selected, className} = this.props; return ( <RoutedLink className={classNames(styles.Link, selected && styles.Selected, className)} to={url} > {this.props.children} </RoutedLink> ); } btnLink() { const {onClick} = this.props; return ( <button className={classNames(styles.Link)} onClick={onClick} > {this.props.children} </button> ); } render() { const {url, external, onClick, selected, className, routed, button} = this.props; if (routed) { return this.routedLink(); } if (button) { return this.btnLink(); } return ( <a className={classNames(styles.Link, selected && styles.Selected, className)} onClick={onClick} onTouchStart={onClick} target={external ? '_blank' : null} href={url} > {this.props.children} </a> ); } }
Add todo about field groups
/* global $ */ import Ember from 'ember'; import { translationMacro as t } from 'ember-i18n'; export default Ember.Controller.extend({ i18n: Ember.inject.service(), actions: { navigationClick(fieldGroupId) { $('html, body').animate({ scrollTop: $('#field-group-' + fieldGroupId).offset().top - 10 }, 300); } }, entityType: t('definitions.zoological'), // TODO: Collect these fieldGroups from a Service based on the // department the user belongs to. fieldGroups: [ { title: 'field_group_basic_data', fields: [{ type: 'autocomplete', title: 'definitions.name' }] }, { title: 'field_group_taxonomy', fields: [] }, { title: 'field_group_site', fields: [] }, { title: 'field_group_preparation', fields: [] }, { title: 'field_group_other', fields: [] } ] });
/* global $ */ import Ember from 'ember'; import { translationMacro as t } from 'ember-i18n'; export default Ember.Controller.extend({ i18n: Ember.inject.service(), actions: { navigationClick(fieldGroupId) { $('html, body').animate({ scrollTop: $('#field-group-' + fieldGroupId).offset().top - 10 }, 300); } }, entityType: t('definitions.zoological'), fieldGroups: [ { title: 'field_group_basic_data', fields: [{ type: 'autocomplete', title: 'definitions.name' }] }, { title: 'field_group_taxonomy', fields: [] }, { title: 'field_group_site', fields: [] }, { title: 'field_group_preparation', fields: [] }, { title: 'field_group_other', fields: [] } ] });
Fix in publish to example folder
'use strict'; module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), concat: { dist: { src: ['src/**/*.js'], dest: 'dist/<%= pkg.name %>.js' } }, uglify: { dist: { files: { 'dist/<%= pkg.name %>.min.js': ['<%= concat.dist.dest %>'] } } }, copy: { dist: { src: 'src/**/<%= pkg.name %>.css', dest: 'dist/<%= pkg.name %>.css' }, example: { expand: true, flatten: true, src: ['dist/*'], dest: 'example/node_modules/gnap-map/dist/' } }, cssmin: { dist: { src: 'dist/<%= pkg.name %>.css', dest: 'dist/<%= pkg.name %>.min.css' } } }); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.registerTask('dist', ['concat', 'uglify', 'copy:dist', 'cssmin', 'copy:example']); };
'use strict'; module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), concat: { dist: { src: ['src/**/*.js'], dest: 'dist/<%= pkg.name %>.js' } }, uglify: { dist: { files: { 'dist/<%= pkg.name %>.min.js': ['<%= concat.dist.dest %>'] } } }, copy: { dist: { src: 'src/**/<%= pkg.name %>.css', dest: 'dist/<%= pkg.name %>.css' }, example: { expand: true, flatten: true, src: ['dist/*'], dest: 'examples/node_modules/gnap-map/dist/' } }, cssmin: { dist: { src: 'dist/<%= pkg.name %>.css', dest: 'dist/<%= pkg.name %>.min.css' } } }); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.registerTask('dist', ['concat', 'uglify', 'copy:dist', 'cssmin', 'copy:example']); };
Fix bug with exists property
<?php namespace ThibaudDauce\MoloquentInheritance; use ReflectionClass; trait MoloquentInheritanceTrait { public $parentClasses; /** * Boot the moloquent inheritance for a model. * * @return void */ public static function bootMoloquentInheritanceTrait() { static::addGlobalScope(new MoloquentInheritanceScope); } /** * Fill the model with an array of attributes. * * @override Illuminate\Database\Eloquent\Model * @param array $attributes * @return $this * * @throws MassAssignmentException */ public function fill(array $attributes) { $this->setParentClasses(); return parent::fill($attributes); } public function getParentClasses() { $reflection = new ReflectionClass($this); $classes = [$reflection->getName()]; while ($reflection->getName() !== get_class()) { $reflection = $reflection->getParentClass(); $classes[] = $reflection->getName(); } return $classes; } public function setParentClasses() { $this->attributes['parent_classes'] = $this->getParentClasses(); } /** * Create a new model instance that is existing. * * @override Illuminate\Database\Eloquent\Model * @param array $attributes * @return \Illuminate\Database\Eloquent\Model|static */ public function newFromBuilder($attributes = array()) { $class = $attributes['parent_classes'][0]; if ($this instanceof $class) return parent::newFromBuilder($attributes); $instance = new $class; $instance->newFromBuilder((array) $attributes); return $instance; } }
<?php namespace ThibaudDauce\MoloquentInheritance; use ReflectionClass; trait MoloquentInheritanceTrait { public $parentClasses; /** * Boot the moloquent inheritance for a model. * * @return void */ public static function bootMoloquentInheritanceTrait() { static::addGlobalScope(new MoloquentInheritanceScope); } /** * Fill the model with an array of attributes. * * @override Illuminate\Database\Eloquent\Model * @param array $attributes * @return $this * * @throws MassAssignmentException */ public function fill(array $attributes) { $this->setParentClasses(); return parent::fill($attributes); } public function getParentClasses() { $reflection = new ReflectionClass($this); $classes = [$reflection->getName()]; while ($reflection->getName() !== get_class()) { $reflection = $reflection->getParentClass(); $classes[] = $reflection->getName(); } return $classes; } public function setParentClasses() { $this->attributes['parent_classes'] = $this->getParentClasses(); } /** * Create a new model instance that is existing. * * @override Illuminate\Database\Eloquent\Model * @param array $attributes * @return \Illuminate\Database\Eloquent\Model|static */ public function newFromBuilder($attributes = array()) { $class = $attributes['parent_classes'][0]; $instance = new $class; $instance->setRawAttributes((array) $attributes, true); return $instance; } }
Remove developer debug window during screen share Right now when you try to share your screen it opens a developer window.
'use strict'; const electron = require('electron'); const { remote } = require('electron'); const selfBrowserWindow = remote.getCurrentWindow(); selfBrowserWindow.webContents.once('dom-ready', () => { window.JitsiMeetElectron = { /** * Get sources available for screensharing. The callback is invoked * with an array of DesktopCapturerSources. * * @param {Function} callback - The success callback. * @param {Function} errorCallback - The callback for errors. * @param {Object} options - Configuration for getting sources. * @param {Array} options.types - Specify the desktop source types * to get, with valid sources being "window" and "screen". * @param {Object} options.thumbnailSize - Specify how big the * preview images for the sources should be. The valid keys are * height and width, e.g. { height: number, width: number}. By * default electron will return images with height and width of * 150px. */ obtainDesktopStreams (callback, errorCallback, options = {}) { electron.desktopCapturer.getSources(options, (error, sources) => { if (error) { errorCallback(error); return; } callback(sources); }); } }; });
'use strict'; const electron = require('electron'); const { remote } = require('electron'); const selfBrowserWindow = remote.getCurrentWindow(); selfBrowserWindow.webContents.openDevTools({ mode: 'detach' }); selfBrowserWindow.webContents.once('dom-ready', () => { window.JitsiMeetElectron = { /** * Get sources available for screensharing. The callback is invoked * with an array of DesktopCapturerSources. * * @param {Function} callback - The success callback. * @param {Function} errorCallback - The callback for errors. * @param {Object} options - Configuration for getting sources. * @param {Array} options.types - Specify the desktop source types * to get, with valid sources being "window" and "screen". * @param {Object} options.thumbnailSize - Specify how big the * preview images for the sources should be. The valid keys are * height and width, e.g. { height: number, width: number}. By * default electron will return images with height and width of * 150px. */ obtainDesktopStreams (callback, errorCallback, options = {}) { electron.desktopCapturer.getSources(options, (error, sources) => { if (error) { errorCallback(error); return; } callback(sources); }); } }; });
Reduce bottom padding on alert panel
var classNames = require('classnames'); var React = require('react'); var Panel = require('./Panel'); var AlertPanel = React.createClass({ displayName: 'AlertPanel', defaultProps: { className: '', icon: null }, propTypes: { title: React.PropTypes.string, icon: React.PropTypes.node, iconClassName: React.PropTypes.string }, getTitle: function () { return ( <h3 className="inverse flush-top"> {this.props.title} </h3> ); }, getIcon: function () { let {icon, iconClassName} = this.props; if (!!icon) { return icon; } if (!iconClassName) { return null; } return ( <i className={iconClassName}></i> ); }, render: function () { let classes = classNames('container container-fluid container-pod', 'flush-bottom', this.props.className); return ( <div className={classes}> <Panel ref="panel" className="panel panel-inverse vertical-center horizontal-center text-align-center flush-bottom alert-panel" footer={this.props.footer} footerClass="panel-footer flush-top" heading={this.getIcon()} headingClass="panel-header no-border flush-bottom"> {this.getTitle()} {this.props.children} </Panel> </div> ); } }); module.exports = AlertPanel;
var classNames = require('classnames'); var React = require('react'); var Panel = require('./Panel'); var AlertPanel = React.createClass({ displayName: 'AlertPanel', defaultProps: { icon: null }, propTypes: { title: React.PropTypes.string, icon: React.PropTypes.node, iconClassName: React.PropTypes.string }, getTitle: function () { return ( <h3 className="inverse flush-top"> {this.props.title} </h3> ); }, getIcon: function () { let {icon, iconClassName} = this.props; if (!!icon) { return icon; } if (!iconClassName) { return null; } return ( <i className={iconClassName}></i> ); }, render: function () { var classes = { 'container container-fluid container-pod': true }; if (this.props.className) { classes[this.props.className] = true; } var classSet = classNames(classes); return ( <div className={classSet}> <Panel ref="panel" className="panel panel-inverse vertical-center horizontal-center text-align-center flush-bottom alert-panel" footer={this.props.footer} footerClass="panel-footer flush-top" heading={this.getIcon()} headingClass="panel-header no-border flush-bottom"> {this.getTitle()} {this.props.children} </Panel> </div> ); } }); module.exports = AlertPanel;
Test basic a-frame tag (not react component)
import 'aframe'; import 'babel-polyfill'; import {Animation, Entity, Scene} from 'aframe-react'; import React from 'react'; import ReactDOM from 'react-dom'; import Camera from './components/Camera'; import Cursor from './components/Cursor'; import Sky from './components/Sky'; class SpaceScene extends React.Component { constructor(props) { super(props); this.state = { color: 'red' } } changeColor = () => { const colors = ['red', 'orange', 'yellow', 'green', 'blue']; this.setState({ color: colors[Math.floor(Math.random() * colors.length)], }); }; render () { return ( <Scene> <Camera><Cursor/></Camera> <Sky/> <Entity light={{type: 'ambient', color: '#888'}}/> <Entity light={{type: 'directional', intensity: 0.2}} position={[-1, 1, 0]}/> <Entity light={{type: 'directional', intensity: 1}} position={[1, 1, 0]}/> <a-box width="4" height="10" depth="2" color={'#FFF'} onClick={this.changeColor} position="0 0 -5"> <Animation attribute="rotation" dur="5000" repeat="indefinite" to="0 360 360"/> </a-box> </Scene> ); } } ReactDOM.render(<SpaceScene/>, document.querySelector('.scene-container'));
import 'aframe'; import 'babel-polyfill'; import {Animation, Entity, Scene} from 'aframe-react'; import React from 'react'; import ReactDOM from 'react-dom'; import Camera from './components/Camera'; import Cursor from './components/Cursor'; import Sky from './components/Sky'; class SpaceScene extends React.Component { constructor(props) { super(props); this.state = { color: 'red' } } changeColor = () => { const colors = ['red', 'orange', 'yellow', 'green', 'blue']; this.setState({ color: colors[Math.floor(Math.random() * colors.length)], }); }; render () { return ( <Scene> <Camera><Cursor/></Camera> <Sky/> <Entity light={{type: 'ambient', color: '#888'}}/> <Entity light={{type: 'directional', intensity: 0.2}} position={[-1, 1, 0]}/> <Entity light={{type: 'directional', intensity: 1}} position={[1, 1, 0]}/> <Entity geometry="primitive: box" material={{color: this.state.color}} onClick={this.changeColor} position="0 0 -5"> <Animation attribute="rotation" dur="5000" repeat="indefinite" to="0 360 360"/> </Entity> </Scene> ); } } ReactDOM.render(<SpaceScene/>, document.querySelector('.scene-container'));
Add space between import and class declaration All heil PEP.
from pygame.mixer import Sound class SelectStateSFX(object): """Plays sound effects that are used by both the Character Select State and the Stage Select State. Class Constants: SCROLL_PATH: A String for the file path to the scroll items sound effect. CONFIRM_PATH: A String for the file path to the confirm choice sound effect. Attributes: channel: A PyGame Channel where all of the sounds will be played. scroll: A PyGame Sound that plays when the players scroll through the list of available options. confirm: A PyGame Sound that plays when the players confirm a choice. """ SCROLL_PATH = 'audio/scroll_char_stage.ogg' CONFIRM_PATH = 'confirm.wav' def __init__(self, channel): """Declare and initialize instance variables. Args: channel: A PyGame Channel that will be used to play the Sounds. """ self.channel = channel self.scroll = Sound(self.SCROLL_PATH) self.confirm = Sound(self.CONFIRM_PATH) def play_scroll(self): """Play the 'scroll items' sound effect.""" self.channel.play(self.scroll) def play_confirm(self): """Play the 'confirm choice' sound effect.""" self.channel.play(self.confirm)
from pygame.mixer import Sound class SelectStateSFX(object): """Plays sound effects that are used by both the Character Select State and the Stage Select State. Class Constants: SCROLL_PATH: A String for the file path to the scroll items sound effect. CONFIRM_PATH: A String for the file path to the confirm choice sound effect. Attributes: channel: A PyGame Channel where all of the sounds will be played. scroll: A PyGame Sound that plays when the players scroll through the list of available options. confirm: A PyGame Sound that plays when the players confirm a choice. """ SCROLL_PATH = 'audio/scroll_char_stage.ogg' CONFIRM_PATH = 'confirm.wav' def __init__(self, channel): """Declare and initialize instance variables. Args: channel: A PyGame Channel that will be used to play the Sounds. """ self.channel = channel self.scroll = Sound(self.SCROLL_PATH) self.confirm = Sound(self.CONFIRM_PATH) def play_scroll(self): """Play the 'scroll items' sound effect.""" self.channel.play(self.scroll) def play_confirm(self): """Play the 'confirm choice' sound effect.""" self.channel.play(self.confirm)
Change to "ask for forgiveness", as the 'client_roles' condition could get too complicated
"""Facility to render node graphs using pydot""" import os import pydot from kitchen.settings import STATIC_ROOT, REPO def generate_node_map(nodes): """Generates a graphviz nodemap""" graph = pydot.Dot(graph_type='digraph') graph_nodes = {} # Create nodes for node in nodes: label = node['name'] + "\n" + "\n".join( [role for role in node['role'] \ if not role.startswith(REPO['EXCLUDE_ROLE_PREFIX'])]) node_el = pydot.Node(label, shape="box", style="filled", fillcolor="lightyellow", fontsize="8") graph_nodes[node['name']] = node_el graph.add_node(node_el) # Create links for node in nodes: for attr in node.keys(): try: client_roles = node[attr]['client_roles'] except (TypeError, KeyError): continue for client_node in nodes: if set.intersection( set(client_roles), set(client_node['roles'])): edge = pydot.Edge(graph_nodes[client_node['name']], graph_nodes[node['name']], fontsize="7") edge.set_label(attr) graph.add_edge(edge) # Generate graph graph.write_png(os.path.join(STATIC_ROOT, 'img', 'node_map.png'))
"""Facility to render node graphs using pydot""" import os import pydot from kitchen.settings import STATIC_ROOT, REPO def generate_node_map(nodes): """Generates a graphviz nodemap""" graph = pydot.Dot(graph_type='digraph') graph_nodes = {} # Create nodes for node in nodes: label = node['name'] + "\n" + "\n".join( [role for role in node['role'] \ if not role.startswith(REPO['EXCLUDE_ROLE_PREFIX'])]) node_el = pydot.Node(label, shape="box", style="filled", fillcolor="lightyellow", fontsize="8") graph_nodes[node['name']] = node_el graph.add_node(node_el) # Create links for node in nodes: for attr in node.keys(): if isinstance(node[attr], dict) and 'client_roles' in node[attr]: for client_node in nodes: if set.intersection(set(node[attr]['client_roles']), set(client_node['roles'])): edge = pydot.Edge(graph_nodes[client_node['name']], graph_nodes[node['name']], fontsize="7") edge.set_label(attr) graph.add_edge(edge) # Generate graph graph.write_png(os.path.join(STATIC_ROOT, 'img', 'node_map.png'))
Disable keyboard support on tree, so it doesn't trap scrolling.
// Auto-magically referenced. Yay. $(document).ready(function() { var rubyFolders = gon.folders; if (!rubyFolders) { return; } var folders = {}; var currentId = gon.currentFolder.id; // Convert all the folders to tree nodes. rubyFolders.forEach(function(folder) { var nameAndCount = folder.name + " (" + folder.count + ")"; folders[folder.id] = { id: folder.id, label: nameAndCount, url: folder.url, parentId: folder.parent_folder_id, children: [] }; }); var rootFolder; // Generate the tree we need for jqTree. for (var id in folders) { var folder = folders[id]; var parentId = folder.parentId; if (!parentId) { rootFolder = folder; } else { folders[parentId].children.push(folder); } } var treeData = [rootFolder]; // Set up the tree. var treeElement = $('#file-tree'); treeElement.tree({ data: treeData, autoOpen: true, keyboardSupport: false }); // Select the folder we're currently in. var currentFolderNode = treeElement.tree('getNodeById', currentId); treeElement.tree('selectNode', currentFolderNode); // Set up bindings on the tree. treeElement.bind('tree.select', function(event) { var selectedNode = event.node; if (selectedNode) { var selectedFolderUrl = selectedNode.url; window.location.href = selectedFolderUrl; } }); });
// Auto-magically referenced. Yay. $(document).ready(function() { var rubyFolders = gon.folders; if (!rubyFolders) { return; } var folders = {}; var currentId = gon.currentFolder.id; // Convert all the folders to tree nodes. rubyFolders.forEach(function(folder) { var nameAndCount = folder.name + " (" + folder.count + ")"; folders[folder.id] = { id: folder.id, label: nameAndCount, url: folder.url, parentId: folder.parent_folder_id, children: [] }; }); var rootFolder; // Generate the tree we need for jqTree. for (var id in folders) { var folder = folders[id]; var parentId = folder.parentId; if (!parentId) { rootFolder = folder; } else { folders[parentId].children.push(folder); } } var treeData = [rootFolder]; // Set up the tree. var treeElement = $('#file-tree'); treeElement.tree({ data: treeData, autoOpen: true }); // Select the folder we're currently in. var currentFolderNode = treeElement.tree('getNodeById', currentId); treeElement.tree('selectNode', currentFolderNode); // Set up bindings on the tree. treeElement.bind('tree.select', function(event) { var selectedNode = event.node; if (selectedNode) { var selectedFolderUrl = selectedNode.url; window.location.href = selectedFolderUrl; } }); });
Test: Add manual document launch test
/** PSPDFKit Copyright (c) 2015-2016 PSPDFKit GmbH. All rights reserved. THIS SOURCE CODE AND ANY ACCOMPANYING DOCUMENTATION ARE PROTECTED BY INTERNATIONAL COPYRIGHT LAW AND MAY NOT BE RESOLD OR REDISTRIBUTED. USAGE IS BOUND TO THE PSPDFKIT LICENSE AGREEMENT. UNAUTHORIZED REPRODUCTION OR DISTRIBUTION IS SUBJECT TO CIVIL AND CRIMINAL PENALTIES. This notice may not be removed from this file. */ exports.defineAutoTests = function () { describe('PSPSDFKit (window.PSPDFKit)', function () { it("should exist", function () { expect(window.PSPDFKit).toBeDefined(); }); describe('showDocument', function() { it('should exist', function () { expect(window.PSPDFKit.showDocument).toBeDefined(); }); }); describe('showDocumentFromAssets', function() { it('should exist', function () { expect(window.PSPDFKit.showDocumentFromAssets).toBeDefined(); }); }); }); }; exports.defineManualTests = function(contentEl, createActionButton) { createActionButton('Open Document', function() { var asset = 'www/Guide.pdf'; console.log('Opening document ' + asset); window.PSPDFKit.showDocumentFromAssets(asset, {}, function() { console.log("Document was successfully loaded."); }, function(error) { console.log('Error while loading the document:' + error) }); }); };
/** PSPDFKit Copyright (c) 2015-2016 PSPDFKit GmbH. All rights reserved. THIS SOURCE CODE AND ANY ACCOMPANYING DOCUMENTATION ARE PROTECTED BY INTERNATIONAL COPYRIGHT LAW AND MAY NOT BE RESOLD OR REDISTRIBUTED. USAGE IS BOUND TO THE PSPDFKIT LICENSE AGREEMENT. UNAUTHORIZED REPRODUCTION OR DISTRIBUTION IS SUBJECT TO CIVIL AND CRIMINAL PENALTIES. This notice may not be removed from this file. */ exports.defineAutoTests = function () { describe('PSPSDFKit (window.PSPDFKit)', function () { it("should exist", function () { expect(window.PSPDFKit).toBeDefined(); }); describe('showDocument', function() { it('should exist', function () { expect(window.PSPDFKit.showDocument).toBeDefined(); }); }); describe('showDocumentFromAssets', function() { it('should exist', function () { expect(window.PSPDFKit.showDocumentFromAssets).toBeDefined(); }); it('should open a document from assets', function(done) { window.PSPDFKit.showDocumentFromAssets("www/Guide.pdf", function() { done(); }, function(error) { done(error); }); }) }); }); };
Add a ModeType enum for later benefit
def _enum(**enums): return type('Enum', (), enums) ModeType = _enum(List=0, ParamOnUnset=1, Param=2, NoParam=3, Status=4) def unescapeEndpointDescription(desc): result = [] escape = [] depth = 0 desc = iter(desc) for char in desc: if char == "\\": try: char = desc.next() except StopIteration: raise ValueError ("Endpoint description not valid: escaped end of string") if char not in "{}": char = "\\{}".format(char) if depth == 0: result.extend(char) else: escape.extend(char) elif char == "{": if depth > 0: escape.append("{") depth += 1 elif char == "}": depth -= 1 if depth < 0: raise ValueError ("Endpoint description not valid: mismatched end brace") if depth == 0: result.extend(unescapeEndpointDescription("".join(escape)).replace("\\", "\\\\").replace(":", "\\:").replace("=", "\\=")) else: escape.append("}") else: if depth == 0: result.append(char) else: escape.append(char) if depth != 0: raise ValueError ("Endpoint description not valid: mismatched opening brace") return "".join(result)
def unescapeEndpointDescription(desc): result = [] escape = [] depth = 0 desc = iter(desc) for char in desc: if char == "\\": try: char = desc.next() except StopIteration: raise ValueError ("Endpoint description not valid: escaped end of string") if char not in "{}": char = "\\{}".format(char) if depth == 0: result.extend(char) else: escape.extend(char) elif char == "{": if depth > 0: escape.append("{") depth += 1 elif char == "}": depth -= 1 if depth < 0: raise ValueError ("Endpoint description not valid: mismatched end brace") if depth == 0: result.extend(unescapeEndpointDescription("".join(escape)).replace("\\", "\\\\").replace(":", "\\:").replace("=", "\\=")) else: escape.append("}") else: if depth == 0: result.append(char) else: escape.append(char) if depth != 0: raise ValueError ("Endpoint description not valid: mismatched opening brace") return "".join(result)
Make it easier to set image alt text
<?php /* * This file is part of the league/commonmark package. * * (c) Colin O'Dell <[email protected]> * * Original code based on the CommonMark JS reference parser (http://bitly.com/commonmarkjs) * - (c) John MacFarlane * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace League\CommonMark\Inline\Element; class Image extends AbstractWebResource { /** * @var InlineCollection */ protected $altText; /** * @param string $url * @param InlineCollection|string $label * @param string $title */ public function __construct($url, $label = null, $title = '') { parent::__construct($url); if (is_string($label)) { $this->altText = new InlineCollection(array(new Text($label))); } else { $this->altText = $label; } if (!empty($title)) { $this->attributes['title'] = $title; } } /** * @return InlineCollection */ public function getAltText() { return $this->altText; } /** * @param InlineCollection $label * * @return $this */ public function setAltText($label) { if (is_string($label)) { $this->altText = new InlineCollection(array(new Text($label))); } else { $this->altText = $label; } return $this; } }
<?php /* * This file is part of the league/commonmark package. * * (c) Colin O'Dell <[email protected]> * * Original code based on the CommonMark JS reference parser (http://bitly.com/commonmarkjs) * - (c) John MacFarlane * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace League\CommonMark\Inline\Element; class Image extends AbstractWebResource { /** * @var InlineCollection */ protected $altText; /** * @param string $url * @param InlineCollection|string $label * @param string $title */ public function __construct($url, $label = null, $title = '') { parent::__construct($url); if (is_string($label)) { $this->altText = new InlineCollection(array(new Text($label))); } else { $this->altText = $label; } if (!empty($title)) { $this->attributes['title'] = $title; } } /** * @return InlineCollection */ public function getAltText() { return $this->altText; } /** * @param InlineCollection $label * * @return $this */ public function setAltText($label) { $this->altText = $label; return $this; } }
admin_programme: Add google+ icon to admin form.
# -*- coding: utf-8 -*- from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder from Instanssi.ext_programme.models import ProgrammeEvent class ProgrammeEventForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ProgrammeEventForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Fieldset( u'Tapahtuma', 'event_type', 'title', 'description', 'start', 'end', 'presenters', 'presenters_titles', 'icon_original', 'email', 'home_url', 'twitter_url', 'github_url', 'facebook_url', 'linkedin_url', 'wiki_url', 'gplus_url', ButtonHolder ( Submit('submit', u'Tallenna') ) ) ) class Meta: model = ProgrammeEvent exclude = ('event','icon_small',)
# -*- coding: utf-8 -*- from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder from Instanssi.ext_programme.models import ProgrammeEvent class ProgrammeEventForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ProgrammeEventForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Fieldset( u'Tapahtuma', 'event_type', 'title', 'description', 'start', 'end', 'presenters', 'presenters_titles', 'icon_original', 'email', 'home_url', 'twitter_url', 'github_url', 'facebook_url', 'linkedin_url', 'wiki_url', ButtonHolder ( Submit('submit', u'Tallenna') ) ) ) class Meta: model = ProgrammeEvent exclude = ('event','icon_small',)
Make `baseUrl` non-final as we should be able to override it.
/* * Copyright 2021, Yurii Serhiichuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.openweathermap.api.query; import lombok.Data; @Data public abstract class AbstractQuery implements Query { @SuppressWarnings({"FieldCanBeLocal", "FieldMayBeFinal"}) /* We'd like to be able to override the base URL. */ private String baseUrl = BASE_URL; private UnitFormat unitFormat; private Language language; @Override public String toStringRepresentation(String apiKey) { StringBuilder stringBuilder = new StringBuilder(baseUrl); stringBuilder.append(getSearchPath()); stringBuilder.append(QUESTION_MARK); if (getLanguage() != null) { stringBuilder.append("lang=").append(getLanguage().getStringRepresentation()).append(AND); } if (getUnitFormat() != null) { stringBuilder.append("units=").append(getUnitFormat().getStringRepresentation()).append(AND); } stringBuilder.append(getRequestPart()); stringBuilder.append(AND).append("appid=").append(apiKey); return stringBuilder.toString(); } protected abstract String getSearchPath(); protected abstract String getRequestPart(); }
/* * Copyright 2021, Yurii Serhiichuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.openweathermap.api.query; import lombok.Data; @Data public abstract class AbstractQuery implements Query { private UnitFormat unitFormat; private Language language; private final String baseUrl = BASE_URL; @Override public String toStringRepresentation(String apiKey) { StringBuilder stringBuilder = new StringBuilder(baseUrl); stringBuilder.append(getSearchPath()); stringBuilder.append(QUESTION_MARK); if (getLanguage() != null) { stringBuilder.append("lang=").append(getLanguage().getStringRepresentation()).append(AND); } if (getUnitFormat() != null) { stringBuilder.append("units=").append(getUnitFormat().getStringRepresentation()).append(AND); } stringBuilder.append(getRequestPart()); stringBuilder.append(AND).append("appid=").append(apiKey); return stringBuilder.toString(); } protected abstract String getSearchPath(); protected abstract String getRequestPart(); }
Add a TODO explaining why tasks.CompletionQueue needs a capacity limit
__all__ = [ 'SocketServer', ] import errno import logging from g1.asyncs.bases import servers from g1.asyncs.bases import tasks LOG = logging.getLogger(__name__) LOG.addHandler(logging.NullHandler()) class SocketServer: def __init__(self, socket, handler): self._socket = socket self._handler = handler async def serve(self): LOG.info('start server: %r', self._socket) with self._socket: async with tasks.CompletionQueue() as queue: await servers.supervise_server( queue, (queue.spawn(self._accept(queue)), ), ) LOG.info('stop server: %r', self._socket) async def _accept(self, queue): # TODO: NOTE: Because we did not set a capacity limit for queue # (CompletionQueue does not support this feature at the moment), # this accept loop could possibly spawn an out-of-control number # of handler tasks. while True: try: sock, addr = await self._socket.accept() except OSError as exc: if exc.errno == errno.EBADF: LOG.info('server socket close: %r', self._socket) break raise LOG.debug('serve client: %r', addr) queue.spawn(self._handler(sock, addr)) def shutdown(self): self._socket.close()
__all__ = [ 'SocketServer', ] import errno import logging from g1.asyncs.bases import servers from g1.asyncs.bases import tasks LOG = logging.getLogger(__name__) LOG.addHandler(logging.NullHandler()) class SocketServer: def __init__(self, socket, handler): self._socket = socket self._handler = handler async def serve(self): LOG.info('start server: %r', self._socket) with self._socket: async with tasks.CompletionQueue() as queue: await servers.supervise_server( queue, (queue.spawn(self._accept(queue)), ), ) LOG.info('stop server: %r', self._socket) async def _accept(self, queue): while True: try: sock, addr = await self._socket.accept() except OSError as exc: if exc.errno == errno.EBADF: LOG.info('server socket close: %r', self._socket) break raise LOG.debug('serve client: %r', addr) queue.spawn(self._handler(sock, addr)) def shutdown(self): self._socket.close()
Change to alternative batch class
#!/usr/bin/env python import os import sys import glob import clawpack.tests as clawtests class FaultTest(clawtests.Test): def __init__(self, deformation_file): super(FaultTest, self).__init__() self.type = "compsys" self.name = "guerrero_gap" self.prefix = os.path.basename(deformation_file).split('.')[0] self.deformation_file = os.path.abspath(deformation_file) self.executable = 'xgeoclaw' # Data objects import setrun self.rundata = setrun.setrun() # Add deformation file self.rundata.dtopo_data.dtopofiles = [] self.rundata.dtopo_data.dtopofiles.append([1,5,5,self.deformation_file]) def __str__(self): output = super(FaultTest, self).__str__() output += "\n Deformation File: %s" % self.deformation_file return output if __name__ == '__main__': if len(sys.argv) > 1: deformation_files = sys.argv[1:] else: deformation_files = glob.glob('./bathy/rot_gap*.xyzt') tests = [] for deformation_file in deformation_files: tests.append(FaultTest(deformation_file)) controller = clawtests.TestController(tests) print controller controller.tar = True controller.run()
#!/usr/bin/env python import os import sys import glob import clawpack.clawutil.tests as clawtests class FaultTest(clawtests.Test): def __init__(self, deformation_file): super(FaultTest, self).__init__() self.type = "compsys" self.name = "guerrero_gap" self.prefix = os.path.basename(deformation_file).split('.')[0] self.deformation_file = os.path.abspath(deformation_file) self.executable = 'xgeoclaw' # Data objects import setrun self.rundata = setrun.setrun() # Add deformation file self.rundata.dtopo_data.dtopofiles = [] self.rundata.dtopo_data.dtopofiles.append([1,5,5,self.deformation_file]) def __str__(self): output = super(FaultTest, self).__str__() output += "\n Deformation File: %s" % self.deformation_file return output if __name__ == '__main__': if len(sys.argv) > 1: deformation_files = sys.argv[1:] else: deformation_files = glob.glob('./bathy/rot_gap*.xyzt') tests = [] for deformation_file in deformation_files: tests.append(FaultTest(deformation_file)) controller = clawtests.TestController(tests) print controller controller.tar = True controller.run()
Use success button for saving
@extends('layout.dashboard') @section('content') <div class="header"> <span class='uppercase'> <i class="fa fa-user"></i> {{ Lang::get('cachet.dashboard.user') }} </span> </div> <div class='content-wrapper'> <div class="row"> <div class="col-sm-12"> @if($updated = Session::get('updated')) <div class='alert alert-{{ $updated ? "success" : "danger" }}'> @if($updated) <strong>Awesome.</strong> Profile updated. @else <strong>Whoops.</strong> Something went wrong when updating. @endif </div> @endif <form name='UserForm' class='form-vertical' role='form' action='/dashboard/user' method='POST'> <fieldset> <div class='form-group'> <label>Username</label> <input type='text' class='form-control' name='username' value='{{ Auth::user()->username }}' required /> </div> <div class='form-group'> <label>Email Address</label> <input type='email' class='form-control' name='email' value='{{ Auth::user()->email }}' required /> </div> <div class='form-group'> <label>Password</label> <input type='password' class='form-control' name='password' value='' /> </div> </fieldset> <button type="submit" class="btn btn-success">Update profile</button> </form> </div> </div> </div> @stop
@extends('layout.dashboard') @section('content') <div class="header"> <span class='uppercase'> <i class="fa fa-user"></i> {{ Lang::get('cachet.dashboard.user') }} </span> </div> <div class='content-wrapper'> <div class="row"> <div class="col-sm-12"> @if($updated = Session::get('updated')) <div class='alert alert-{{ $updated ? "success" : "danger" }}'> @if($updated) <strong>Awesome.</strong> Profile updated. @else <strong>Whoops.</strong> Something went wrong when updating. @endif </div> @endif <form name='UserForm' class='form-vertical' role='form' action='/dashboard/user' method='POST'> <fieldset> <div class='form-group'> <label>Username</label> <input type='text' class='form-control' name='username' value='{{ Auth::user()->username }}' required /> </div> <div class='form-group'> <label>Email Address</label> <input type='email' class='form-control' name='email' value='{{ Auth::user()->email }}' required /> </div> <div class='form-group'> <label>Password</label> <input type='password' class='form-control' name='password' value='' /> </div> </fieldset> <button type="submit" class="btn btn-primary">Update profile</button> </form> </div> </div> </div> @stop
Change versionup to write package.json using 2 space indentation. Add some doco.
var _ = require('underscore'), fs = require('fs'), Toolbelt = require('./toolbelt').Toolbelt, toolbelt = new Toolbelt(); // Charlotte takes care of stuffs that can't be done easily from shell function Charlotte() { var CONF_FILE = 'package.json', conf = JSON.parse(fs.readFileSync(CONF_FILE)); // bump major/minor/build number in package.json's version field function versionup(type) { var version = ((conf.version) ? conf.version : '0.0.0').split('.'); if (type === 'major') { version[0]++; version[1] = 0; version[2] = 0; } else if (type === 'minor') { version[1]++; version[2] = 0; } else { version[2]++; } conf.version = version.join('.'); fs.writeFileSync(CONF_FILE, JSON.stringify(conf, null, 2)); return conf.version; } // process variables in template files function template() { _.keys(conf.bob.template).forEach(function (file) { // TODO: add file check handling var data = fs.readFileSync(file).toString(); conf.bob.template[file].forEach(function (prop) { data = toolbelt.applyFn(data); // TODO: deeper prop handling data = data.replace(new RegExp('\\${' + prop + '}', 'g'), conf[prop]); }); fs.writeFileSync(file, data); }); } return { versionup: versionup, template: template }; } exports.Charlotte = Charlotte;
var _ = require('underscore'), fs = require('fs'), Toolbelt = require('./toolbelt').Toolbelt, toolbelt = new Toolbelt(); function Charlotte() { var CONF_FILE = 'package.json', conf = JSON.parse(fs.readFileSync(CONF_FILE)); function versionup(type) { var version = ((conf.version) ? conf.version : '0.0.0').split('.'); if (type === 'major') { version[0]++; version[1] = 0; version[2] = 0; } else if (type === 'minor') { version[1]++; version[2] = 0; } else { version[2]++; } conf.version = version.join('.'); fs.writeFileSync(CONF_FILE, JSON.stringify(conf, null, 4)); return conf.version; } function template() { _.keys(conf.bob.template).forEach(function (file) { // TODO: add file check handling var data = fs.readFileSync(file).toString(); conf.bob.template[file].forEach(function (prop) { data = toolbelt.applyFn(data); // TODO: deeper prop handling data = data.replace(new RegExp('\\${' + prop + '}', 'g'), conf[prop]); }); fs.writeFileSync(file, data); }); } return { 'versionup': versionup, 'template': template }; } exports.Charlotte = Charlotte;
Allow null peer alias in table if an identity request fails or doesn’t occur before a message packet is available, allow the incomplete peer to be saved. The public key is what’s important.
package pro.dbro.ble.data.model; import net.simonvt.schematic.annotation.AutoIncrement; import net.simonvt.schematic.annotation.DataType; import net.simonvt.schematic.annotation.NotNull; import net.simonvt.schematic.annotation.PrimaryKey; import static net.simonvt.schematic.annotation.DataType.Type.BLOB; import static net.simonvt.schematic.annotation.DataType.Type.INTEGER; import static net.simonvt.schematic.annotation.DataType.Type.TEXT; /** * Created by davidbrodsky on 7/28/14. */ public interface PeerTable { /** SQL type Modifiers Reference Name SQL Column Name */ @DataType(INTEGER) @PrimaryKey @AutoIncrement String id = "_id"; @DataType(TEXT) String alias = "alias"; @DataType(TEXT) @NotNull String lastSeenDate = "last_seen"; @DataType(BLOB) @NotNull String pubKey = "pk"; @DataType(BLOB) String secKey = "sk"; @DataType(BLOB) String rawPkt = "pkt"; }
package pro.dbro.ble.data.model; import net.simonvt.schematic.annotation.AutoIncrement; import net.simonvt.schematic.annotation.DataType; import net.simonvt.schematic.annotation.NotNull; import net.simonvt.schematic.annotation.PrimaryKey; import static net.simonvt.schematic.annotation.DataType.Type.BLOB; import static net.simonvt.schematic.annotation.DataType.Type.INTEGER; import static net.simonvt.schematic.annotation.DataType.Type.TEXT; /** * Created by davidbrodsky on 7/28/14. */ public interface PeerTable { /** SQL type Modifiers Reference Name SQL Column Name */ @DataType(INTEGER) @PrimaryKey @AutoIncrement String id = "_id"; @DataType(TEXT) @NotNull String alias = "alias"; @DataType(TEXT) @NotNull String lastSeenDate = "last_seen"; @DataType(BLOB) @NotNull String pubKey = "pk"; @DataType(BLOB) String secKey = "sk"; @DataType(BLOB) String rawPkt = "pkt"; }
Update trove classifier to Stable. Update my info.
#!/usr/bin/env python try: from setuptools import setup except ImportError: from distutils.core import setup readme = open('README.rst').read() history = open('HISTORY.rst').read().replace('.. :changelog:', '') setup( name='binaryornot', version='0.4.0', description=( 'Ultra-lightweight pure Python package to check ' 'if a file is binary or text.' ), long_description=readme + '\n\n' + history, author='Audrey Roy Greenfeld', author_email='[email protected]', url='https://github.com/audreyr/binaryornot', packages=[ 'binaryornot', ], package_dir={'binaryornot': 'binaryornot'}, include_package_data=True, install_requires=[ 'chardet>=2.0.0', ], license="BSD", zip_safe=False, keywords='binaryornot', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', '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', 'Programming Language :: Python :: 3.5', ], test_suite='tests', )
#!/usr/bin/env python try: from setuptools import setup except ImportError: from distutils.core import setup readme = open('README.rst').read() history = open('HISTORY.rst').read().replace('.. :changelog:', '') setup( name='binaryornot', version='0.4.0', description=( 'Ultra-lightweight pure Python package to check ' 'if a file is binary or text.' ), long_description=readme + '\n\n' + history, author='Audrey Roy', author_email='[email protected]', url='https://github.com/audreyr/binaryornot', packages=[ 'binaryornot', ], package_dir={'binaryornot': 'binaryornot'}, include_package_data=True, install_requires=[ 'chardet>=2.0.0', ], license="BSD", zip_safe=False, keywords='binaryornot', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', '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', ], test_suite='tests', )
Update dependency from mypy-lang to mypy
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import codecs from setuptools import setup def read(fname): file_path = os.path.join(os.path.dirname(__file__), fname) return codecs.open(file_path, encoding='utf-8').read() setup( name='pytest-mypy', version='0.2.0', author='Daniel Bader', author_email='[email protected]', maintainer='Daniel Bader', maintainer_email='[email protected]', license='MIT', url='https://github.com/dbader/pytest-mypy', description='Mypy static type checker plugin for Pytest', long_description=read('README.rst'), py_modules=['pytest_mypy'], install_requires=['pytest>=2.9.2', 'mypy>=0.470'], classifiers=[ 'Development Status :: 4 - Beta', 'Framework :: Pytest', 'Intended Audience :: Developers', 'Topic :: Software Development :: Testing', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Operating System :: OS Independent', 'License :: OSI Approved :: MIT License', ], entry_points={ 'pytest11': [ 'mypy = pytest_mypy', ], }, )
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import codecs from setuptools import setup def read(fname): file_path = os.path.join(os.path.dirname(__file__), fname) return codecs.open(file_path, encoding='utf-8').read() setup( name='pytest-mypy', version='0.2.0', author='Daniel Bader', author_email='[email protected]', maintainer='Daniel Bader', maintainer_email='[email protected]', license='MIT', url='https://github.com/dbader/pytest-mypy', description='Mypy static type checker plugin for Pytest', long_description=read('README.rst'), py_modules=['pytest_mypy'], install_requires=['pytest>=2.9.2', 'mypy-lang>=0.4.5'], classifiers=[ 'Development Status :: 4 - Beta', 'Framework :: Pytest', 'Intended Audience :: Developers', 'Topic :: Software Development :: Testing', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Operating System :: OS Independent', 'License :: OSI Approved :: MIT License', ], entry_points={ 'pytest11': [ 'mypy = pytest_mypy', ], }, )
Update the name of the app
<?php use Symfony\Component\Console\Application; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Finder\Finder; $console = new Application('SMART Search - Livenews. Search view', '0.1'); $app->boot(); $console ->register('assetic:dump') ->setDescription('Dumps all assets to the filesystem') ->setCode(function (InputInterface $input, OutputInterface $output) use ($app) { if (!$app['assetic.enabled']) { return false; } $dumper = $app['assetic.dumper']; if (isset($app['twig'])) { $dumper->addTwigAssets(); } $dumper->dumpAssets(); $output->writeln('<info>Dump finished</info>'); }) ; if (isset($app['cache.path'])) { $console ->register('cache:clear') ->setDescription('Clears the cache') ->setCode(function (InputInterface $input, OutputInterface $output) use ($app) { $cacheDir = $app['cache.path']; $finder = Finder::create()->in($cacheDir)->notName('.gitkeep'); $filesystem = new Filesystem(); $filesystem->remove($finder); $output->writeln(sprintf("%s <info>success</info>", 'cache:clear')); }); } return $console;
<?php use Symfony\Component\Console\Application; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Finder\Finder; $console = new Application('Silex - Kitchen Edition', '0.1'); $app->boot(); $console ->register('assetic:dump') ->setDescription('Dumps all assets to the filesystem') ->setCode(function (InputInterface $input, OutputInterface $output) use ($app) { if (!$app['assetic.enabled']) { return false; } $dumper = $app['assetic.dumper']; if (isset($app['twig'])) { $dumper->addTwigAssets(); } $dumper->dumpAssets(); $output->writeln('<info>Dump finished</info>'); }) ; if (isset($app['cache.path'])) { $console ->register('cache:clear') ->setDescription('Clears the cache') ->setCode(function (InputInterface $input, OutputInterface $output) use ($app) { $cacheDir = $app['cache.path']; $finder = Finder::create()->in($cacheDir)->notName('.gitkeep'); $filesystem = new Filesystem(); $filesystem->remove($finder); $output->writeln(sprintf("%s <info>success</info>", 'cache:clear')); }); } return $console;
Fix Grunt file for local testing
module.exports = function(grunt) { // TODO: platforms shouldn't be hardcoded here var platforms = ['win64']; // Build up array of destinations for Twister deamon files var destinations = {files: []}; platforms.forEach(function (platform) { destinations.files.push({ expand: true, src: ['./twister-data/**'], dest: './builds/Twisting/' + platform + '/' }); }); // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), nodewebkit: { options: { platforms: platforms, buildDir: './builds' }, src: ['./src/**/*', '!./src/twister-data/**/*', '!./src/*.exe', '!./src/*.pak', '!./src/*.dll'] }, copy: { twister: destinations }, less: { development: { files: { "./src/app/styles/style.css": "./src/app/styles/main.less" } } }, auto_install: { subdir: { options: { cwd: 'src', stdout: true, stderr: true, failOnError: true, } } }, }); grunt.loadNpmTasks('grunt-node-webkit-builder'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-auto-install'); grunt.registerTask('build', ['less', 'nodewebkit', 'copy:twister']); grunt.registerTask('compile', ['less']); grunt.registerTask('postinstall', ['auto_install']); };
module.exports = function(grunt) { // TODO: platforms shouldn't be hardcoded here var platforms = ['win64']; // Build up array of destinations for Twister deamon files var destinations = {files: []}; platforms.forEach(function (platform) { destinations.files.push({ expand: true, src: ['./twister-data/**'], dest: './builds/Twisting/' + platform + '/' }); }); // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), nodewebkit: { options: { platforms: platforms, buildDir: './builds' }, src: './src/**/*' }, copy: { twister: destinations }, less: { development: { files: { "./src/app/styles/style.css": "./src/app/styles/main.less" } } }, auto_install: { subdir: { options: { cwd: 'src', stdout: true, stderr: true, failOnError: true, } } }, }); grunt.loadNpmTasks('grunt-node-webkit-builder'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-auto-install'); grunt.registerTask('build', ['less', 'nodewebkit', 'copy:twister']); grunt.registerTask('compile', ['less']); grunt.registerTask('postinstall', ['auto_install']); };
Update the admin interface and demo site generator Update the admin interface to feature a fully responsive, fully retina, cleaned up look and feel based on Bootstrap 3. Simultaniously updated the generated demo site to be more in line with what we use as a starting point for our websites. While this commit is squashed under my name, this is the result of the hard work by too many people to mention by name.
<?php namespace Kunstmaan\TaggingBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Kunstmaan\TaggingBundle\Entity\TagManager; use Kunstmaan\TaggingBundle\Form\DataTransformer\TagsTransformer; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class TagsAdminType extends AbstractType { protected $tagManager; public function __construct(TagManager $tagManager) { $this->tagManager = $tagManager; } public function buildForm(FormBuilderInterface $builder, array $options) { $transformer = new TagsTransformer($this->tagManager); $builder->addViewTransformer($transformer, true); } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults($this->getDefaultOptions(array())); } public function getDefaultOptions(array $options) { $result = array(); foreach ($this->tagManager->findAll() as $tag) { $result[$tag->getId()] = $tag->getName(); } return array( 'choices' => $result, 'multiple' => TRUE, 'required' => false, 'attr' => array( 'class' => 'js-advanced-select form-control advanced-select' ) ); } public function getParent() { return 'choice'; } /** * Returns the name of this type. * * @return string The name of this type */ public function getName() { return 'kunstmaan_taggingbundle_tags'; } }
<?php namespace Kunstmaan\TaggingBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Kunstmaan\TaggingBundle\Entity\TagManager; use Kunstmaan\TaggingBundle\Form\DataTransformer\TagsTransformer; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class TagsAdminType extends AbstractType { protected $tagManager; public function __construct(TagManager $tagManager) { $this->tagManager = $tagManager; } public function buildForm(FormBuilderInterface $builder, array $options) { $transformer = new TagsTransformer($this->tagManager); $builder->addViewTransformer($transformer, true); } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults($this->getDefaultOptions(array())); } public function getDefaultOptions(array $options) { $result = array(); foreach ($this->tagManager->findAll() as $tag) { $result[$tag->getId()] = $tag->getName(); } return array( 'choices' => $result, 'multiple' => TRUE, 'required' => false, 'attr' => array( 'class' => 'chzn-select' ) ); } public function getParent() { return 'choice'; } /** * Returns the name of this type. * * @return string The name of this type */ public function getName() { return 'kunstmaan_taggingbundle_tags'; } }
Add pdb and cif property
'use strict'; const common = module.exports = {}; common.getBasename = function (filename) { let base = filename.replace(/.*\//, ''); return base.replace(/\.[0-9]+$/, ''); }; common.getExtension = function (filename) { let extension = common.getBasename(filename); return extension.replace(/.*\./, '').toLowerCase(); }; common.getFilename = function (typeEntry) { let keys = Object.keys(typeEntry); for (let i = 0; i < keys.length; i++) { if (typeEntry[keys[i]] && typeEntry[keys[i]].filename) { return typeEntry[keys[i]].filename; } } }; common.basenameFind = function (typeEntries, filename) { let reference = common.getBasename(filename); return typeEntries.find(typeEntry => { return common.getBasename(common.getFilename(typeEntry)) === reference; }); }; common.getTargetProperty = function (filename) { switch (common.getExtension(filename)) { case 'jdx': case 'dx': case 'jcamp': return 'jcamp'; case 'png': case 'jpg': case 'jpeg': case 'tif': case 'tiff': return 'image'; case 'cif': return 'cif'; case 'pdb': return 'pdb'; case 'xml': return 'xml'; case 'cdf': case 'netcdf': return 'cdf'; case 'pdf': return 'pdf'; default : return 'file' } };
'use strict'; const common = module.exports = {}; common.getBasename = function (filename) { let base = filename.replace(/.*\//, ''); return base.replace(/\.[0-9]+$/, ''); }; common.getExtension = function (filename) { let extension = common.getBasename(filename); return extension.replace(/.*\./, '').toLowerCase(); }; common.getFilename = function (typeEntry) { let keys = Object.keys(typeEntry); for (let i = 0; i < keys.length; i++) { if (typeEntry[keys[i]] && typeEntry[keys[i]].filename) { return typeEntry[keys[i]].filename; } } }; common.basenameFind = function (typeEntries, filename) { let reference = common.getBasename(filename); return typeEntries.find(typeEntry => { return common.getBasename(common.getFilename(typeEntry)) === reference; }); }; common.getTargetProperty = function (filename) { switch (common.getExtension(filename)) { case 'jdx': case 'dx': case 'jcamp': return 'jcamp'; case 'png': case 'jpg': case 'jpeg': case 'tif': case 'tiff': return 'image'; case 'xml': return 'xml'; case 'cdf': case 'netcdf': return 'cdf'; case 'pdf': return 'pdf'; default : return 'file' } };
Initialize OL6 view projection with OL2 one
import { mainLizmap, mainEventDispatcher } from '../modules/Globals.js'; import olMap from 'ol/Map'; import View from 'ol/View'; /** Class initializing Openlayers Map. */ export default class Map { constructor() { this._olMap = new olMap({ view: new View({ center: [0, 0], zoom: 2, projection: mainLizmap.projection, constrainResolution: true }), target: 'newOlMap' }); // Init view this.syncViews(); // Listen to old map events to dispatch new ones mainLizmap.lizmap3.map.events.on({ moveend: () => { this.syncViews(); mainEventDispatcher.dispatch('map.moveend'); }, zoomend: () => { this.syncViews(); mainEventDispatcher.dispatch('map.zoomend'); } }); } /** * Synchronize new OL view with old one * @memberof Map */ syncViews(){ this._olMap.getView().setResolution(mainLizmap.lizmap3.map.getResolution()); const lizmap3Center = mainLizmap.lizmap3.map.getCenter(); this._olMap.getView().setCenter([lizmap3Center.lon, lizmap3Center.lat]); } }
import { mainLizmap, mainEventDispatcher } from '../modules/Globals.js'; import olMap from 'ol/Map'; import View from 'ol/View'; /** Class initializing Openlayers Map. */ export default class Map { constructor() { this._olMap = new olMap({ view: new View({ center: [0, 0], zoom: 2, constrainResolution: true }), target: 'newOlMap' }); // Init view this.syncViews(); // Listen to old map events to dispatch new ones mainLizmap.lizmap3.map.events.on({ moveend: () => { this.syncViews(); mainEventDispatcher.dispatch('map.moveend'); }, zoomend: () => { this.syncViews(); mainEventDispatcher.dispatch('map.zoomend'); } }); } /** * Synchronize new OL view with old one * @memberof Map */ syncViews(){ this._olMap.getView().setResolution(mainLizmap.lizmap3.map.getResolution()); const lizmap3Center = mainLizmap.lizmap3.map.getCenter(); this._olMap.getView().setCenter([lizmap3Center.lon, lizmap3Center.lat]); } }
Fix pep8 violation in 29e3a0c.
from django.db import connections from django.db.migrations.executor import MigrationExecutor from prometheus_client import Gauge unapplied_migrations = Gauge( 'django_migrations_unapplied_total', 'Count of unapplied migrations by database connection', ['connection']) applied_migrations = Gauge( 'django_migrations_applied_total', 'Count of applied migrations by database connection', ['connection']) def ExportMigrationsForDatabase(alias, executor): plan = executor.migration_plan(executor.loader.graph.leaf_nodes()) unapplied_migrations.labels(alias).set(len(plan)) applied_migrations.labels(alias).set(len( executor.loader.applied_migrations)) def ExportMigrations(): """Exports counts of unapplied migrations. This is meant to be called during app startup, ideally by django_prometheus.apps.AppConfig. """ return if 'default' in connections and ( connections['default']['ENGINE'] == 'django.db.backends.dummy'): # This is the case where DATABASES = {} in the configuration, # i.e. the user is not using any databases. Django "helpfully" # adds a dummy database and then throws when you try to # actually use it. So we don't do anything, because trying to # export stats would crash the app on startup. return for alias in connections.databases: executor = MigrationExecutor(connections[alias]) ExportMigrationsForDatabase(alias, executor)
from django.db import connections from django.db.migrations.executor import MigrationExecutor from prometheus_client import Gauge unapplied_migrations = Gauge( 'django_migrations_unapplied_total', 'Count of unapplied migrations by database connection', ['connection']) applied_migrations = Gauge( 'django_migrations_applied_total', 'Count of applied migrations by database connection', ['connection']) def ExportMigrationsForDatabase(alias, executor): plan = executor.migration_plan(executor.loader.graph.leaf_nodes()) unapplied_migrations.labels(alias).set(len(plan)) applied_migrations.labels(alias).set(len( executor.loader.applied_migrations)) def ExportMigrations(): """Exports counts of unapplied migrations. This is meant to be called during app startup, ideally by django_prometheus.apps.AppConfig. """ return if 'default' in connections and connections['default']['ENGINE'] == 'django.db.backends.dummy': # This is the case where DATABASES = {} in the configuration, # i.e. the user is not using any databases. Django "helpfully" # adds a dummy database and then throws when you try to # actually use it. So we don't do anything, because trying to # export stats would crash the app on startup. return for alias in connections.databases: executor = MigrationExecutor(connections[alias]) ExportMigrationsForDatabase(alias, executor)
Refactor userlistremove for realtime removal
import React from "react"; const fs = window.require("fs"); const global = require("../app/global"); import IO from "../app/IO"; const UserListRemove = React.createClass({ getInitialState: function() { return { collection: [] }; }, componentDidMount: function() { this.createCollectionArray(); }, render: function() { return ( <div className="row"> <ul className="collection col s12"> {this.state.collection} </ul> </div> ); }, createCollectionArray: function() { const io = new IO; let currentCollection = io.readJSON(global.userItems); if (currentCollection === "") return; currentCollection = currentCollection.map((item, i) => { return ( <li key={i} className="collection-item"> <strong>{item.name}</strong> Season:{item.season} Episode:{item.episode} <a href="#" className="secondary-content"> <i onClick={this.handleItemRemove} data-entry={i} className="fa fa-times"></i> </a> </li> ); }); this.setState({collection: currentCollection}); }, handleItemRemove: function(e) { e.preventDefault(); const io = new IO; let currentCollection = this.state.collection; let index = e.target.getAttribute("data-entry"); io.removeJSONEntry(global.userItems, index); currentCollection.splice(index, 1); this.setState({collection: currentCollection}); } }); module.exports = UserListRemove;
import React from "react"; const fs = window.require("fs"); const global = require("../app/global"); import IO from "../app/IO"; const UserListRemove = React.createClass({ render: function() { let collection = []; collection = this.createCollectionArray(); return ( <div className="row"> {collection} </div> ); }, createCollectionArray: function() { const io = new IO; let collection = io.readJSON(global.userItems); collection = collection.map((item, i) => { return ( <li key={i} className="collection-item"> <strong>{item.name}</strong> Season:{item.season} Episode:{item.episode} <a href="#" onClick={this.handleItemRemove} className="secondary-content"> <i data-entry={i} className="fa fa-times"></i> </a> </li> ); }); return ( <ul className="collection col s12"> {collection} </ul> ); }, handleItemRemove: function(e) { e.preventDefault(); const io = new IO; io.removeJSONEntry(global.userItems, e.target.getAttribute("data-entry")); } }); module.exports = UserListRemove;
Fix test under python 3.4
import h2o import socket import threading import unittest import urllib.request SIMPLE_PATH = b'/simple' SIMPLE_BODY = b'<h1>It works!</h1>' class E2eTest(unittest.TestCase): def setUp(self): config = h2o.Config() host = config.add_host(b'default', 65535) host.add_path(SIMPLE_PATH).add_handler(lambda: SIMPLE_BODY) self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True) self.sock.bind(('127.0.0.1', 0)) self.sock.listen(0) self.url_prefix = ( 'http://127.0.0.1:{}'.format(self.sock.getsockname()[1]).encode()) self.loop = h2o.Loop() self.loop.start_accept(self.sock.fileno(), config) threading.Thread(target=self.run_loop, daemon=True).start() def run_loop(self): while self.loop.run() == 0: pass def get(self, path): return urllib.request.urlopen((self.url_prefix + path).decode()).read() def test_simple(self): self.assertEqual(self.get(SIMPLE_PATH), SIMPLE_BODY) if __name__ == '__main__': unittest.main()
import h2o import socket import threading import unittest import urllib.request SIMPLE_PATH = b'/simple' SIMPLE_BODY = b'<h1>It works!</h1>' class E2eTest(unittest.TestCase): def setUp(self): config = h2o.Config() host = config.add_host(b'default', 65535) host.add_path(SIMPLE_PATH).add_handler(lambda: SIMPLE_BODY) self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True) self.sock.bind(('127.0.0.1', 0)) self.sock.listen() self.url_prefix = b'http://127.0.0.1:%d' % self.sock.getsockname()[1] self.loop = h2o.Loop() self.loop.start_accept(self.sock.fileno(), config) threading.Thread(target=self.run_loop, daemon=True).start() def run_loop(self): while self.loop.run() == 0: pass def get(self, path): return urllib.request.urlopen((self.url_prefix + path).decode()).read() def test_simple(self): self.assertEqual(self.get(SIMPLE_PATH), SIMPLE_BODY) if __name__ == '__main__': unittest.main()
Fix addRouteObject when primary is already an object
import fp from 'mostly-func'; const defaultOptions = { field: 'primary', select: '*' }; /** * Add route service object to hook.params */ export default function addRouteObject (name, opts) { opts = Object.assign({}, defaultOptions, opts); return async context => { let options = Object.assign({}, opts); if (context.type !== 'before') { throw new Error(`The 'addRouteObject' hook should only be used as a 'before' hook.`); } if (!options.service || !options.field) { throw new Error('You need to provide a service and a field'); } context.params = context.params || {}; const primary = options.field === 'id'? context.id : context.params[options.field]; if (!primary) { throw new Error(`No primary service id found in the context params`); } if (!context.params[name]) { try { let object = null; if (fp.isIdLike(primary)) { const service = context.app.service(options.service); object = await service.get(primary, { query: { $select: opts.select }, user: context.params.user }); } else { object = primary; } if (!object) { throw new Error(`Not found primary service object ${name} of ${primary}`); } context.params = fp.assoc(name, object, context.params); } catch (err) { throw new Error(`Not found primary service object ${name}: ` + err.message); } } return context; }; }
import fp from 'mostly-func'; const defaultOptions = { field: 'primary', select: '*' }; /** * Add route service object to hook.params */ export default function addRouteObject (name, opts) { opts = Object.assign({}, defaultOptions, opts); return async context => { let options = Object.assign({}, opts); if (context.type !== 'before') { throw new Error(`The 'addRouteObject' hook should only be used as a 'before' hook.`); } if (!options.service || !options.field) { throw new Error('You need to provide a service and a field'); } context.params = context.params || {}; const primary = options.field === 'id'? context.id : context.params[options.field]; if (!primary) { throw new Error(`No primary service id found in the context params`); } if (!context.params[name]) { try { const service = context.app.service(options.service); const object = await service.get(primary, { query: { $select: opts.select }, user: context.params.user }); if (!object) { throw new Error(`Not found primary service object ${name} of ${primary}`); } context.params = fp.assoc(name, object, context.params); } catch (err) { throw new Error(`Not found primary service object ${name}: ` + err.message); } } return context; }; }
Revert "Attempt to catch IE console logs with Stephane's fix" This reverts commit 39088b4e1d5ae0986db615be82ab5dabb1610fe8.
//To get sjhint to ignore protrator calls ad this to .jshint "browser","element","by","expect","protractor","beforeEach" describe('Sign-In Page', function() { //jshint ignore:line var EC = protractor.ExpectedConditions; beforeEach(function() { browser.get('/signin'); browser.driver.sleep(1); browser.waitForAngular(); // spyOn(console, 'error'); }); // it it('should have a title', function() { //jshint ignore:line expect(browser.getTitle()).toEqual('Accounts: Convention on Biological Diversity'); }); // it it('should show alert message when invalid email/password is submitted', function() { //jshint ignore:line element(by.model('email')).sendKeys(1); element(by.model('password')).sendKeys(2); $('.btn-primary').click().then(function() { EC.visibilityOf($('#failedLoginAlert')); }); // browser.debugger(); }); // it it('should not report errors when the page is loaded', function() { if (browser.browserName !== 'internet explorer') { var count = 0; browser.manage().logs().get('browser').then(function(browserLog) { for (var i = 0; i < browserLog.length; i++) { if (browserLog[i].level.name === 'SEVERE'){ count++; console.log('-----------------------',browserLog[i]); } } expect(count).toEqual(0); }); } }); });
//To get sjhint to ignore protrator calls ad this to .jshint "browser","element","by","expect","protractor","beforeEach" describe('Sign-In Page', function() { //jshint ignore:line var EC = protractor.ExpectedConditions; beforeEach(function() { browser.get('/signin'); browser.driver.sleep(1); browser.waitForAngular(); // spyOn(console, 'error'); }); // it it('should have a title', function() { //jshint ignore:line expect(browser.getTitle()).toEqual('Accounts: Convention on Biological Diversity'); }); // it it('should show alert message when invalid email/password is submitted', function() { //jshint ignore:line element(by.model('email')).sendKeys(1); element(by.model('password')).sendKeys(2); $('.btn-primary').click().then(function() { EC.visibilityOf($('#failedLoginAlert')); }); // browser.debugger(); }); // it it('should not report errors when the page is loaded', function() { // if (browser.browserName !== 'internet explorer') { var count = 0; browser.manage().logs().get('browser').then(function(browserLog) { for (var i = 0; i < browserLog.length; i++) { if (browserLog[i].level.name === 'SEVERE'){ count++; console.log('-----------------------',browserLog[i]); } } expect(count).toEqual(0); }); // } }); });
[Event] Change toString method in event
//@@author A0147984L package seedu.address.model.task; public interface ReadOnlyEvent extends ReadOnlyTask { TaskDate getStartDate(); TaskTime getStartTime(); /** * Formats the person as text, showing all contact details. */ default String getAsText() { final StringBuilder builder = new StringBuilder(); builder.append(getName()); if (getStartDate() != null) { builder.append(" Start Date:"); builder.append(getStartDate()); } if (getStartTime() != null) { builder.append(" Start Time:"); builder.append(getStartTime()); } if (getDate() != null) { builder.append(" Due Date:"); builder.append(getDate()); } if (getTime() != null) { builder.append(" Due Time:"); builder.append(getTime()); } if (getDescription() != null) { builder.append(" Description:"); builder.append(getDescription()); } if (getTag() != null) { builder.append(" List:"); builder.append(getTag()); } if (getVenue() != null) { builder.append(" Venue:"); builder.append(getVenue()); } assert getPriority() != null; builder.append(" Priority:"); builder.append(getPriority()); if (isFavorite()) { builder.append(" favorite"); } if (isFinished()) { builder.append(" finished"); } return builder.toString(); } }
//@@author A0147984L package seedu.address.model.task; public interface ReadOnlyEvent extends ReadOnlyTask { TaskDate getStartDate(); TaskTime getStartTime(); /** * Formats the person as text, showing all contact details. */ default String getAsText() { final StringBuilder builder = new StringBuilder(); builder.append(getName()); if (getStartDate() != null) { builder.append(" Start Date:"); builder.append(getDate()); } if (getStartTime() != null) { builder.append(" Start Time:"); builder.append(getTime()); } if (getDate() != null) { builder.append(" Due Date:"); builder.append(getDate()); } if (getTime() != null) { builder.append(" Due Time:"); builder.append(getTime()); } if (getDescription() != null) { builder.append(" Description:"); builder.append(getDescription()); } if (getTag() != null) { builder.append(" List:"); builder.append(getTag()); } if (getVenue() != null) { builder.append(" Venue:"); builder.append(getVenue()); } assert getPriority() != null; builder.append(" Priority:"); builder.append(getPriority()); if (isFavorite()) { builder.append(" favorite"); } if (isFinished()) { builder.append(" finished"); } return builder.toString(); } }
Add sweet alert with timer when performing reorder
import UserProfileStore from '../../stores/UserProfileStore'; export default function moveTreeNode(context, payload, done) { let userid = context.getStore(UserProfileStore).userid; if (userid != null && userid !== '') { let {selector, sourceNode, targetNode, targetIndex} = payload; let sourceSelector = { 'id': selector.id, 'spath': sourceNode.get('path'), 'sid': sourceNode.get('id'), 'stype': sourceNode.get('type') }; let targetSelector = { 'id': selector.id, 'spath': targetNode.get('path'), 'sid': targetNode.get('id'), 'stype': targetNode.get('type') }; swal({ title: 'Refreshing Deck Structure...', text: '', type: 'success', timer: 1000, showCloseButton: false, showCancelButton: false, allowEscapeKey: false, showConfirmButton: false }); context.service.update('decktree.move', { userid, selector, sourceSelector, targetSelector, targetIndex }, {timeout: 20 * 1000}, (err, res) => { if (err) { context.dispatch('MOVE_TREE_NODE_FAILURE', err); } else { context.dispatch('MOVE_TREE_NODE_SUCCESS', payload); } done(null, res); }); } }
import UserProfileStore from '../../stores/UserProfileStore'; export default function moveTreeNode(context, payload, done) { let userid = context.getStore(UserProfileStore).userid; if (userid != null && userid !== '') { let {selector, sourceNode, targetNode, targetIndex} = payload; let sourceSelector = { 'id': selector.id, 'spath': sourceNode.get('path'), 'sid': sourceNode.get('id'), 'stype': sourceNode.get('type') }; let targetSelector = { 'id': selector.id, 'spath': targetNode.get('path'), 'sid': targetNode.get('id'), 'stype': targetNode.get('type') }; context.service.update('decktree.move', { userid, selector, sourceSelector, targetSelector, targetIndex }, {timeout: 20 * 1000}, (err, res) => { if (err) { context.dispatch('MOVE_TREE_NODE_FAILURE', err); } else { context.dispatch('MOVE_TREE_NODE_SUCCESS', payload); } done(null, res); }); } }
ISSUE-35: Check if class has parent class.
<?php declare(strict_types=1); namespace BowlOfSoup\NormalizerBundle\Service\Extractor; use Doctrine\Persistence\Proxy; class MethodExtractor extends AbstractExtractor { /** @var string */ public const TYPE = 'method'; /** * Extract all annotations for a (reflected) class method. * * @param string|object $annotation * * @throws \ReflectionException */ public function extractMethodAnnotations(\ReflectionMethod $objectMethod, $annotation): array { $annotations = []; if ($objectMethod->getDeclaringClass()->implementsInterface(Proxy::class) && false !== $objectMethod->getDeclaringClass()->getParentClass() && empty($this->annotationReader->getMethodAnnotations($objectMethod)) && $objectMethod->getDeclaringClass()->getParentClass()->hasMethod($objectMethod->getName()) ) { $objectMethod = $objectMethod->getDeclaringClass()->getParentClass()->getMethod($objectMethod->getName()); } $methodAnnotations = $this->annotationReader->getMethodAnnotations($objectMethod); foreach ($methodAnnotations as $methodAnnotation) { if ($methodAnnotation instanceof $annotation) { $annotations[] = $methodAnnotation; } } return $annotations; } /** * @param object|string $object * * @throws \ReflectionException */ public function getMethods($object): array { if (!is_object($object)) { return []; } $reflectedClass = new \ReflectionClass($object); return $reflectedClass->getMethods( \ReflectionMethod::IS_PUBLIC | \ReflectionMethod::IS_PROTECTED | \ReflectionMethod::IS_PRIVATE ); } }
<?php declare(strict_types=1); namespace BowlOfSoup\NormalizerBundle\Service\Extractor; use Doctrine\Persistence\Proxy; class MethodExtractor extends AbstractExtractor { /** @var string */ public const TYPE = 'method'; /** * Extract all annotations for a (reflected) class method. * * @param string|object $annotation * * @throws \ReflectionException */ public function extractMethodAnnotations(\ReflectionMethod $objectMethod, $annotation): array { $annotations = []; if ($objectMethod->getDeclaringClass()->implementsInterface(Proxy::class) && empty($this->annotationReader->getMethodAnnotations($objectMethod)) && $objectMethod->getDeclaringClass()->getParentClass()->hasMethod($objectMethod->getName()) ) { $objectMethod = $objectMethod->getDeclaringClass()->getParentClass()->getMethod($objectMethod->getName()); } $methodAnnotations = $this->annotationReader->getMethodAnnotations($objectMethod); foreach ($methodAnnotations as $methodAnnotation) { if ($methodAnnotation instanceof $annotation) { $annotations[] = $methodAnnotation; } } return $annotations; } /** * @param object|string $object * * @throws \ReflectionException */ public function getMethods($object): array { if (!is_object($object)) { return []; } $reflectedClass = new \ReflectionClass($object); return $reflectedClass->getMethods( \ReflectionMethod::IS_PUBLIC | \ReflectionMethod::IS_PROTECTED | \ReflectionMethod::IS_PRIVATE ); } }
Disable Mix for page load tests
<?php declare(strict_types=1); namespace Tests\Feature; use Illuminate\Testing\Fluent\AssertableJson; use Tests\TestCase; class SimpleRequestsTest extends TestCase { /** * Test simple, non-CAS requests load without any authentication. */ public function testUnauthenticatedRequests(): void { $this->withoutMix(); $response = $this->get('/privacy'); $response->assertStatus(200); $response = $this->get('/attendance/kiosk'); $response->assertStatus(200); } /** * Test that the home page loads successfully. */ public function testHome(): void { $this->withoutMix(); $response = $this->actingAs($this->getTestUser(['member']), 'web')->get('/'); $this->assertEquals(200, $response->status(), 'Response content: '.$response->getContent()); $response = $this->actingAs($this->getTestUser(['non-member']), 'web')->get('/'); $this->assertEquals(200, $response->status(), 'Response content: '.$response->getContent()); } /** * Test the info endpoint. */ public function testInfo(): void { $response = $this->get('/api/v1/info'); $response->assertStatus(200); $response->assertJson(static function (AssertableJson $json): void { $json->where('status', 'success') ->has('info', static function (AssertableJson $json): void { $json->where('appName', 'TESTING Apiary') ->where('appEnv', 'testing'); }); }); } }
<?php declare(strict_types=1); namespace Tests\Feature; use Illuminate\Testing\Fluent\AssertableJson; use Tests\TestCase; class SimpleRequestsTest extends TestCase { /** * Test simple, non-CAS requests load without any authentication. */ public function testUnauthenticatedRequests(): void { $response = $this->get('/privacy'); $response->assertStatus(200); $response = $this->get('/attendance/kiosk'); $response->assertStatus(200); } /** * Test that the home page loads successfully. */ public function testHome(): void { $response = $this->actingAs($this->getTestUser(['member']), 'web')->get('/'); $this->assertEquals(200, $response->status(), 'Response content: '.$response->getContent()); $response = $this->actingAs($this->getTestUser(['non-member']), 'web')->get('/'); $this->assertEquals(200, $response->status(), 'Response content: '.$response->getContent()); } /** * Test the info endpoint. */ public function testInfo(): void { $response = $this->get('/api/v1/info'); $response->assertStatus(200); $response->assertJson(static function (AssertableJson $json): void { $json->where('status', 'success') ->has('info', static function (AssertableJson $json): void { $json->where('appName', 'TESTING Apiary') ->where('appEnv', 'testing'); }); }); } }
BB-2045: Update EntityAclExtension to use custom permissions - fixed permissions configuration
<?php namespace Oro\Bundle\SecurityBundle\Migrations\Schema; use Doctrine\DBAL\Types\Type; use Psr\Log\LoggerInterface; use Oro\Bundle\MigrationBundle\Migration\ParametrizedSqlMigrationQuery; class LoadBasePermissionsQuery extends ParametrizedSqlMigrationQuery { /** * {@inheritdoc} */ protected function processQueries(LoggerInterface $logger, $dryRun = false) { $query = 'INSERT INTO oro_security_permission (name, label, is_apply_to_all, group_names, description) ' . 'VALUES (:name, :label, :is_apply_to_all, :group_names, :description)'; $types = [ 'name' => Type::STRING, 'label' => Type::STRING, 'is_apply_to_all' => Type::BOOLEAN, 'group_names' => Type::TARRAY, 'description' => Type::STRING ]; foreach (['VIEW', 'CREATE', 'EDIT', 'DELETE', 'ASSIGN', 'SHARE'] as $permission) { $this->addSql( $query, [ 'name' => $permission, 'label' => $permission, 'is_apply_to_all' => true, 'group_names' => ['default'], 'description' => null ], $types ); } parent::processQueries($logger, $dryRun); } }
<?php namespace Oro\Bundle\SecurityBundle\Migrations\Schema; use Doctrine\DBAL\Types\Type; use Psr\Log\LoggerInterface; use Oro\Bundle\MigrationBundle\Migration\ParametrizedSqlMigrationQuery; class LoadBasePermissionsQuery extends ParametrizedSqlMigrationQuery { /** * {@inheritdoc} */ protected function processQueries(LoggerInterface $logger, $dryRun = false) { $query = 'INSERT INTO oro_security_permission (name, label, is_apply_to_all, group_names, description) ' . 'VALUES (:name, :label, :is_apply_to_all, :group_names, :description)'; $types = [ 'name' => Type::STRING, 'label' => Type::STRING, 'is_apply_to_all' => Type::BOOLEAN, 'group_names' => Type::TARRAY, 'description' => Type::STRING ]; foreach (['VIEW', 'CREATE', 'EDIT', 'DELETE', 'ASSIGN', 'SHARE'] as $permission) { $this->addSql( $query, [ 'name' => $permission, 'label' => $permission, 'is_apply_to_all' => true, 'group_names' => [], 'description' => null ], $types ); } parent::processQueries($logger, $dryRun); } }
Add py3.6 to supported version
import esipy import io from setuptools import setup # install requirements install_requirements = [ "requests", "pyswagger", "six", "pytz", ] # test requirements test_requirements = [ "coverage", "coveralls", "httmock", "nose", "mock", "future", "python-memcached" ] + install_requirements with io.open('README.rst', encoding='UTF-8') as reader: readme = reader.read() setup( name='EsiPy', version=esipy.__version__, packages=['esipy'], url='https://github.com/Kyria/EsiPy', license='BSD 3-Clause License', author='Kyria', author_email='[email protected]', description='Swagger Client for the ESI API for EVE Online', long_description=readme, install_requires=install_requirements, tests_require=test_requirements, test_suite='nose.collector', classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Programming Language :: Python", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", ] )
import esipy import io from setuptools import setup # install requirements install_requirements = [ "requests", "pyswagger", "six", "pytz", ] # test requirements test_requirements = [ "coverage", "coveralls", "httmock", "nose", "mock", "future", "python-memcached" ] + install_requirements with io.open('README.rst', encoding='UTF-8') as reader: readme = reader.read() setup( name='EsiPy', version=esipy.__version__, packages=['esipy'], url='https://github.com/Kyria/EsiPy', license='BSD 3-Clause License', author='Kyria', author_email='[email protected]', description='Swagger Client for the ESI API for EVE Online', long_description=readme, install_requires=install_requirements, tests_require=test_requirements, test_suite='nose.collector', classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Programming Language :: Python", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", ] )
Replace usage of deprecated model.attributes
var Sequelize = require('sequelize'), _ = require('lodash'); module.exports = function(target) { if (target instanceof Sequelize.Model) { // Model createHook(target); } else { // Sequelize instance target.afterDefine(createHook); } } function createHook(model) { model.addHook('beforeFindAfterOptions', function(options) { if (options.role) { var role = options.role, attributes = options.attributes, includes = options.include; options.attributes = attrAccessible(model, role, attributes); cleanIncludesRecursive(includes, role); } }); } function attrAccessible(model, role, attributes) { var attrsToReject = attrProtected(model, role); return rejectAttributes(attributes, attrsToReject); } function attrProtected(model, role) { return _.keys(_.pickBy(model.rawAttributes, function(attr, name) { return !_.isUndefined(attr.access) && ( attr.access === false || attr.access[role] === false ); })); } function rejectAttributes(attributes, attrsToRemove) { return _.reject(attributes, function(attr) { if (_.isArray(attr)) { attr = attr[1]; } return _.includes(attrsToRemove, attr); }); } function cleanIncludesRecursive(includes, role) { _.each(includes, function(include) { var model = include.model, attributes = include.attributes; include.attributes = attrAccessible(model, role, attributes); if (include.include) { cleanIncludesRecursive(include.include, role); } }); }
var Sequelize = require('sequelize'), _ = require('lodash'); module.exports = function(target) { if (target instanceof Sequelize.Model) { // Model createHook(target); } else { // Sequelize instance target.afterDefine(createHook); } } function createHook(model) { model.addHook('beforeFindAfterOptions', function(options) { if (options.role) { var role = options.role, attributes = options.attributes, includes = options.include; options.attributes = attrAccessible(model, role, attributes); cleanIncludesRecursive(includes, role); } }); } function attrAccessible(model, role, attributes) { var attrsToReject = attrProtected(model, role); return rejectAttributes(attributes, attrsToReject); } function attrProtected(model, role) { return _.keys(_.pickBy(model.attributes, function(attr, name) { return !_.isUndefined(attr.access) && ( attr.access === false || attr.access[role] === false ); })); } function rejectAttributes(attributes, attrsToRemove) { return _.reject(attributes, function(attr) { if (_.isArray(attr)) { attr = attr[1]; } return _.includes(attrsToRemove, attr); }); } function cleanIncludesRecursive(includes, role) { _.each(includes, function(include) { var model = include.model, attributes = include.attributes; include.attributes = attrAccessible(model, role, attributes); if (include.include) { cleanIncludesRecursive(include.include, role); } }); }
Change deferred object function to always()
require([ 'backbone', 'collections/category_collection', 'collections/catalog_collection', 'collections/enterprise_customer_collection', 'ecommerce', 'routers/coupon_router', 'utils/navigate' ], function(Backbone, CategoryCollection, CatalogCollection, EnterpriseCustomerCollection, ecommerce, CouponRouter, navigate) { 'use strict'; $(function() { var startApp = function() { var $app = $('#app'), couponApp = new CouponRouter({$el: $app}); couponApp.start(); // Handle navbar clicks. $('a.navbar-brand').on('click', navigate); // Handle internal clicks $app.on('click', 'a', navigate); }; ecommerce.coupons = ecommerce.coupons || {}; ecommerce.coupons.categories = new CategoryCollection(); ecommerce.coupons.categories.url = '/api/v2/coupons/categories/'; ecommerce.coupons.catalogs = new CatalogCollection(); ecommerce.coupons.enterprise_customers = new EnterpriseCustomerCollection(); $.when(ecommerce.coupons.categories.fetch(), ecommerce.coupons.catalogs.fetch(), ecommerce.coupons.enterprise_customers.fetch()).always( startApp()); }); } );
require([ 'backbone', 'collections/category_collection', 'collections/catalog_collection', 'collections/enterprise_customer_collection', 'ecommerce', 'routers/coupon_router', 'utils/navigate' ], function(Backbone, CategoryCollection, CatalogCollection, EnterpriseCustomerCollection, ecommerce, CouponRouter, navigate) { 'use strict'; $(function() { var startApp = function() { var $app = $('#app'), couponApp = new CouponRouter({$el: $app}); couponApp.start(); // Handle navbar clicks. $('a.navbar-brand').on('click', navigate); // Handle internal clicks $app.on('click', 'a', navigate); }; ecommerce.coupons = ecommerce.coupons || {}; ecommerce.coupons.categories = new CategoryCollection(); ecommerce.coupons.categories.url = '/api/v2/coupons/categories/'; ecommerce.coupons.catalogs = new CatalogCollection(); ecommerce.coupons.enterprise_customers = new EnterpriseCustomerCollection(); $.when(ecommerce.coupons.categories.fetch(), ecommerce.coupons.catalogs.fetch(), ecommerce.coupons.enterprise_customers.fetch()).then( startApp(), startApp()); }); } );
Fix FeatureRepo load left join to stories
<?php namespace Neblion\ScrumBundle\Entity; use Doctrine\ORM\EntityRepository; /** * FeatureRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class FeatureRepository extends EntityRepository { public function load($id) { return $this->getEntityManager() ->createQuery( 'SELECT f, p, s FROM NeblionScrumBundle:Feature f INNER JOIN f.project p LEFT JOIN f.stories s WHERE f.id = :id' ) ->setParameter('id', $id) ->getOneOrNullResult(); } public function getListForProject($project_id, $returnQuery = false) { $query = $this->getEntityManager() ->createQuery( 'SELECT f FROM NeblionScrumBundle:Feature f INNER JOIN f.project p WHERE p.id = :project_id ORDER BY f.name' ) ->setParameter('project_id', $project_id); if (!$returnQuery) { return $query->getArrayResult(); } return $query; } }
<?php namespace Neblion\ScrumBundle\Entity; use Doctrine\ORM\EntityRepository; /** * FeatureRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class FeatureRepository extends EntityRepository { public function load($id) { return $this->getEntityManager() ->createQuery( 'SELECT f, p, s FROM NeblionScrumBundle:Feature f INNER JOIN f.project p INNER JOIN f.stories s WHERE f.id = :id' ) ->setParameter('id', $id) ->getOneOrNullResult(); } public function getListForProject($project_id, $returnQuery = false) { $query = $this->getEntityManager() ->createQuery( 'SELECT f FROM NeblionScrumBundle:Feature f INNER JOIN f.project p WHERE p.id = :project_id ORDER BY f.name' ) ->setParameter('project_id', $project_id); if (!$returnQuery) { return $query->getArrayResult(); } return $query; } }
Fix React Hot Loader, use ‘react-hot-loader/webpack.’
import path from 'path'; const isProduction = process.env.NODE_ENV === 'production'; export default { context: path.join(__dirname, '../'), entry: undefined, output: undefined, // Resolve the `./src` directory so we can avoid writing // ../../styles/base.css resolve: { modulesDirectories: [ 'node_modules', './src' ], extensions: [ '', '.js', '.jsx', '.svg' ] }, resolveLoader: { modulesDirectories: [ 'node_modules', './webpack/loaders' ] }, // Instruct webpack how to handle each file type that it might encounter module: { loaders: [ { test: /\.js[x]?$/, exclude: /node_modules/, loaders: (function() { const loaders = ['babel-loader']; if (!isProduction) { loaders.unshift('react-hot-loader/webpack'); } return loaders; })() }, { test: /json-formatter-js\/src\/\w+.js$/, loader: 'babel-loader' }, { test: /\.css$/, loader: 'style-loader!css-loader' }, { test: /\.(png|jpg)$/, loader: 'file-loader?name=images/[name].[ext]' }, { test: /\.(svg)$/, loader: 'svg-loader' } ] }, };
import path from 'path'; const isProduction = process.env.NODE_ENV === 'production'; export default { context: path.join(__dirname, '../'), entry: undefined, output: undefined, // Resolve the `./src` directory so we can avoid writing // ../../styles/base.css resolve: { modulesDirectories: [ 'node_modules', './src' ], extensions: [ '', '.js', '.jsx', '.svg' ] }, resolveLoader: { modulesDirectories: [ 'node_modules', './webpack/loaders' ] }, // Instruct webpack how to handle each file type that it might encounter module: { loaders: [ { test: /\.js[x]?$/, exclude: /node_modules/, loaders: (function() { const loaders = ['babel-loader']; if (!isProduction) { loaders.unshift('react-hot'); } return loaders; })() }, { test: /json-formatter-js\/src\/\w+.js$/, loader: 'babel-loader' }, { test: /\.css$/, loader: 'style-loader!css-loader' }, { test: /\.(png|jpg)$/, loader: 'file-loader?name=images/[name].[ext]' }, { test: /\.(svg)$/, loader: 'svg-loader' } ] }, };
Improve fenced code block parser's handling of closing fences.
<?php namespace FluxBB\Markdown\Parser; use FluxBB\Markdown\Common\Text; use FluxBB\Markdown\Node\CodeBlock; class FencedCodeBlockParser extends AbstractParser { /** * Parse the given block content. * * Any newly created nodes should be pushed to the stack. Any remaining content should be passed to the next parser * in the chain. * * @param Text $block * @return void */ public function parseBlock(Text $block) { $block->handle('{ (?:\n\n|\A) (?: ( #1 fence ([`~]) #2 the fence character (` or ~) \2{2,} # at least two remaining fence characters ) [ ]* ([a-zA-Z0-9]*?)? #3 code language [optional] \n+ (.*?)\n #4 code block \1\2* # closing fence - at least as long as the opening one ) }smx', function (Text $whole, Text $fence, Text $fenceChar, Text $lang, Text $code) { $code->escapeHtml(ENT_NOQUOTES); /*$this->markdown->emit('detab', array($code)); $code->replace('/\A\n+/', ''); $code->replace('/\s+\z/', '');*/ $this->stack->acceptCodeBlock(new CodeBlock($code)); }, function (Text $part) { $this->next->parseBlock($part); }); } }
<?php namespace FluxBB\Markdown\Parser; use FluxBB\Markdown\Common\Text; use FluxBB\Markdown\Node\CodeBlock; class FencedCodeBlockParser extends AbstractParser { /** * Parse the given block content. * * Any newly created nodes should be pushed to the stack. Any remaining content should be passed to the next parser * in the chain. * * @param Text $block * @return void */ public function parseBlock(Text $block) { $block->handle('{ (?:\n\n|\A) (?: ([`~]{3})[ ]* #1 fence ` or ~ ([a-zA-Z0-9]*?)? #2 language [optional] \n+ (.*?)\n #3 code block \1 # matched #1 ) }smx', function (Text $w, Text $fence, Text $lang, Text $code) { $code->escapeHtml(ENT_NOQUOTES); /*$this->markdown->emit('detab', array($code)); $code->replace('/\A\n+/', ''); $code->replace('/\s+\z/', '');*/ $this->stack->acceptCodeBlock(new CodeBlock($code)); }, function (Text $part) { $this->next->parseBlock($part); }); } }
Add redis_client to unit test
<?php namespace Noxlogic\RateLimitBundle\Tests\DependencyInjection; use Noxlogic\RateLimitBundle\DependencyInjection\Configuration; use Symfony\Bundle\FrameworkBundle\Tests\Functional\WebTestCase; use Symfony\Component\Config\Definition\Processor; /** * ConfigurationTest */ class ConfigurationTest extends WebTestCase { /** * @var Processor */ private $processor; public function setUp() { $this->processor = new Processor(); } private function getConfigs(array $configArray) { $configuration = new Configuration(); return $this->processor->processConfiguration($configuration, array($configArray)); } public function testUnconfiguredConfiguration() { $configuration = $this->getConfigs(array()); $this->assertSame(array( 'storage_engine' => 'redis', 'redis_client' => 'default_client', 'rate_response_code' => 429, 'rate_response_message' => 'You exceeded the rate limit', 'display_headers' => true, 'headers' => array( 'limit' => 'X-RateLimit-Limit', 'remaining' => 'X-RateLimit-Remaining', 'reset' => 'X-RateLimit-Reset', ), ), $configuration); } }
<?php namespace Noxlogic\RateLimitBundle\Tests\DependencyInjection; use Noxlogic\RateLimitBundle\DependencyInjection\Configuration; use Symfony\Bundle\FrameworkBundle\Tests\Functional\WebTestCase; use Symfony\Component\Config\Definition\Processor; /** * ConfigurationTest */ class ConfigurationTest extends WebTestCase { /** * @var Processor */ private $processor; public function setUp() { $this->processor = new Processor(); } private function getConfigs(array $configArray) { $configuration = new Configuration(); return $this->processor->processConfiguration($configuration, array($configArray)); } public function testUnconfiguredConfiguration() { $configuration = $this->getConfigs(array()); $this->assertSame(array( 'storage_engine' => 'redis', 'rate_response_code' => 429, 'rate_response_message' => 'You exceeded the rate limit', 'display_headers' => true, 'headers' => array( 'limit' => 'X-RateLimit-Limit', 'remaining' => 'X-RateLimit-Remaining', 'reset' => 'X-RateLimit-Reset', ), ), $configuration); } }
Return stub request object on concurrent request
var qajax = require("qajax"); var uniqueCalls = []; function removeCall(options) { uniqueCalls.splice(uniqueCalls.indexOf(options.url), 1); } var qajaxWrapper = function (options) { if (!options.concurrent) { if (uniqueCalls.indexOf(options.url) > -1) { return { error: () => { return this; }, success: function () { return this; } }; } uniqueCalls.push(options.url); } var response = { status: null, body: null }; var parseResponse = function (xhr) { response.status = xhr.status; try { response.body = JSON.parse(xhr.responseText); } catch (e) { response.body = xhr.responseText; } }; var api = qajax(options); api.error = function (callback) { var promise = this; // Bind callback also for non 200 status promise.then( // not a 2* response function (xhr) { if (xhr.status.toString()[0] !== "2") { parseResponse(xhr); removeCall(options); callback(response); } }, // the promise is only rejected if the server has failed // to reply to the client (network problem or timeout reached). function (xhr) { parseResponse(xhr); removeCall(options); callback(response); } ); return promise; }; api.success = function (callback) { var promise = this; promise .then(qajax.filterStatus(function (status) { return status.toString()[0] === "2"; })) .then(function (xhr) { parseResponse(xhr); removeCall(options); callback(response); }); return promise; }; return api; }; module.exports = qajaxWrapper;
var qajax = require("qajax"); var qajaxWrapper = function (options) { var response = { status: null, body: null }; var parseResponse = function (xhr) { response.status = xhr.status; try { response.body = JSON.parse(xhr.responseText); } catch (e) { response.body = xhr.responseText; } }; var api = qajax(options); api.error = function (callback) { var promise = this; // Bind callback also for non 200 status promise.then( // not a 2* response function (xhr) { if (xhr.status.toString()[0] !== "2") { parseResponse(xhr); callback(response); } }, // the promise is only rejected if the server has failed // to reply to the client (network problem or timeout reached). function (xhr) { parseResponse(xhr); callback(response); } ); return promise; }; api.success = function (callback) { var promise = this; promise .then(qajax.filterStatus(function (status) { return status.toString()[0] === "2"; })) .then(function (xhr) { parseResponse(xhr); callback(response); }); return promise; }; return api; }; module.exports = qajaxWrapper;
Remove conditional of window width for start carrousel logos
/** * The Footer view. */ define([ 'jquery', 'backbone', 'slick' ], function($,Backbone,slick) { 'use strict'; var FooterView = Backbone.View.extend({ el: '#footerView', initialize: function() { // CACHE this.$logos = $('#footer-logos'); this.$footerFixed = $('#footerFixed'); this.$footerToggle = $('#footerToggle'); this.$footerClose = $('#footerClose'); //INIT this.$logos.slick({ infinite: true, slidesToShow: 5, slidesToScroll: 5, speed: 500, autoplay: true, autoplaySpeed: 3000 }); this.setListeners(); }, setListeners: function(){ if (this.$footerFixed.length) { this.$footerToggle.on('click',_.bind(function(e){ ga('send', 'event', 'Map', 'Toggle', 'Footer'); this.$footerFixed.toggleClass('active'); (this.$footerFixed.hasClass('active')) ? this.$footerToggle.text('Hide footer') : this.$footerToggle.text('Show footer'); }, this )); // this.$footerClose.on('click',_.bind(function(e){ // this.$footerFixed.removeClass('active'); // }, this )); } } }); return FooterView; });
/** * The Footer view. */ define([ 'jquery', 'backbone', 'slick' ], function($,Backbone,slick) { 'use strict'; var FooterView = Backbone.View.extend({ el: '#footerView', initialize: function() { // CACHE this.$logos = $('#footer-logos'); this.$footerFixed = $('#footerFixed'); this.$footerToggle = $('#footerToggle'); this.$footerClose = $('#footerClose'); //INIT if ($(window).width() >= 850) { this.$logos.slick({ infinite: true, slidesToShow: 5, slidesToScroll: 5, speed: 500, autoplay: true, autoplaySpeed: 3000 }); } this.setListeners(); }, setListeners: function(){ if (this.$footerFixed.length) { this.$footerToggle.on('click',_.bind(function(e){ ga('send', 'event', 'Map', 'Toggle', 'Footer'); this.$footerFixed.toggleClass('active'); (this.$footerFixed.hasClass('active')) ? this.$footerToggle.text('Hide footer') : this.$footerToggle.text('Show footer'); }, this )); // this.$footerClose.on('click',_.bind(function(e){ // this.$footerFixed.removeClass('active'); // }, this )); } } }); return FooterView; });
Add check do we have Add Company button in Create Company Form test
<?php namespace Tests; use App\User; use App\Company; use Illuminate\Foundation\Testing\WithoutMiddleware; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; class CompanyCreateFormTest extends \TestCase { use DatabaseTransactions; public function test_companies_can_be_created_by_admin() { $user = factory(User::class, 'admin')->create(); $this->actingAs($user); $companyName = 'Company ' . time(); $this->visit('/companies') ->dontSee($companyName); $this->visit('/companies') ->dontSee('User is not authorised to Create Company.') ->see('Add Company') // button ->type($companyName, 'name') ->press('Add Company') ->see($companyName) ->seeInDatabase('companies', ['name' => $companyName]); } public function test_long_companies_cant_be_created() { $user = factory(User::class, 'admin')->create(); $this->actingAs($user); $this->visit('/companies') ->type(str_random(300), 'name') ->press('Add Company') ->see('Whoops!'); } public function test_companies_cannot_be_created_by_viewer() { $user = factory(User::class, 'viewer')->create(); $this->actingAs($user); $this->visit('/companies') ->see('User is not authorised to Create Company.') ->dontSee('Add Company'); } }
<?php namespace Tests; use App\User; use App\Company; use Illuminate\Foundation\Testing\WithoutMiddleware; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; class CompanyCreateFormTest extends \TestCase { use DatabaseTransactions; public function test_companies_can_be_created_by_admin() { $user = factory(User::class, 'admin')->create(); $this->actingAs($user); $companyName = 'Company ' . time(); $this->visit('/companies') ->dontSee($companyName); $this->visit('/companies') ->dontSee('User is not authorised to Create Company.') ->type($companyName, 'name') ->press('Add Company') ->see($companyName) ->seeInDatabase('companies', ['name' => $companyName]); } public function test_long_companies_cant_be_created() { $user = factory(User::class, 'admin')->create(); $this->actingAs($user); $this->visit('/companies') ->type(str_random(300), 'name') ->press('Add Company') ->see('Whoops!'); } public function test_companies_cannot_be_created_by_viewer() { $user = factory(User::class, 'viewer')->create(); $this->actingAs($user); $this->visit('/companies') ->see('User is not authorised to Create Company.') ->dontSee('Add Company'); } }
Reduce amount of information in reference links
define(['rules/rules.module' ], function() { angular.module('rules').factory('references', [ function() { function generateReference(query) { var bindings = []; angular.forEach(query.bindings, function(binding) { if ('id' in binding) { bindings.push(binding.id); } }); var info = { rule: query.rule, query: query.query, bindings: bindings, constraints: query.constraints }; var url = ('#/rules/explain?inference=' + encodeURIComponent(angular.toJson(info, false))); var reference = { P854: [{ datatype: 'url', datavalue: { type: 'string', value: url }, snaktype: 'value', property: 'P854' }] }; return [{ snaks: reference, 'snaks-order': ['P854'] }]; } return { generateReference: generateReference }; }]); return {}; });
define(['rules/rules.module' ], function() { angular.module('rules').factory('references', [ function() { function generateReference(query) { var url = ('#/rules/explain?inference=' + encodeURIComponent(angular.toJson(query, false))); var reference = { P854: [{ datatype: 'url', datavalue: { type: 'string', value: url }, snaktype: 'value', property: 'P854' }] }; return [{ snaks: reference, 'snaks-order': ['P854'] }]; } return { generateReference: generateReference }; }]); return {}; });
Exclude more categories to make generating site faster
<?php get_header(); if (have_posts()) { while (have_posts()) { the_post(); ?> <div class="blogPost"> <?php the_content(); ?> <?php if (is_page("tags")) { ?> <ul class="tagList"> <?php wp_list_categories( array( "hierarchical" => 1, "title_li" => __(""), "show_count" => 1, "depth" => 0, "exclude" => "1,7,11,148" ) ); ?> </ul> <ul class="tagList"> <?php wp_get_archives( array( "type" => "yearly" ) ); ?> </ul> <ul class="tagList"> <?php wp_get_archives( array( "type" => "monthly" ) ); ?> </ul> <ul class="tagList"> <?php wp_get_archives( array( "type" => "daily" ) ); ?> </ul> <?php } ?> </div> <?php } } get_footer(); ?>
<?php get_header(); if (have_posts()) { while (have_posts()) { the_post(); ?> <div class="blogPost"> <?php the_content(); ?> <?php if (is_page("tags")) { ?> <ul class="tagList"> <?php wp_list_categories( array( "hierarchical" => 1, "title_li" => __(""), "show_count" => 1, "depth" => 0, "exclude" => "1,7" ) ); ?> </ul> <ul class="tagList"> <?php wp_get_archives( array( "type" => "yearly" ) ); ?> </ul> <ul class="tagList"> <?php wp_get_archives( array( "type" => "monthly" ) ); ?> </ul> <ul class="tagList"> <?php wp_get_archives( array( "type" => "daily" ) ); ?> </ul> <?php } ?> </div> <?php } } get_footer(); ?>
Fix issue with Accept-Language header for certain system languages. The proper Locale was not being used when calling String.format(), which was causing the resulting HTTP requests to fail. Bug: T118910 Change-Id: I09e8c57d92eb969de816ed5025ad17f66aec386c
package org.wikipedia.interlanguage; import android.support.annotation.NonNull; import java.util.Locale; public final class AcceptLanguageUtil { private static final float APP_LANGUAGE_QUALITY = .9f; private static final float SYSTEM_LANGUAGE_QUALITY = .8f; /** * @return The value that should go in the Accept-Language header. */ @NonNull public static String getAcceptLanguage(@NonNull String siteLanguageCode, @NonNull String appLanguageCode, @NonNull String systemLanguageCode) { String acceptLanguage = siteLanguageCode; acceptLanguage = appendToAcceptLanguage(acceptLanguage, appLanguageCode, APP_LANGUAGE_QUALITY); acceptLanguage = appendToAcceptLanguage(acceptLanguage, systemLanguageCode, SYSTEM_LANGUAGE_QUALITY); return acceptLanguage; } @NonNull private static String appendToAcceptLanguage(@NonNull String acceptLanguage, @NonNull String languageCode, float quality) { // If accept-language already contains the language, just return accept-language. if (acceptLanguage.contains(languageCode)) { return acceptLanguage; } // If accept-language is empty, don't append. Just return the language. if (acceptLanguage.isEmpty()) { return languageCode; } // Accept-language is nonempty, append the language. return String.format(Locale.ROOT, "%s,%s;q=%.1f", acceptLanguage, languageCode, quality); } private AcceptLanguageUtil() { } }
package org.wikipedia.interlanguage; import android.support.annotation.NonNull; public final class AcceptLanguageUtil { private static final float APP_LANGUAGE_QUALITY = .9f; private static final float SYSTEM_LANGUAGE_QUALITY = .8f; /** * @return The value that should go in the Accept-Language header. */ @NonNull public static String getAcceptLanguage(@NonNull String siteLanguageCode, @NonNull String appLanguageCode, @NonNull String systemLanguageCode) { String acceptLanguage = siteLanguageCode; acceptLanguage = appendToAcceptLanguage(acceptLanguage, appLanguageCode, APP_LANGUAGE_QUALITY); acceptLanguage = appendToAcceptLanguage(acceptLanguage, systemLanguageCode, SYSTEM_LANGUAGE_QUALITY); return acceptLanguage; } @NonNull private static String appendToAcceptLanguage(@NonNull String acceptLanguage, @NonNull String languageCode, float quality) { // If accept-language already contains the language, just return accept-language. if (acceptLanguage.contains(languageCode)) { return acceptLanguage; } // If accept-language is empty, don't append. Just return the language. if (acceptLanguage.isEmpty()) { return languageCode; } // Accept-language is nonempty, append the language. return String.format("%s,%s;q=%.1f", acceptLanguage, languageCode, quality); } private AcceptLanguageUtil() { } }
Remove text align center from status and toasts in the header.
import { HeaderService } from "./header.service.js"; export class HeaderTemplate { static update(render) { const start = Date.now(); /* eslint-disable indent */ render` <nav class="flex flex-row bt bb mw9 center shadow-2"> <div class="flex flex-wrap flex-row justify-around items-center min-w-70 logo"> <span class="b"> <a href="https://github.com/albertosantini/node-conpa">ConPA 5</a> Asset Allocation App </span> </div> <div class="flex flex-wrap flex-row items-center min-w-30> <span class="f7"> <toasts></toasts> <div>${{ any: HeaderService.getStatus().then(({ namespace: status }) => { const end = Date.now(); return `${status.message} (${end - start}ms)`; }), placeholder: "Loading..." }}</div> </span> </div> </nav> `; /* eslint-enable indent */ } }
import { HeaderService } from "./header.service.js"; export class HeaderTemplate { static update(render) { const start = Date.now(); /* eslint-disable indent */ render` <nav class="flex flex-row bt bb tc mw9 center shadow-2"> <div class="flex flex-wrap flex-row justify-around items-center min-w-70 logo"> <span class="b"> <a href="https://github.com/albertosantini/node-conpa">ConPA 5</a> Asset Allocation App </span> </div> <div class="flex flex-wrap flex-row items-center min-w-30> <span class="f7"> <toasts></toasts> <div>${{ any: HeaderService.getStatus().then(({ namespace: status }) => { const end = Date.now(); return `${status.message} (${end - start}ms)`; }), placeholder: "Loading..." }}</div> </span> </div> </nav> `; /* eslint-enable indent */ } }
Raise Exception when there's an HTTP error
import urllib from extutils import get_filename from template import render import requests import yaml import jsonschema SCHEMA = { '$schema': 'http://json-schema.org/draft-04/schema#', 'description': 'Describes the extract extension handler input', 'type':'object', 'properties': { 'url': { 'description': 'Where to download the tarball/zip/etc from', 'type':'string' }, 'username': { 'description': 'Username to login with BASIC Auth', 'type':'string' }, 'password': { 'description': 'Password to use with BASIC Auth', 'type':'string' } }, 'required': ['url'] } def _download_file(url, handle, auth=None): r = requests.get(url, auth=auth, stream=True) r.raise_for_status() for chunk in r.iter_content(chunk_size=4096): if chunk: # filter out keep-alive new chunks handle.write(chunk) handle.close() def ext_download(loader, inputhash, abs_source, dest, **kwargs): """ Downloads a ~download file""" contents = yaml.load(render(abs_source, inputhash, loader)) jsonschema.validate(contents, SCHEMA) finalfile = get_filename(dest) handle = open(finalfile, 'w') auth = None if 'username' in contents and 'password' in contents: auth = (contents['username'], contents['password']) _download_file(contents['url'], handle, auth) return finalfile
import urllib from extutils import get_filename from template import render import requests import yaml import jsonschema SCHEMA = { '$schema': 'http://json-schema.org/draft-04/schema#', 'description': 'Describes the extract extension handler input', 'type':'object', 'properties': { 'url': { 'description': 'Where to download the tarball/zip/etc from', 'type':'string' }, 'username': { 'description': 'Username to login with BASIC Auth', 'type':'string' }, 'password': { 'description': 'Password to use with BASIC Auth', 'type':'string' } }, 'required': ['url'] } def _download_file(url, handle, auth=None): r = requests.get(url, auth=auth, stream=True) for chunk in r.iter_content(chunk_size=4096): if chunk: # filter out keep-alive new chunks handle.write(chunk) handle.close() def ext_download(loader, inputhash, abs_source, dest, **kwargs): """ Downloads a ~download file""" contents = yaml.load(render(abs_source, inputhash, loader)) jsonschema.validate(contents, SCHEMA) finalfile = get_filename(dest) handle = open(finalfile, 'w') auth = None if 'username' in contents and 'password' in contents: auth = (contents['username'], contents['password']) _download_file(contents['url'], handle, auth) return finalfile
Create BLL for profile - edit js files
$(document).ready(function () { var tokenKey = sessionStorage.getItem() function AppViewModel() { var self = this; self.FirstName = ko.observable(""); self.SecondName = ko.observable(""); self.About = ko.observable(""); self.Picture = ko.observable(""); self.fullName = ko.computed(function () { return self.FirstName() + " " + self.SecondName(); }, this); $.ajax({ url: "api/profile", contentType: "application/json", type: "GET", header: {"Authorization " : " Bearer " + sessionStorage.getItem(tokenKey) }, // + sessionStorage.getItem(tokenKey) success: function (data) { self.FirstName(data.firstName); self.SecondName(data.secondName); self.About(data.about); self.Picture(data.picture); }, error: function (data) { alert("error occured"); } }); } // Activates knockout.js // bind view model to referring view ko.applyBindings(new AppViewModel()); });
$(document).ready(function () { function AppViewModel() { var self = this; self.FirstName = ko.observable(""); self.SecondName = ko.observable(""); self.About = ko.observable(""); self.Picture = ko.observable(""); self.fullName = ko.computed(function () { return self.FirstName() + " " + self.SecondName(); }, this); $.ajax({ url: "http://localhost:51952/api/profile", contentType: "application/json", type: "GET", header:{"Authorization" : "Bearer "+ sessionStorage.getItem(tokenKey) }, success: function (data) { self.FirstName(data.firstName); self.SecondName(data.secondName); self.About(data.about); self.Picture(data.picture); }, error: function (data) { alert("error occured"); } }); } // Activates knockout.js // bind view model to referring view ko.applyBindings(new AppViewModel()); });
Add default value for customer getAll
export default function CustomersResource({apiHandler}) { return { async getAll({limit = null, offset = null, sort = null, expand = '', filter = '', q = '', criteria = ''} = {}) { const params = { limit, offset, sort, expand, filter, q, criteria }; return await apiHandler.getAll(`customers`, params); }, async get({id}) { return await apiHandler.get(`customers/${id}`); }, async create({id = '', data}) { return await apiHandler.create(`customers/${id}`, data); }, async update({id, data}) { return await apiHandler.put(`customers/${id}`, data); }, async getLeadSource({id}) { return await apiHandler.get(`customers/${id}/lead-source`); }, async createLeadSource({id, data}) { return await apiHandler.put(`customers/${id}/lead-source`, data); }, async deleteLeadSource({id}) { return await apiHandler.delete(`customers/${id}/lead-source`); } }; };
export default function CustomersResource({apiHandler}) { return { async getAll({limit = null, offset = null, sort = null, expand = '', filter = '', q = '', criteria = ''}) { const params = { limit, offset, sort, expand, filter, q, criteria }; return await apiHandler.getAll(`customers`, params); }, async get({id}) { return await apiHandler.get(`customers/${id}`); }, async create({id = '', data}) { return await apiHandler.create(`customers/${id}`, data); }, async update({id, data}) { return await apiHandler.put(`customers/${id}`, data); }, async getLeadSource({id}) { return await apiHandler.get(`customers/${id}/lead-source`); }, async createLeadSource({id, data}) { return await apiHandler.put(`customers/${id}/lead-source`, data); }, async deleteLeadSource({id}) { return await apiHandler.delete(`customers/${id}/lead-source`); } }; };
Change the way the test works with the command
/* global describe global it */ const chai = require('chai') const exec = require('child_process').exec const path = require('path') var assert = chai.assert console.log('Testing the app') var cmd = 'node ' + path.join(__dirname, '../index.js') + ' ' describe('Conversion Params', function () { // Further code for tests goes here it('If no params', function (done) { // Test implementation goes here exec(`${cmd}`, function (err, stdout, stderr) { assert.isNotNull(err) done() }) }) it('If no amount', function (done) { exec(`${cmd} --f=USD --to=EUR --ouput=fulls`, function (err, stdout, stderr) { assert.isNull(err) assert.strictEqual(stdout, 'Amount param should be defined\n') done() }) }) }) describe('Conversion Logic', function () { it('If currency does not exist', function (done) { exec(`${cmd} --f=USDG --to=EURs --ouput=fulls 1`, function (err, stdout, stderr) { assert.isNull(err) assert.strictEqual(stdout, 'Currency no supported or bad spell\n') done() }) }) it('If conversion is good', function (done) { exec(`${cmd} --f=USD --to=EUR --ouput=fulls 1`, function (err, stdout, stderr) { assert.isNull(err) var result = stdout.split(' ') assert.isNotNull(result[0]) assert.isNumber(parseInt(result[0])) done() }) }) })
const chai = require('chai') const exec = require('child_process').exec var assert = chai.assert console.log('Testing the app') describe('Conversion Params', function () { // Further code for tests goes here it('If no params', function (done) { // Test implementation goes here exec('currencyconv', function (err, stdout, stderr) { assert.isNotNull(err) done() }) }) it('If no amount', function (done) { exec('currencyconv --f=USD --to=EUR --ouput=fulls', function (err, stdout, stderr) { assert.isNull(err) assert.strictEqual(stdout, 'Amount param should be defined\n') done() }) }) }) describe('Conversion Logic', function () { it('If currency does not exist', function (done) { exec('currencyconv --f=USDG --to=EURs --ouput=fulls 1', function (err, stdout, stderr) { assert.isNull(err) assert.strictEqual(stdout, 'Currency no supported or bad spell\n') done() }) }) it('If conversion is good', function (done) { exec('currencyconv --f=USD --to=EUR --ouput=fulls 1', function (err, stdout, stderr) { assert.isNull(err) var result = stdout.split(' ') assert.isNotNull(result[0]) assert.isNumber(parseInt(result[0])) done() }) }) })
Make tab spacing on render optional Added a very simple optional variable when using `render()` to allow alternate line indentations (or none).
<?php /** * @package Opengraph * @author Axel Etcheverry <[email protected]> * @copyright Copyright (c) 2011 Axel Etcheverry (http://www.axel-etcheverry.com) * Displays <a href="http://creativecommons.org/licenses/MIT/deed.fr">MIT</a> * @license http://creativecommons.org/licenses/MIT/deed.fr MIT */ /** * @namespace */ namespace Opengraph; class Writer extends Opengraph { /** * @var \ArrayObject */ protected static $storage; /** * @var Integer */ //protected static $position; /** * Append meta * * @param String $property * @param String $content * @return \Opengraph\Opengraph */ public function append($property, $content) { return $this->addMeta($property, $content, self::APPEND); } /** * Prepend meta * * @param String $property * @param String $content * @return \Opengraph\Opengraph */ public function prepend($property, $content) { return $this->addMeta($property, $content, self::PREPEND); } /** * Render all meta tags * * @return String */ public function render($indent = "\t") { $html = ''; foreach(self::$storage as $meta) { $html .= $indent . $meta->render() . PHP_EOL; } return $html; } }
<?php /** * @package Opengraph * @author Axel Etcheverry <[email protected]> * @copyright Copyright (c) 2011 Axel Etcheverry (http://www.axel-etcheverry.com) * Displays <a href="http://creativecommons.org/licenses/MIT/deed.fr">MIT</a> * @license http://creativecommons.org/licenses/MIT/deed.fr MIT */ /** * @namespace */ namespace Opengraph; class Writer extends Opengraph { /** * @var \ArrayObject */ protected static $storage; /** * @var Integer */ //protected static $position; /** * Append meta * * @param String $property * @param String $content * @return \Opengraph\Opengraph */ public function append($property, $content) { return $this->addMeta($property, $content, self::APPEND); } /** * Prepend meta * * @param String $property * @param String $content * @return \Opengraph\Opengraph */ public function prepend($property, $content) { return $this->addMeta($property, $content, self::PREPEND); } /** * Render all meta tags * * @return String */ public function render() { $html = ''; foreach(self::$storage as $meta) { $html .= "\t" . $meta->render() . PHP_EOL; } return $html; } }
Remove unnecessary conditional in argument parsing
import ircbotframe import sys class Handler: def __init__(self, host, port=6667, name="MediaWiki", description="MediaWiki recent changes bot", channels=[]): self.channels = channels self.bot = ircbotframe.ircBot(host, port, name, description) self.bot.bind("376", self.endMOTD) self.bot.start() def endMOTD(self, sender, headers, message): for chan in self.channels: self.bot.joinchan(chan) def main(cmd, args): args = args[:] parsemode = ["host"] host = None name = "MediaWiki" channels = [] while len(args) > 0: if len(parsemode) < 1: if args[0] == "-n": parsemode.insert(0, "name") else: channels.append(args[0]) else: if parsemode[0] == "name": name = args[0] elif parsemode[0] == "host": host = args[0] parsemode = parsemode[1:] args = args[1:] if host == None: print("Usage: " + cmd + " [-n <name>] <host> <channel> [<channel> ...]") return else: Handler(host=host, name=name channels=channels) if __name__ == "__main__": if __name__ == '__main__': main(sys.argv[0], sys.argv[1:] if len(sys.argv) > 1 else [])
import ircbotframe import sys class Handler: def __init__(self, host, port=6667, name="MediaWiki", description="MediaWiki recent changes bot", channels=[]): self.channels = channels self.bot = ircbotframe.ircBot(host, port, name, description) self.bot.bind("376", self.endMOTD) self.bot.start() def endMOTD(self, sender, headers, message): for chan in self.channels: self.bot.joinchan(chan) def main(cmd, args): args = args[:] parsemode = ["host"] host = None name = "MediaWiki" channels = [] while len(args) > 0: if len(parsemode) < 1: if args[0] == "-n": parsemode.insert(0, "name") else: channels.append(args[0]) else: if parsemode[0] == "name": name = args[0] elif parsemode[0] == "host": host = args[0] parsemode = parsemode[1:] args = args[1:] if host == None: print("Usage: " + cmd + " [-n <name>] <host> <channel> [<channel> ...]") return elif len(args) > 1: Handler(host=host, name=name channels=channels) if __name__ == "__main__": if __name__ == '__main__': main(sys.argv[0], sys.argv[1:] if len(sys.argv) > 1 else [])
Fix task channel registration when installing module from UI I noticed that when we install a new module via UI, its channel does not get registered. The reason for that is that when entities bundle is getting restarted, what unregisters the ChannelService, the ChannelService did not get registered back on, due to the info that tracker is already present. This change should fix this and the channels should get properly registered now. Change-Id: I4d3aa3e5f24a6e6fa380fc726cb2b9f8ac597b94
package org.motechproject.tasks.osgi; import org.eclipse.gemini.blueprint.service.exporter.OsgiServiceRegistrationListener; import org.motechproject.tasks.service.ChannelService; import org.osgi.framework.BundleContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import java.util.Map; /** * A listener for {@link ChannelService}, effectively serves as a tasks-bundle start handler, that sets up tracking of start/stop events of all other bundles */ public class ChannelServiceRegistrationListener implements OsgiServiceRegistrationListener { private static final Logger LOG = LoggerFactory.getLogger(ChannelServiceRegistrationListener.class); private BundleContext bundleContext; private TasksBlueprintApplicationContextTracker tracker; @Autowired public ChannelServiceRegistrationListener(BundleContext bundleContext) { LOG.info("Starting ChannelService registration listener"); this.bundleContext = bundleContext; } @Override public void registered(Object service, Map serviceProperties) { if (service instanceof ChannelService && tracker == null) { LOG.info("ChannelService registered, starting TasksBlueprintApplicationContextTracker"); ChannelService channelService = (ChannelService) service; tracker = new TasksBlueprintApplicationContextTracker(bundleContext, channelService); tracker.open(true); } } @Override public void unregistered(Object service, Map serviceProperties) { if (service instanceof ChannelService && tracker != null) { tracker.close(); tracker = null; } } }
package org.motechproject.tasks.osgi; import org.eclipse.gemini.blueprint.service.exporter.OsgiServiceRegistrationListener; import org.motechproject.tasks.service.ChannelService; import org.osgi.framework.BundleContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import java.util.Map; /** * A listener for {@link ChannelService}, effectively serves as a tasks-bundle start handler, that sets up tracking of start/stop events of all other bundles */ public class ChannelServiceRegistrationListener implements OsgiServiceRegistrationListener { private static final Logger LOG = LoggerFactory.getLogger(ChannelServiceRegistrationListener.class); private BundleContext bundleContext; private TasksBlueprintApplicationContextTracker tracker; @Autowired public ChannelServiceRegistrationListener(BundleContext bundleContext) { LOG.info("Starting ChannelService registration listener"); this.bundleContext = bundleContext; } @Override public void registered(Object service, Map serviceProperties) { if (service instanceof ChannelService && tracker == null) { LOG.info("ChannelService registered, starting TasksBlueprintApplicationContextTracker"); ChannelService channelService = (ChannelService) service; tracker = new TasksBlueprintApplicationContextTracker(bundleContext, channelService); tracker.open(true); } } @Override public void unregistered(Object service, Map serviceProperties) { if (service instanceof ChannelService && tracker != null) { tracker.close(); } } }