text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add test for module_path extension
<?php namespace Nwidart\Modules\Tests; use Illuminate\Support\Str; class HelpersTest extends BaseTestCase { /** * @var \Illuminate\Filesystem\Filesystem */ private $finder; /** * @var string */ private $modulePath; public function setUp(): void { parent::setUp(); $this->modulePath = base_path('modules/Blog'); $this->finder = $this->app['files']; $this->artisan('module:make', ['name' => ['Blog']]); } public function tearDown(): void { $this->finder->deleteDirectory($this->modulePath); parent::tearDown(); } /** @test */ public function it_finds_the_module_path() { $this->assertTrue(Str::contains(module_path('Blog'), 'modules/Blog')); } /** @test */ public function it_can_bind_a_relative_path_to_module_path() { $this->assertTrue(Str::contains(module_path('Blog', 'config/config.php'), 'modules/Blog/config/config.php')); } }
<?php namespace Nwidart\Modules\Tests; use Illuminate\Support\Str; class HelpersTest extends BaseTestCase { /** * @var \Illuminate\Filesystem\Filesystem */ private $finder; /** * @var string */ private $modulePath; public function setUp(): void { parent::setUp(); $this->modulePath = base_path('modules/Blog'); $this->finder = $this->app['files']; $this->artisan('module:make', ['name' => ['Blog']]); } public function tearDown(): void { $this->finder->deleteDirectory($this->modulePath); parent::tearDown(); } /** @test */ public function it_finds_the_module_path() { $this->assertTrue(Str::contains(module_path('Blog'), 'modules/Blog')); } }
Fix documentation. PHP does not allow arbitrary class casting. svn commit r12147
<?php require_once 'Swat/Swat.php'; require_once 'Swat/SwatError.php'; require_once 'Swat/exceptions/SwatException.php'; /** * The base object type * * @package Swat * @copyright 2004-2006 silverorange * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1 */ class SwatObject { // {{{ public function __toString() /** * Gets this object as a string * * This is a magic method that is called by PHP when this object is used * in string context. For example: * * <code> * $my_object = new SwatMessage('Hello, World!'); * echo $my_object; * </code> * * @return string this object represented as a string. */ public function __toString() { ob_start(); Swat::printObject($this); return ob_get_clean(); } // }}} } ?>
<?php require_once 'Swat/Swat.php'; require_once 'Swat/SwatError.php'; require_once 'Swat/exceptions/SwatException.php'; /** * The base object type * * @package Swat * @copyright 2004-2006 silverorange * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1 */ class SwatObject { // {{{ public function __toString() /** * Gets this object as a string * * This is a magic method that is called by PHP when this object is used * in string context. For example: * * <code> * echo (SwatObject)$my_object; * </code> * * @return string this object represented as a string. */ public function __toString() { ob_start(); Swat::printObject($this); return ob_get_clean(); } // }}} } ?>
Change function from public to protected
<?php namespace Lio\Forum\Replies; use Lio\Core\FormModel; use Validator; class ReplyForm extends FormModel { protected $validationRules = [ 'body' => 'required', '_time' => 'min_time:2', ]; protected function beforeValidation() { $type = isset($this->inputData['_type']) ? $this->inputData['_type'] : null; // Time validation on Create forms if ($type === 'create') { Validator::extend('min_time', function ($attribute, $time, $params) { $minTime = $params[0]; return (time() - $time) > $minTime; }); } } }
<?php namespace Lio\Forum\Replies; use Lio\Core\FormModel; use Validator; class ReplyForm extends FormModel { protected $validationRules = [ 'body' => 'required', '_time' => 'min_time:2', ]; public function beforeValidation() { $type = isset($this->inputData['_type']) ? $this->inputData['_type'] : null; // Time validation on Create forms if ($type === 'create') { Validator::extend('min_time', function ($attribute, $time, $params) { $minTime = $params[0]; return (time() - $time) > $minTime; }); } } }
Fix flash message on test add
<?php namespace Egzaminer\Exam; use Egzaminer\Admin\Dashboard as Controller; class ExamAdd extends Controller { public function addAction() { if (isset($_POST['add'])) { $model = new ExamAddModel(); if ($id = $model->add($_POST)) { $_SESSION['valid'] = true; header('Location: '.$this->dir().'/admin/test/edit/'.$id); exit; } else { $this->data['valid'] = false; } } $this->render('admin-exam-add', 'Dodawanie testu'); } }
<?php namespace Egzaminer\Exam; use Egzaminer\Admin\Dashboard as Controller; class ExamAdd extends Controller { public function addAction() { if (isset($_POST['add'])) { $model = new ExamAddModel(); if ($id = $model->add($_POST)) { $this->data['valid'] = true; header('Location: '.$this->dir().'/admin/test/edit/'.$id); exit; } else { $this->data['valid'] = false; } } $this->render('admin-exam-add', 'Dodawanie testu'); } }
Make the reset datastore servlet clear ride requests
package com.sheepdog.mashmesh.debug; import com.googlecode.objectify.Objectify; import com.sheepdog.mashmesh.models.*; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class ResetDatastoreServlet extends HttpServlet { @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { Objectify ofy = OfyService.ofy(); ofy.delete(ofy.query(UserProfile.class).chunkSize(100)); ofy.delete(ofy.query(VolunteerProfile.class).chunkSize(100)); ofy.delete(ofy.query(RideRecord.class).chunkSize(100)); ofy.delete(ofy.query(RideRequest.class).chunkSize(100)); int documentsDeleted = VolunteerProfile.clearIndex(); resp.setContentType("text/plain"); resp.getWriter().println(documentsDeleted + " text search documents deleted"); resp.getWriter().println("OK"); } }
package com.sheepdog.mashmesh.debug; import com.googlecode.objectify.Objectify; import com.sheepdog.mashmesh.models.OfyService; import com.sheepdog.mashmesh.models.RideRecord; import com.sheepdog.mashmesh.models.UserProfile; import com.sheepdog.mashmesh.models.VolunteerProfile; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class ResetDatastoreServlet extends HttpServlet { @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { Objectify ofy = OfyService.ofy(); ofy.delete(ofy.query(UserProfile.class).chunkSize(100)); ofy.delete(ofy.query(VolunteerProfile.class).chunkSize(100)); ofy.delete(ofy.query(RideRecord.class).chunkSize(100)); int documentsDeleted = VolunteerProfile.clearIndex(); resp.setContentType("text/plain"); resp.getWriter().println(documentsDeleted + " text search documents deleted"); resp.getWriter().println("OK"); } }
Allow addon to be nested at depth of n
/* jshint node: true */ 'use strict'; var VersionChecker = require('ember-cli-version-checker'); module.exports = { name: 'ember-scrollable', init: function() { this._super.init && this._super.init.apply(this, arguments); var checker = new VersionChecker(this); this._checkerForEmber = checker.for('ember', 'bower'); }, included: function(app) { while (app.app) { app = app.app; } this.app = app; this._super.included.apply(this, arguments); }, treeFor: function() { if (this._checkerForEmber.lt('2.3.0') && this.parent === this.project) { console.warn('hash helper is required by ember-scrollable, please install ember-hash-helper-polyfill or upgrade.'); } return this._super.treeFor.apply(this, arguments); } };
/* jshint node: true */ 'use strict'; var VersionChecker = require('ember-cli-version-checker'); module.exports = { name: 'ember-scrollable', init: function() { this._super.init && this._super.init.apply(this, arguments); var checker = new VersionChecker(this); this._checkerForEmber = checker.for('ember', 'bower'); }, included: function(app) { if (app.app) { app = app.app; } this.app = app; this._super.included.apply(this, arguments); }, treeFor: function() { if (this._checkerForEmber.lt('2.3.0') && this.parent === this.project) { console.warn('hash helper is required by ember-scrollable, please install ember-hash-helper-polyfill or upgrade.'); } return this._super.treeFor.apply(this, arguments); } };
Send emails to non @uprise.org accounts in production settings.
const path = require('path'); module.exports = { sessionOptions: { secret: process.env.SESSION_SECRET_KEY, saveUninitialized: true, // save new sessions resave: false, // do not automatically write to the session store cookie: { httpOnly: true, maxAge: 2419200000 } // TODO set secure to true when https is used }, redis: { host: process.env.REDIS_HOST, port: process.env.REDIS_PORT }, aws: { accessKeyId: process.env.AWS_ACCESS_KEY_ID, accessKeySecret: process.env.AWS_ACCESS_KEY_SECRET, bucketName: process.env.AWS_S3_BUCKET_NAME, region: process.env.AWS_S3_REGION, expirationTime: 300 }, postmark: { serverKey: process.env.POSTMARK_SECRET_KEY, validRecipient: (email) => { return process.env.NODE_ENV === 'production' || (email.split('@').pop() === 'uprise.org'); // only send to @uprise.org email accounts for non production }, from: 'notifications@uprise.org', contactEmail: 'help@uprise.org' }, urls: { api: process.env.SERVER_BASE_URL, client: process.env.CLIENT_BASE_URL }, paths: { base: path.resolve(__dirname, '..') }, sentry: { dsn: process.env.SENTRY_PRIVATE_DSN } }
const path = require('path'); module.exports = { sessionOptions: { secret: process.env.SESSION_SECRET_KEY, saveUninitialized: true, // save new sessions resave: false, // do not automatically write to the session store cookie: { httpOnly: true, maxAge: 2419200000 } // TODO set secure to true when https is used }, redis: { host: process.env.REDIS_HOST, port: process.env.REDIS_PORT }, aws: { accessKeyId: process.env.AWS_ACCESS_KEY_ID, accessKeySecret: process.env.AWS_ACCESS_KEY_SECRET, bucketName: process.env.AWS_S3_BUCKET_NAME, region: process.env.AWS_S3_REGION, expirationTime: 300 }, postmark: { serverKey: process.env.POSTMARK_SECRET_KEY, validRecipient: (email) => { return (email.split('@').pop() === 'uprise.org'); // only send to @uprise.org email accounts for now }, from: 'notifications@uprise.org', contactEmail: 'help@uprise.org' }, urls: { api: process.env.SERVER_BASE_URL, client: process.env.CLIENT_BASE_URL }, paths: { base: path.resolve(__dirname, '..') }, sentry: { dsn: process.env.SENTRY_PRIVATE_DSN } }
Add display name for clock
import React, {Component} from 'react'; import moment from 'moment-timezone'; import classnames from 'classnames'; import styles from './style.scss'; export default class Dashboard extends Component { componentWillMount() { this.timeTick(); setInterval(this.timeTick.bind(this), 1000 /* ms */); } timeTick() { const {timezone, displayName} = this.props; let timezoneName; if (displayName) { timezoneName = displayName; } else { const timezone = timezone || moment.tz.guess(); timezoneName = timezone.split('/')[1]; } this.setState({ timezoneName, now: timezone ? moment.tz(timezone) : moment() }); } render() { const {className} = this.props; const {now, timezoneName} = this.state; return ( <div className={classnames(className, styles.main)}> <div>{now.format('HH:mm')}</div> <div>{now.format('DD/MM/YYYY')}</div> <div>{timezoneName}</div> </div> ); } }
import React, {Component} from 'react'; import moment from 'moment-timezone'; import classnames from 'classnames'; import styles from './style.scss'; export default class Dashboard extends Component { componentWillMount() { this.timeTick(); setInterval(this.timeTick.bind(this), 1000 /* ms */); } timeTick() { const {timezone} = this.props; this.setState({ now: timezone ? moment.tz(timezone) : moment(), currentTimezone: timezone || moment.tz.guess() }); } render() { const {className} = this.props; const {now, currentTimezone} = this.state; return ( <div className={classnames(className, styles.main)}> <div>{now.format('HH:mm')}</div> <div>{now.format('DD/MM/YYYY')}</div> <div>{currentTimezone.split('/')[1]}</div> </div> ); } }
Update request class so specing of controllers can progress
<?php /** * MageSpec * * NOTICE OF LICENSE * * This source file is subject to the MIT License, that is bundled with this * package in the file LICENSE. * It is also available through the world-wide-web at this URL: * * http://opensource.org/licenses/MIT * * If you did not receive a copy of the license and are unable to obtain it * through the world-wide-web, please send an email * to <magetest@sessiondigital.com> so we can send you a copy immediately. * * @category MageTest * @package PhpSpec_MagentoExtension * @subpackage Specification * * @copyright Copyright (c) 2012-2013 MageTest team and contributors. */ namespace MageTest\PhpSpec\MagentoExtension\Specification; use PhpSpec\ObjectBehavior; use Prophecy\Argument; use Mage_Core_Controller_Request_Http as Request; use Zend_Controller_Response_Abstract as Response; /** * ControllerBehavior * * @category MageTest * @package PhpSpec_MagentoExtension * @subpackage Specification * * @author MageTest team (https://github.com/MageTest/MageSpec/contributors) */ abstract class ControllerBehavior extends ObjectBehavior { function let(Request $request, Response $response) { $this->beConstructedWith($request, $response); } }
<?php /** * MageSpec * * NOTICE OF LICENSE * * This source file is subject to the MIT License, that is bundled with this * package in the file LICENSE. * It is also available through the world-wide-web at this URL: * * http://opensource.org/licenses/MIT * * If you did not receive a copy of the license and are unable to obtain it * through the world-wide-web, please send an email * to <magetest@sessiondigital.com> so we can send you a copy immediately. * * @category MageTest * @package PhpSpec_MagentoExtension * @subpackage Specification * * @copyright Copyright (c) 2012-2013 MageTest team and contributors. */ namespace MageTest\PhpSpec\MagentoExtension\Specification; use PhpSpec\ObjectBehavior; use Prophecy\Argument; use Zend_Controller_Request_Abstract as Request; use Zend_Controller_Response_Abstract as Response; /** * ControllerBehavior * * @category MageTest * @package PhpSpec_MagentoExtension * @subpackage Specification * * @author MageTest team (https://github.com/MageTest/MageSpec/contributors) */ abstract class ControllerBehavior extends ObjectBehavior { function let(Request $request, Response $response) { $this->beConstructedWith($request, $response); } }
Disable some tests in test_hbase_insert to fix the build. Change-Id: I037b292d0eb93c5c743a201b2045eb2ba0712ae7 Reviewed-on: http://gerrit.ent.cloudera.com:8080/387 Reviewed-by: Ishaan Joshi <d1d1e60202ec9f2503deb1b724986485a125d802@cloudera.com> Tested-by: Ishaan Joshi <d1d1e60202ec9f2503deb1b724986485a125d802@cloudera.com>
#!/usr/bin/env python # Copyright (c) 2012 Cloudera, Inc. All rights reserved. # Targeted Impala HBase Tests # import logging import pytest from tests.common.test_vector import * from tests.common.impala_test_suite import * class TestHBaseQueries(ImpalaTestSuite): @classmethod def get_workload(self): return 'functional-query' @classmethod def add_test_dimensions(cls): super(TestHBaseQueries, cls).add_test_dimensions() cls.TestMatrix.add_constraint(\ lambda v: v.get_value('table_format').file_format == 'hbase') def test_hbase_scan_node(self, vector): self.run_test_case('QueryTest/hbase-scan-node', vector) def test_hbase_row_key(self, vector): self.run_test_case('QueryTest/hbase-rowkeys', vector) def test_hbase_filters(self, vector): self.run_test_case('QueryTest/hbase-filters', vector) def test_hbase_inserts(self, vector): try: self.run_test_case('QueryTest/hbase-inserts', vector) except AssertionError: msg = ('IMPALA-579 - Insert into a binary encoded hbase table produces' ' incorrect results') pytest.xfail(msg) def test_hbase_subquery(self, vector): self.run_test_case('QueryTest/hbase-subquery', vector)
#!/usr/bin/env python # Copyright (c) 2012 Cloudera, Inc. All rights reserved. # Targeted Impala HBase Tests # import logging import pytest from tests.common.test_vector import * from tests.common.impala_test_suite import * class TestHBaseQueries(ImpalaTestSuite): @classmethod def get_workload(self): return 'functional-query' @classmethod def add_test_dimensions(cls): super(TestHBaseQueries, cls).add_test_dimensions() cls.TestMatrix.add_constraint(\ lambda v: v.get_value('table_format').file_format == 'hbase') def test_hbase_scan_node(self, vector): self.run_test_case('QueryTest/hbase-scan-node', vector) def test_hbase_row_key(self, vector): self.run_test_case('QueryTest/hbase-rowkeys', vector) def test_hbase_filters(self, vector): self.run_test_case('QueryTest/hbase-filters', vector) def test_hbase_inserts(self, vector): self.run_test_case('QueryTest/hbase-inserts', vector) def test_hbase_subquery(self, vector): self.run_test_case('QueryTest/hbase-subquery', vector)
Rewrite urlpatterns to new format
from __future__ import absolute_import, unicode_literals from django.conf.urls import url from django.views.generic import TemplateView from . import views as core_views urlpatterns = [ # pylint: disable=invalid-name url(r'^$', core_views.upload_app, name="upload_app"), url(r'^potrditev$', TemplateView.as_view(template_name='uploader/upload_confirm.html'), name="upload_confirm"), # url(r'^seznam$', 'uploader.views.list_select', name="list_select"), # url(r'^seznam/(?P<salon_id>\d+)$', 'uploader.views.list_details', # name="list_datails"), # url(r'^razpisi$', # TemplateView.as_view(template_name="uploader/notices.html"), # name="notices"), # url(r'^razpisi/os$', # TemplateView.as_view(template_name="uploader/notice_os.html"), # name="notice_os"), # url(r'^razpisi/ss$', # TemplateView.as_view(template_name="uploader/notice_ss.html"), # name="notice_ss"), ]
from __future__ import absolute_import, unicode_literals from django.conf.urls import patterns, url from django.views.generic import TemplateView urlpatterns = patterns( # pylint: disable=invalid-name '', url(r'^$', 'uploader.views.upload_app', name="upload_app"), url(r'^potrditev$', TemplateView.as_view(template_name='uploader/upload_confirm.html'), name="upload_confirm"), # url(r'^$', 'uploader.views.upload', name="upload"), url(r'^seznam$', 'uploader.views.list_select', name="list_select"), url(r'^seznam/(?P<salon_id>\d+)$', 'uploader.views.list_details', name="list_datails"), url(r'^razpisi$', TemplateView.as_view(template_name="uploader/notices.html"), name="notices"), url(r'^razpisi/os$', TemplateView.as_view(template_name="uploader/notice_os.html"), name="notice_os"), url(r'^razpisi/ss$', TemplateView.as_view(template_name="uploader/notice_ss.html"), name="notice_ss"), )
Verify non-generic members also work just fine
<?php namespace net\xp_framework\unittest\core\generics; use util\Objects; /** * Lookup map */ #[@generic(self= 'K, V', parent= 'K, V')] class Lookup extends AbstractDictionary { protected $size; #[@generic(var= '[:V]')] protected $elements= []; /** * Put a key/value pairt * * @param K key * @param V value */ #[@generic(params= 'K, V')] public function put($key, $value) { $this->elements[Objects::hashOf($key)]= $value; $this->size= sizeof($this->elements); } /** * Returns a value associated with a given key * * @param K key * @return V value * @throws util.NoSuchElementException */ #[@generic(params= 'K', return= 'V')] public function get($key) { $offset= Objects::hashOf($key); if (!isset($this->elements[$offset])) { throw new \util\NoSuchElementException('No such key '.\xp::stringOf($key)); } return $this->elements[$offset]; } /** * Returns all values * * @return V[] values */ #[@generic(return= 'V[]')] public function values() { return array_values($this->elements); } /** @return int */ public function size() { return $this->size; } }
<?php namespace net\xp_framework\unittest\core\generics; use util\Objects; /** * Lookup map */ #[@generic(self= 'K, V', parent= 'K, V')] class Lookup extends AbstractDictionary { #[@generic(var= '[:V]')] protected $elements= []; /** * Put a key/value pairt * * @param K key * @param V value */ #[@generic(params= 'K, V')] public function put($key, $value) { $this->elements[Objects::hashOf($key)]= $value; } /** * Returns a value associated with a given key * * @param K key * @return V value * @throws util.NoSuchElementException */ #[@generic(params= 'K', return= 'V')] public function get($key) { $offset= Objects::hashOf($key); if (!isset($this->elements[$offset])) { throw new \util\NoSuchElementException('No such key '.\xp::stringOf($key)); } return $this->elements[$offset]; } /** * Returns all values * * @return V[] values */ #[@generic(return= 'V[]')] public function values() { return array_values($this->elements); } }
Update redis config from deprecated - pooling enabled by default
package fi.nls.oskari.spring.session; import fi.nls.oskari.util.PropertyUtil; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.data.redis.connection.RedisStandaloneConfiguration; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; // TODO: Check if maxInactiveIntervalInSeconds can be configured @Configuration @Profile(RedisSessionConfig.PROFILE) @EnableRedisHttpSession(maxInactiveIntervalInSeconds=7200) public class RedisSessionConfig extends WebMvcConfigurerAdapter { public static final String PROFILE ="redis-session"; @Bean public JedisConnectionFactory connectionFactory() { RedisStandaloneConfiguration config = new RedisStandaloneConfiguration( PropertyUtil.get("redis.hostname", "127.0.0.1"), PropertyUtil.getOptional("redis.port", 6379)); JedisConnectionFactory jedis = new JedisConnectionFactory(config); return jedis; } }
package fi.nls.oskari.spring.session; import fi.nls.oskari.util.PropertyUtil; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; // TODO: Check if maxInactiveIntervalInSeconds can be configured @Configuration @Profile(RedisSessionConfig.PROFILE) @EnableRedisHttpSession(maxInactiveIntervalInSeconds=7200) public class RedisSessionConfig extends WebMvcConfigurerAdapter { public static final String PROFILE ="redis-session"; @Bean public JedisConnectionFactory connectionFactory() { JedisConnectionFactory jedis = new JedisConnectionFactory(); jedis.setHostName(PropertyUtil.get("redis.hostname", "127.0.0.1")); jedis.setPort(PropertyUtil.getOptional("redis.port", 6379)); jedis.setUsePool(true); return jedis; } }
Increase search history max items to 99 and always push latest search word to top order
import { SEARCH_HISTORY } from '../constants/actionTypes'; export default function searchHistory( state = { items: [], }, action = {}, ) { switch (action.type) { case SEARCH_HISTORY.ADD: { let newItems; const { items } = state; const newItem = action.payload.item; if (items && items.length) { newItems = [ newItem, ...items.filter(item => item !== newItem).slice(0, 99), ]; } else { newItems = [newItem]; } return { ...state, items: newItems, }; } case SEARCH_HISTORY.REMOVE: return { ...state, items: state.items.filter(item => item !== action.payload.item), }; case SEARCH_HISTORY.CLEAR: return { ...state, items: [], }; default: return state; } }
import { SEARCH_HISTORY } from '../constants/actionTypes'; export default function searchHistory( state = { items: [], }, action = {}, ) { switch (action.type) { case SEARCH_HISTORY.ADD: { let newItems; const items = state.items; const newItem = action.payload.item; if (items && items.length) { if (items.indexOf(newItem) === -1) { newItems = [newItem, ...items.slice(0, 29)]; } else { newItems = [...items]; } } else { newItems = [newItem]; } return { ...state, items: newItems, }; } case SEARCH_HISTORY.REMOVE: return { ...state, items: state.items.filter(item => item !== action.payload.item), }; case SEARCH_HISTORY.CLEAR: return { ...state, items: [], }; default: return state; } }
Add scipy in requirements list
from setuptools import setup setup(name='pygraphc', version='0.0.1', description='Event log clustering in Python', long_description='This package contains event log clustering method including non-graph and ' 'graph-based approaches.', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', 'Topic :: Security', ], keywords='log clustering graph anomaly', url='http://github.com/studiawan/pygraphc/', author='Hudan Studiawan', author_email='studiawan@gmail.com', license='MIT', packages=['pygraphc'], scripts=['scripts/pygraphc'], install_requires=[ 'networkx', 'numpy', 'scipy', 'scikit-learn', 'nltk', 'Sphinx', 'numpydoc', 'TextBlob', ], include_package_data=True, zip_safe=False)
from setuptools import setup setup(name='pygraphc', version='0.0.1', description='Event log clustering in Python', long_description='This package contains event log clustering method including non-graph and ' 'graph-based approaches.', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', 'Topic :: Security', ], keywords='log clustering graph anomaly', url='http://github.com/studiawan/pygraphc/', author='Hudan Studiawan', author_email='studiawan@gmail.com', license='MIT', packages=['pygraphc'], scripts=['scripts/pygraphc'], install_requires=[ 'networkx', 'scikit-learn', 'nltk', 'numpy', 'Sphinx', 'numpydoc', 'TextBlob', ], include_package_data=True, zip_safe=False)
Fix up the /ajax/translate/ sanitizing
<?php /** * @package content */ /** * The AjaxTranslate page is used for translating strings on the fly * that are used in Symphony's javascript */ Class contentAjaxTranslate extends AjaxPage{ public function handleFailedAuthorisation(){ $this->_status = self::STATUS_UNAUTHORISED; $this->_Result = json_encode(array('status' => __('You are not authorised to access this page.'))); } public function view(){ $strings = $_GET['strings']; $namespace = (empty($_GET['namespace']) ? null : General::sanitize($_GET['namespace'])); $new = array(); foreach($strings as $key => $value) { // Check value if(empty($value) || $value = 'false') { $value = $key; } $value = General::sanitize($value); // Translate $new[$value] = Lang::translate(urldecode($value), null, $namespace); } $this->_Result = json_encode($new); } public function generate(){ header('Content-Type: application/json'); echo $this->_Result; exit; } }
<?php /** * @package content */ /** * The AjaxTranslate page is used for translating strings on the fly * that are used in Symphony's javascript */ Class contentAjaxTranslate extends AjaxPage{ public function handleFailedAuthorisation(){ $this->_status = self::STATUS_UNAUTHORISED; $this->_Result = json_encode(array('status' => __('You are not authorised to access this page.'))); } public function view(){ $strings = $_GET['strings']; $namespace = (empty($_GET['namespace']) ? null : General::sanitize($_GET['namespace'])); $new = array(); foreach($strings as $key => $value) { // Check value if(empty($value) || $value = 'false') { $value = General::sanitize($key); } // Translate $new[$value] = Lang::translate(urldecode($value), null, $namespace); } $this->_Result = json_encode($new); } public function generate(){ header('Content-Type: application/json'); echo $this->_Result; exit; } }
FIx tests for America/Adak timezone
var parse = require('../parse/index.js') var getDaysInMonth = require('../get_days_in_month/index.js') /** * @category Month Helpers * @summary Set the month to the given date. * * @description * Set the month to the given date. * * @param {Date|String|Number} date - the date to be changed * @param {Number} month - the month of the new date * @returns {Date} the new date with the month setted * * @example * // Set February to 1 September 2014: * var result = setMonth(new Date(2014, 8, 1), 1) * //=> Sat Feb 01 2014 00:00:00 */ function setMonth (dirtyDate, month) { var date = parse(dirtyDate) var year = date.getFullYear() var day = date.getDate() var dateWithDesiredMonth = new Date(0) dateWithDesiredMonth.setFullYear(year, month, 15) dateWithDesiredMonth.setHours(0, 0, 0, 0) var daysInMonth = getDaysInMonth(dateWithDesiredMonth) // Set the last day of the new month // if the original date was the last day of the longer month date.setMonth(month, Math.min(day, daysInMonth)) return date } module.exports = setMonth
var parse = require('../parse/index.js') var getDaysInMonth = require('../get_days_in_month/index.js') /** * @category Month Helpers * @summary Set the month to the given date. * * @description * Set the month to the given date. * * @param {Date|String|Number} date - the date to be changed * @param {Number} month - the month of the new date * @returns {Date} the new date with the month setted * * @example * // Set February to 1 September 2014: * var result = setMonth(new Date(2014, 8, 1), 1) * //=> Sat Feb 01 2014 00:00:00 */ function setMonth (dirtyDate, month) { var date = parse(dirtyDate) var year = date.getFullYear() var day = date.getDate() var dateWithDesiredMonth = new Date(0) dateWithDesiredMonth.setFullYear(year, month) dateWithDesiredMonth.setHours(0, 0, 0, 0) var daysInMonth = getDaysInMonth(dateWithDesiredMonth) // Set the last day of the new month // if the original date was the last day of the longer month date.setMonth(month, Math.min(day, daysInMonth)) return date } module.exports = setMonth
Add URL matching to Wikipedia module
const wiki = require('wikijs').default; module.exports.commands = ['wiki', 'wikipedia']; const urlRegex = /^(?:https?:\/\/)?(?:en\.)?wikipedia\.org\/wiki\/(.+)/; const errorMessage = term => `No Wikipedia page found for "${term}"`; function shortSummary(page, withUrl) { return page.summary() // Get the first "sentence" (hopefully) .then(str => str.substr(0, str.indexOf('.') + 1)) // Truncate with an ellipsis if length exceeds 250 chars .then(str => (str.length > 250 ? `${str.substr(0, 250)}...` : str)) // Append URL if requested .then(str => (withUrl ? `${str} <${page.raw.canonicalurl}>` : str)); } module.exports.run = (remainder, parts, reply) => { wiki().search(remainder, 1) .then(data => data.results[0]) .then(wiki().page) .then(page => shortSummary(page, true)) .then(reply) .catch(() => reply(errorMessage(remainder))); }; module.exports.url = (url, reply) => { if (urlRegex.test(url)) { const [, match] = urlRegex.exec(url); const title = decodeURIComponent(match); wiki().page(title) .then(shortSummary) .then(reply) .catch(() => reply(errorMessage(title))); } };
const wiki = require('wikijs').default; module.exports.commands = ['wiki', 'wikipedia']; function prettyPage(page) { return page.summary() // Get the first "sentence" (hopefully) .then(str => str.substr(0, str.indexOf('.') + 1)) // Truncate with an ellipsis if length exceeds 250 chars .then(str => (str.length > 250 ? `${str.substr(0, 250)}...` : str)) // Append Wikipedia URL .then(str => `${str} <${page.raw.canonicalurl}>`); } module.exports.run = function run(remainder, parts, reply) { wiki().search(remainder, 1) .then(data => data.results[0]) .then(wiki().page) .then(prettyPage) .then(reply) .catch(() => reply(`No Wikipedia page found for "${remainder}"`)); };
Fix datetime usage in memorize model
from datetime import datetime, timedelta from django.utils.timezone import utc from django.db import models from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic from .algorithm import interval class Practice(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() item = generic.GenericForeignKey('content_type', 'object_id') started_last_viewing = models.DateTimeField(null=True,blank=True, auto_now_add=True) ended_last_viewing = models.DateTimeField(null=True,blank=True, auto_now_add=True) user = models.ForeignKey(User) next_practice = models.DateTimeField(auto_now_add=True) times_practiced = models.PositiveIntegerField(default=0) easy_factor = models.FloatField(default=2.5) class Meta: ordering = ['next_practice'] def set_next_practice(self, rating): self.times_practiced += 1 minutes, ef = interval(self.times_practiced, rating, self.easy_factor) self.next_practice = datetime.utcnow().replace(tzinfo=utc) + timedelta(minutes=minutes) self.easy_factor = ef def delay(self): self.next_practice = datetime.utcnow().replace(tzinfo=utc) + timedelta(minutes=10)
from datetime import datetime, timedelta import datetime from django.utils.timezone import utc from django.db import models from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic from .algorithm import interval class Practice(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() item = generic.GenericForeignKey('content_type', 'object_id') started_last_viewing = models.DateTimeField(null=True,blank=True, auto_now_add=True) ended_last_viewing = models.DateTimeField(null=True,blank=True, auto_now_add=True) user = models.ForeignKey(User) next_practice = models.DateTimeField(auto_now_add=True) times_practiced = models.PositiveIntegerField(default=0) easy_factor = models.FloatField(default=2.5) class Meta: ordering = ['next_practice'] def set_next_practice(self, rating): self.times_practiced += 1 minutes, ef = interval(self.times_practiced, rating, self.easy_factor) self.next_practice = datetime.datetime.utcnow().replace(tzinfo=utc) + timedelta(minutes=minutes) self.easy_factor = ef def delay(self): self.next_practice = datetime.utcnow().replace(utc) + timedelta(minutes=10)
Remove padding characters from cert URL. This makes the URL prettier by removing reserved characters, and matches the behavior of the planned AMP CDN URL.
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package amppackager import ( "crypto/sha256" "crypto/x509" "encoding/base64" ) // CertURLPrefix must start without a slash, for PackagerBase's sake. const CertURLPrefix = "amppkg/cert" // CertName returns the basename for the given cert, as served by this // packager's cert cache. Should be stable and unique (e.g. // content-addressing). Clients should url.PathEscape this, just in case its // format changes to need escaping in the future. func CertName(cert *x509.Certificate) string { sum := sha256.Sum256(cert.Raw) return base64.RawURLEncoding.EncodeToString(sum[:]) }
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package amppackager import ( "crypto/sha256" "crypto/x509" "encoding/base64" ) // CertURLPrefix must start without a slash, for PackagerBase's sake. const CertURLPrefix = "amppkg/cert" // CertName returns the basename for the given cert, as served by this // packager's cert cache. Should be stable and unique (e.g. // content-addressing). Clients should url.PathEscape this, just in case its // format changes to need escaping in the future. func CertName(cert *x509.Certificate) string { sum := sha256.Sum256(cert.Raw) return base64.URLEncoding.EncodeToString(sum[:]) }
Add error handler on html preprocessing Close #238
'use strict'; var gulp = require('gulp'); var paths = gulp.paths; var $ = require('gulp-load-plugins')(); gulp.task('markups', function() { function renameToHtml(path) { path.extname = '.html'; } return gulp.src(paths.src + '/{app,components}/**/*.<%= props.htmlPreprocessor.extension %>') <% if (props.htmlPreprocessor.key === 'jade') { %> .pipe($.consolidate('jade', { pretty: ' ' })) <% } else if (props.htmlPreprocessor.key === 'haml') { %> .pipe($.consolidate('hamljs')) <% } else if (props.htmlPreprocessor.key === 'handlebars') { %> .pipe($.consolidate('handlebars')) <% } %> .on('error', function handleError(err) { console.error(err.toString()); this.emit('end'); }) .pipe($.rename(renameToHtml)) .pipe(gulp.dest(paths.tmp + '/serve/')); });
'use strict'; var gulp = require('gulp'); var paths = gulp.paths; var $ = require('gulp-load-plugins')(); gulp.task('markups', function() { function renameToHtml(path) { path.extname = '.html'; } return gulp.src(paths.src + '/{app,components}/**/*.<%= props.htmlPreprocessor.extension %>') <% if (props.htmlPreprocessor.key === 'jade') { %> .pipe($.consolidate('jade', { pretty: ' ' })) <% } else if (props.htmlPreprocessor.key === 'haml') { %> .pipe($.consolidate('hamljs')) <% } else if (props.htmlPreprocessor.key === 'handlebars') { %> .pipe($.consolidate('handlebars')) <% } %> .pipe($.rename(renameToHtml)) .pipe(gulp.dest(paths.tmp + '/serve/')); });
Fix country ISO code for US
import pytest from mock import Mock from saleor.core.utils import ( Country, get_country_by_ip, get_currency_for_country) @pytest.mark.parametrize('ip_data, expected_country', [ ({'country': {'iso_code': 'PL'}}, Country('PL')), ({'country': {'iso_code': 'UNKNOWN'}}, None), (None, None), ({}, None), ({'country': {}}, None)]) def test_get_country_by_ip(ip_data, expected_country, monkeypatch): monkeypatch.setattr( 'saleor.core.utils.geolite2.reader', Mock(return_value=Mock(get=Mock(return_value=ip_data)))) country = get_country_by_ip('127.0.0.1') assert country == expected_country @pytest.mark.parametrize('country, expected_currency', [ (Country('PL'), 'PLN'), (Country('US'), 'USD'), (Country('GB'), 'GBP')]) def test_get_currency_for_country(country, expected_currency, monkeypatch): currency = get_currency_for_country(country) assert currency == expected_currency
import pytest from mock import Mock from saleor.core.utils import ( Country, get_country_by_ip, get_currency_for_country) @pytest.mark.parametrize('ip_data, expected_country', [ ({'country': {'iso_code': 'PL'}}, Country('PL')), ({'country': {'iso_code': 'UNKNOWN'}}, None), (None, None), ({}, None), ({'country': {}}, None)]) def test_get_country_by_ip(ip_data, expected_country, monkeypatch): monkeypatch.setattr( 'saleor.core.utils.geolite2.reader', Mock(return_value=Mock(get=Mock(return_value=ip_data)))) country = get_country_by_ip('127.0.0.1') assert country == expected_country @pytest.mark.parametrize('country, expected_currency', [ (Country('PL'), 'PLN'), (Country('USA'), 'USD'), (Country('GB'), 'GBP')]) def test_get_currency_for_country(country, expected_currency, monkeypatch): currency = get_currency_for_country(country) assert currency == expected_currency
Fix bug in rate limiting when processing commits
package client import ( "sync" "github.com/calebamiles/github-client/comments" "github.com/calebamiles/github-client/commits" ) func (c *DefaultClient) processCommits(commitWithoutComments commits.CommitWithoutComments, cs *commitAccumulator, ready chan struct{}, wg *sync.WaitGroup, errs *errorAccumulator) { defer wg.Done() ready <- struct{}{} defer func(readyChan chan struct{}) { <-readyChan }(ready) var allComments []comments.Comment commentsPages, err := c.Fetcher.Fetch(commitWithoutComments.CommentsURL()) if err != nil { errs.Add(err) return } for j := range commentsPages { commentsOnPage, commentsLoopErr := comments.New(commentsPages[j]) if commentsLoopErr != nil { errs.Add(commentsLoopErr) return } allComments = append(allComments, commentsOnPage...) } commitToAdd := &commit{ CommitWithoutComments: commitWithoutComments, comments: allComments, } cs.Add(commitToAdd) return } type commit struct { commits.CommitWithoutComments comments []comments.Comment } func (c *commit) Comments() []comments.Comment { return c.comments }
package client import ( "sync" "github.com/calebamiles/github-client/comments" "github.com/calebamiles/github-client/commits" ) func (c *DefaultClient) processCommits(commitWithoutComments commits.CommitWithoutComments, cs *commitAccumulator, ready chan struct{}, wg *sync.WaitGroup, errs *errorAccumulator) { defer wg.Done() ready <- struct{}{} defer func() { <-ready }() var allComments []comments.Comment commentsPages, err := c.Fetcher.Fetch(commitWithoutComments.CommentsURL()) if err != nil { errs.Add(err) return } for j := range commentsPages { commentsOnPage, commentsLoopErr := comments.New(commentsPages[j]) if commentsLoopErr != nil { errs.Add(commentsLoopErr) return } allComments = append(allComments, commentsOnPage...) } commitToAdd := &commit{ CommitWithoutComments: commitWithoutComments, comments: allComments, } cs.Add(commitToAdd) return } type commit struct { commits.CommitWithoutComments comments []comments.Comment } func (c *commit) Comments() []comments.Comment { return c.comments }
Add - Simplest code to turn the Given into concrete actions (HTTP request to check that a POST resource exists)
/* We use the output messages from the cucumber runner to create Step Definitions: the glue between features written in Gherkin and the actual system under test. Use Given, When, Then. */ let request = require('request'); const {defineSupportCode} = require('cucumber'); defineSupportCode(function({Given, Then, When}) { Given('I have an employee insert resource', function (callback) { // Write code here that turns the phrase above into concrete actions //Simplest HTTP request to check that a POST resource exists request.post('http://localhost:3000/api_mpayroll/employees', function(error, response){ if (error) { console.log(error); callback(null, 'pending'); } else { response.statusCode = 201; callback(); } } ) }); When('I submit the employee record', function (callback) { // Write code here that turns the phrase above into concrete actions callback(null, 'pending'); }); Then('A new hourly employee is Created', function (callback) { // Write code here that turns the phrase above into concrete actions callback(null, 'pending'); }); });
/* We use the output messages from the cucumber runner to create Step Definitions: the glue between features written in Gherkin and the actual system under test. Use Given, When, Then. */ let request = require('request'); const {defineSupportCode} = require('cucumber'); defineSupportCode(function({Given, Then, When}) { Given('I have an employee insert resource', function (callback) { // Write code here that turns the phrase above into concrete actions //Simplest HTTP request to check that a POST resource exists request.post('http://localhost:3000/api_mpayroll/employees', function(error, response){ if (error) { console.log(error); callback(null, 'pending'); } else { response.statusCode = 201; callback(); } } ) }); When('I submit the employee record', function (callback) { // Write code here that turns the phrase above into concrete actions callback(null, 'pending'); }); Then('A new hourly employee is Created', function (callback) { // Write code here that turns the phrase above into concrete actions callback(null, 'pending'); }); });
Use the pool instead the database connection
package db import ( "github.com/garyburd/redigo/redis" ) // Save takes a key (struct used as template for all data containers to ease the managing of the DB) // and generates an unique key in order to add the record to the DB. func Save(key string, value []byte) error { conn := pool.Get() defer conn.Close() _, err := conn.Do("SET", key, value) return err } // Get is used to pull information from the DB in order to be used by the server. // Get operates as read only function and does not modify the data in the DB. func Get(key string) ([]byte, error) { conn := pool.Get() defer conn.Close() return redis.Bytes(conn.Do("GET", key)) } // GetList operates as Get, but instead of an unique key it takes a patern in order to return // a list of keys that reflect the entered patern. func GetList(pattern string) ([]interface{}, error) { conn := pool.Get() defer conn.Close() return redis.Values(conn.Do("KEYS", pattern)) } // I think Delete speaks for itself but still. This function is used to remove entrys from the DB. func Delete(key string) error { conn := pool.Get() defer conn.Close() _, err := conn.Do("DEL", key) return err }
package db import ( "github.com/garyburd/redigo/redis" ) // Save takes a key (struct used as template for all data containers to ease the managing of the DB) // and generates an unique key in order to add the record to the DB. func Save(key string, value []byte) error { defer mutex.Unlock() mutex.Lock() _, err := connection.Do("SET", key, value) return err } // Get is used to pull information from the DB in order to be used by the server. // Get operates as read only function and does not modify the data in the DB. func Get(key string) ([]byte, error) { defer mutex.Unlock() mutex.Lock() return redis.Bytes(connection.Do("GET", key)) } // GetList operates as Get, but instead of an unique key it takes a patern in order to return // a list of keys that reflect the entered patern. func GetList(pattern string) ([]interface{}, error) { defer mutex.Unlock() mutex.Lock() return redis.Values(connection.Do("KEYS", pattern)) } // I think Delete speaks for itself but still. This function is used to remove entrys from the DB. func Delete(key string) error { defer mutex.Unlock() mutex.Lock() _, err := connection.Do("DEL", key) return err }
Add columns and values to repr
from django.db.models import Model, CharField, Field class MaxLengthCharField(CharField): def __init__(self, *args, **kwargs): kwargs['max_length'] = 255 super().__init__(*args, **kwargs) class BaseModel(Model): class Meta: abstract = True def _get_explicit_field_names(self): return [field.name for field in self._meta.get_fields() if isinstance(field, Field) and field.name != 'id'] def to_dict(self): fields = self._get_explicit_field_names() return {field: getattr(self, field) for field in fields} def __repr__(self): model = str(self.__class__.__name__) columns = ', '.join('{}="{}"'.format(field, value) for field, value in self.to_dict().items()) return '{}({})'.format(model, columns)
from django.db.models import Model, CharField, Field class MaxLengthCharField(CharField): def __init__(self, *args, **kwargs): kwargs['max_length'] = 255 super().__init__(*args, **kwargs) class BaseModel(Model): class Meta: abstract = True def _get_explicit_field_names(self): return [field.name for field in self._meta.get_fields() if isinstance(field, Field) and field.name != 'id'] def to_dict(self): fields = self._get_explicit_field_names() return {field: getattr(self, field) for field in fields} def __repr__(self): return 'Model({})'.format(repr(self.to_dict()))
Fix for escaping single quote character(s)
#!/usr/bin/env python """ Copyright (c) 2006-2013 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import re from lib.core.exception import SqlmapUndefinedMethod class Syntax: """ This class defines generic syntax functionalities for plugins. """ def __init__(self): pass @staticmethod def _escape(expression, quote=True, escaper=None): retVal = expression if quote: for item in re.findall(r"'[^']*'+", expression, re.S): retVal = retVal.replace(item, escaper(item[1:-1])) else: retVal = escaper(expression) return retVal @staticmethod def escape(expression, quote=True): errMsg = "'escape' method must be defined " errMsg += "inside the specific DBMS plugin" raise SqlmapUndefinedMethod(errMsg)
#!/usr/bin/env python """ Copyright (c) 2006-2013 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import re from lib.core.exception import SqlmapUndefinedMethod class Syntax: """ This class defines generic syntax functionalities for plugins. """ def __init__(self): pass @staticmethod def _escape(expression, quote=True, escaper=None): retVal = expression if quote: for item in re.findall(r"'[^']+'", expression, re.S): retVal = retVal.replace(item, escaper(item[1:-1])) else: retVal = escaper(expression) return retVal @staticmethod def escape(expression, quote=True): errMsg = "'escape' method must be defined " errMsg += "inside the specific DBMS plugin" raise SqlmapUndefinedMethod(errMsg)
Set action set's for Kotlin perspective: open type, launch configurations
/******************************************************************************* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *******************************************************************************/ package org.jetbrains.kotlin.perspective; import org.eclipse.debug.ui.IDebugUIConstants; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.ui.IPageLayout; import org.eclipse.ui.IPerspectiveFactory; public class KotlinPerspectiveFactory implements IPerspectiveFactory { @Override public void createInitialLayout(IPageLayout layout) { layout.addActionSet(IDebugUIConstants.LAUNCH_ACTION_SET); layout.addActionSet(JavaUI.ID_ACTION_SET); } }
/******************************************************************************* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *******************************************************************************/ package org.jetbrains.kotlin.perspective; import org.eclipse.ui.IPageLayout; import org.eclipse.ui.IPerspectiveFactory; public class KotlinPerspectiveFactory implements IPerspectiveFactory { @Override public void createInitialLayout(IPageLayout layout) { } }
Refactor server tree context menu into it's own component
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.blazzify.jasonium.ui; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.scene.control.ContextMenu; import javafx.scene.control.MenuItem; /** * * @author Azzuwan Aziz <azzuwan@gmail.com> */ public class ServerTreeContextMenu extends ContextMenu { MenuItem connect = new MenuItem("Connect"); MenuItem disconnect = new MenuItem("Disconnect"); MenuItem remove = new MenuItem("Remove"); public ServerTreeContextMenu() { connect.setOnAction((event) -> { Alert alert = new Alert(Alert.AlertType.INFORMATION, "Connecting!", ButtonType.OK); alert.showAndWait(); }); disconnect.setOnAction((event) -> { }); remove.setOnAction((event) -> { }); this.getItems().addAll(connect, disconnect, remove); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.blazzify.jasonium.ui; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.scene.control.ContextMenu; import javafx.scene.control.MenuItem; /** * * @author Azzuwan Aziz <azzuwan@gmail.com> */ public class ServerTreeContextMenu extends ContextMenu { MenuItem connect = new MenuItem("Connect"); MenuItem disconnect = new MenuItem("Disconnect"); MenuItem remove = new MenuItem("Remove"); public ServerTreeContextMenu() { connect.setOnAction((event) -> { Alert alert = new Alert(Alert.AlertType.INFORMATION, "Connecting!", ButtonType.OK); }); disconnect.setOnAction((event) -> { }); remove.setOnAction((event) -> { }); this.getItems().addAll(connect, disconnect, remove); } }
Change progress plugin javascript to replace progress with custom field value
window.GobiertoAdmin.GobiertoCommonCustomFieldRecordsProgressPluginController = (function() { function GobiertoCommonCustomFieldRecordsProgressPluginController() {} GobiertoCommonCustomFieldRecordsProgressPluginController.prototype.form = function(opts = {}) { _handlePluginData(opts.uid); }; function _handlePluginData(uid) { let element = $(`[data-uid=${uid}]`) let id = element.attr('id') let data = JSON.parse($(`#${id}`).find("input[name$='[value]'").val()) _insertProgressPlugin(id, data) } function _insertProgressPlugin(id, data) { let element = $(`#${id}`) element.remove(); let progress_select = $("select[id$='_progress'") if(progress_select.length) { progress_select.replaceWith( $('<input type="text" disabled="disabled">').val( data.toLocaleString(I18n.locale, { style: 'percent', maximumFractionDigits: 1 }) ) ); } } return GobiertoCommonCustomFieldRecordsProgressPluginController; })(); window.GobiertoAdmin.gobierto_common_custom_field_records_progress_plugin_controller = new GobiertoAdmin.GobiertoCommonCustomFieldRecordsProgressPluginController;
window.GobiertoAdmin.GobiertoCommonCustomFieldRecordsProgressPluginController = (function() { function GobiertoCommonCustomFieldRecordsProgressPluginController() {} var grid; GobiertoCommonCustomFieldRecordsProgressPluginController.prototype.form = function(opts = {}) { _handlePluginData(opts.uid); }; function _applyPluginStyles(element, plugin_name_hint) { element.wrap("<div class='v_container'><div class='v_el v_el_level v_el_full_content'></div></div>"); } function _handlePluginData(uid) { let element = $(`[data-uid=${uid}]`) let id = element.attr('id') let data = JSON.parse($(`#${id}`).find("input[name$='[value]'").val()) _applyPluginStyles(element, "progress") _insertProgressPlugin(id, data) } function _insertProgressPlugin(id, data) { let element = $(`#${id}`) let formatted_data = data ? data.toLocaleString(I18n.locale, { style: 'percent', maximumFractionDigits: 1 }) : "-" element.append(formatted_data); // element.append($('<input>', { disabled: true, type: 'text', val: formatted_data })) } return GobiertoCommonCustomFieldRecordsProgressPluginController; })(); window.GobiertoAdmin.gobierto_common_custom_field_records_progress_plugin_controller = new GobiertoAdmin.GobiertoCommonCustomFieldRecordsProgressPluginController;
Add in ability to instantiate non public default constructors
/*** * * Copyright 2014 Andrew Hall * * 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.statefulj.framework.core.model.impl; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.statefulj.framework.core.model.Factory; public class FactoryImpl<T, CT> implements Factory<T, CT> { @Override public T create(Class<T> clazz, String event, CT context) { try { Constructor<T> ctr = clazz.getDeclaredConstructor(); ctr.setAccessible(true); return ctr.newInstance(); } catch(IllegalAccessException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (SecurityException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(clazz.getCanonicalName() + " does not have a default constructor"); } } }
/*** * * Copyright 2014 Andrew Hall * * 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.statefulj.framework.core.model.impl; import org.statefulj.framework.core.model.Factory; public class FactoryImpl<T, CT> implements Factory<T, CT> { @Override public T create(Class<T> clazz, String event, CT context) { T newInstance = null; try { newInstance = clazz.newInstance(); } catch(IllegalAccessException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } return newInstance; } }
Use verbose method name to avoid conflict with implementing class. Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
<?php namespace Orchestra\Support\Traits; use Illuminate\Support\Facades\File; use Symfony\Component\HttpFoundation\File\UploadedFile; use Orchestra\Support\Str; trait UploadableTrait { /** * Save uploaded file into directory. * * @param \Symfony\Component\HttpFoundation\File\UploadedFile $file * @param string $path * @return string */ protected function saveUploadedFile(UploadedFile $file, $path) { $file->move($path, $filename = $this->getUploadedFilename($file)); return $filename; } /** * Delete uploaded from directory * * @param string $file * @return bool */ protected function deleteUploadedFile($file) { return File::delete($file); } /** * Get uploaded filename. * * @param \Symfony\Component\HttpFoundation\File\UploadedFile $file * @return string */ protected function getUploadedFilename(UploadedFile $file) { $extension = $file->getClientOriginalExtension(); return Str::random(10).".{$extension}"; } }
<?php namespace Orchestra\Support\Traits; use Orchestra\Support\Str; use Illuminate\Support\Facades\File; use Symfony\Component\HttpFoundation\File\UploadedFile; trait UploadableTrait { /** * Save uploaded file into directory * * @param use Symfony\Component\HttpFoundation\File\UploadedFile * @param string $path * @return string */ protected function save(UploadedFile $file, $path) { $extension = $file->getClientOriginalExtension(); $filename = Str::random(10).".{$extension}"; $file->move($path, $filename); return $filename; } /** * Delete uploaded from directory * * @param string $file * @return bool */ protected function delete($file) { return File::delete($file); } }
Make MNIST example py3 compatible.
import os import gzip import pickle import sys # Python 2/3 compatibility. try: from urllib.request import urlretrieve except ImportError: from urllib import urlretrieve '''Adapted from theano tutorial''' def load_mnist(data_file = './mnist.pkl.gz'): if not os.path.exists(data_file): origin = ('http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz') print('Downloading data from %s' % origin) urlretrieve(origin, data_file) print('... loading data') f = gzip.open(data_file, 'rb') if sys.version_info[0] == 3: train_set, valid_set, test_set = pickle.load(f, encoding='latin1') else: train_set, valid_set, test_set = pickle.load(f) f.close() train_set_x, train_set_y = train_set valid_set_x, valid_set_y = valid_set test_set_x, test_set_y = test_set return (train_set_x, train_set_y), (valid_set_x, valid_set_y), (test_set_x, test_set_y)
import os import gzip import pickle import urllib import sys '''Adapted from theano tutorial''' def load_mnist(data_file = './mnist.pkl.gz'): if not os.path.exists(data_file): origin = ('http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz') print('Downloading data from %s' % origin) urllib.urlretrieve(origin, data_file) print('... loading data') f = gzip.open(data_file, 'rb') if sys.version_info[0] == 3: train_set, valid_set, test_set = pickle.load(f, encoding='latin1') else: train_set, valid_set, test_set = pickle.load(f) f.close() train_set_x, train_set_y = train_set valid_set_x, valid_set_y = valid_set test_set_x, test_set_y = test_set return (train_set_x, train_set_y), (valid_set_x, valid_set_y), (test_set_x, test_set_y)
Use cluster to utilize multiple cores Add cluster module to utilize multiple cores. Closes #54.
// server.js // // entry point activity pump application // // Copyright 2011-2012, StatusNet Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. var cluster = require("cluster"), os = require("os"), makeApp = require("./lib/app").makeApp, config = require("./config"), cnt, i; if (cluster.isMaster) { cnt = config.children || Math.max(os.cpus().length - 1, 1); for (i = 0; i < cnt; i++) { cluster.fork(); } } else { makeApp(config, function(err, app) { if (err) { console.log(err); } else { app.run(function(err) {}); } }); }
// server.js // // entry point activity pump application // // Copyright 2011-2012, StatusNet Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. var makeApp = require("./lib/app").makeApp; var config = require("./config"); makeApp(config, function(err, app) { if (err) { console.log(err); } else { app.run(function(err) {}); } });
Fix molecule offset on mobile devices. Use renderer size instead of canvas'
import * as THREE from 'three'; function Axes(target, targetCamera) { this._target = target; this._targetCamera = targetCamera; this._camera = new THREE.PerspectiveCamera(targetCamera.fov, targetCamera.aspect, 1, 100); this._object = new THREE.AxisHelper(1); this._scene = new THREE.Scene(); this._scene.add(this._object); this._update(); } Axes.prototype._update = function() { var fov = this._targetCamera.fov; var camera = this._camera; camera.aspect = this._targetCamera.aspect; camera.setMinimalFov(fov); camera.setDistanceToFit(1.0, fov); camera.updateProjectionMatrix(); this._object.quaternion.copy(this._target.quaternion); }; Axes.prototype.render = function(renderer) { this._update(); var full = renderer.getSize(); var width = full.width * 0.25; var height = full.height * 0.25; var autoClear = renderer.autoClear; renderer.autoClear = false; renderer.setViewport(0.0, full.height - height, width, height); // use left bottom corner renderer.clear(false, true, false); renderer.render(this._scene, this._camera); renderer.setViewport(0, 0, full.width, full.height); renderer.autoClear = autoClear; }; export default Axes;
import * as THREE from 'three'; function Axes(target, targetCamera) { this._target = target; this._targetCamera = targetCamera; this._camera = new THREE.PerspectiveCamera(targetCamera.fov, targetCamera.aspect, 1, 100); this._object = new THREE.AxisHelper(1); this._scene = new THREE.Scene(); this._scene.add(this._object); this._update(); } Axes.prototype._update = function() { var fov = this._targetCamera.fov; var camera = this._camera; camera.aspect = this._targetCamera.aspect; camera.setMinimalFov(fov); camera.setDistanceToFit(1.0, fov); camera.updateProjectionMatrix(); this._object.quaternion.copy(this._target.quaternion); }; Axes.prototype.render = function(renderer) { this._update(); var full = renderer.getDrawingBufferSize(); var width = full.width * 0.25; var height = full.height * 0.25; var autoClear = renderer.autoClear; renderer.autoClear = false; renderer.setViewport(0.0, full.height - height, width, height); // use left bottom corner renderer.clear(false, true, false); renderer.render(this._scene, this._camera); renderer.setViewport(0, 0, full.width, full.height); renderer.autoClear = autoClear; }; export default Axes;
Declare package_data to ensure month.aliases is included
from setuptools import setup, find_packages def _is_requirement(line): """Returns whether the line is a valid package requirement.""" line = line.strip() return line and not (line.startswith("-r") or line.startswith("#")) def _read_requirements(filename): """Returns a list of package requirements read from the file.""" requirements_file = open(filename).read() return [line.strip() for line in requirements_file.splitlines() if _is_requirement(line)] required_packages = _read_requirements("requirements/base.txt") test_packages = _read_requirements("requirements/tests.txt") setup( name='rapidpro-expressions', version='1.0', description='Python implementation of the RapidPro expression and templating system', url='https://github.com/rapidpro/flows', author='Nyaruka', author_email='code@nyaruka.com', license='BSD', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 2', ], keywords='rapidpro templating', packages=find_packages(), package_data={'expressions': ['month.aliases']}, install_requires=required_packages, test_suite='nose.collector', tests_require=required_packages + test_packages, )
from setuptools import setup, find_packages def _is_requirement(line): """Returns whether the line is a valid package requirement.""" line = line.strip() return line and not (line.startswith("-r") or line.startswith("#")) def _read_requirements(filename): """Returns a list of package requirements read from the file.""" requirements_file = open(filename).read() return [line.strip() for line in requirements_file.splitlines() if _is_requirement(line)] required_packages = _read_requirements("requirements/base.txt") test_packages = _read_requirements("requirements/tests.txt") setup( name='rapidpro-expressions', version='1.0', description='Python implementation of the RapidPro expression and templating system', url='https://github.com/rapidpro/flows', author='Nyaruka', author_email='code@nyaruka.com', license='BSD', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 2', ], keywords='rapidpro templating', packages=find_packages(), install_requires=required_packages, test_suite='nose.collector', tests_require=required_packages + test_packages, )
Use Args in cobra.Command to validate args. Also re-use context. Signed-off-by: Daniel Nephin <6347c07ae509164cffebfb1e2a0d6ed64958db19@docker.com>
package cli import ( "fmt" "strings" "github.com/spf13/cobra" ) // NoArgs validate args and returns an error if there are any args func NoArgs(cmd *cobra.Command, args []string) error { if len(args) == 0 { return nil } if cmd.HasSubCommands() { return fmt.Errorf("\n" + strings.TrimRight(cmd.UsageString(), "\n")) } return fmt.Errorf( "\"%s\" accepts no argument(s).\n\nUsage: %s\n\n%s", cmd.CommandPath(), cmd.UseLine(), cmd.Short, ) } // RequiresMinArgs returns an error if there is not at least min args func RequiresMinArgs(min int) cobra.PositionalArgs { return func(cmd *cobra.Command, args []string) error { if len(args) >= min { return nil } return fmt.Errorf( "\"%s\" requires at least %d argument(s).\n\nUsage: %s\n\n%s", cmd.CommandPath(), min, cmd.UseLine(), cmd.Short, ) } }
package cli import ( "fmt" "github.com/spf13/cobra" ) // MinRequiredArgs checks if the minimum number of args exists, and returns an // error if they do not. func MinRequiredArgs(args []string, min int, cmd *cobra.Command) error { if len(args) >= min { return nil } return fmt.Errorf( "\"%s\" requires at least %d argument(s).\n\nUsage: %s\n\n%s", cmd.CommandPath(), min, cmd.UseLine(), cmd.Short, ) } // AcceptsNoArgs returns an error message if there are args func AcceptsNoArgs(args []string, cmd *cobra.Command) error { if len(args) == 0 { return nil } return fmt.Errorf( "\"%s\" accepts no argument(s).\n\nUsage: %s\n\n%s", cmd.CommandPath(), cmd.UseLine(), cmd.Short, ) }
:wrench: Change post id on comment fixtures by reference
<?php namespace OAuthBundle\DataFixtures\ORM; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\FixtureInterface; use Doctrine\Common\Persistence\ObjectManager; use Doctrine\Common\DataFixtures\OrderedFixtureInterface; use WordPressBundle\Entity\Comment; class LoadCommentData extends AbstractFixture implements OrderedFixtureInterface { public function load(ObjectManager $manager) { $comment1 = new Comment(); $comment1->setCommentPostId($this->getReference("post-1")->getId()); $comment1->setCommentAuthor("Doctor strange"); $comment1->setCommentAuthorEmail("doctor@strange.com"); $comment1->setCommentAuthorUrl("http://doctorstrange.com"); $comment1->setCommentDate(new \DateTime("now")); $comment1->setCommentDateGmt(new \DateTime("now")); $comment1->setCommentContent("Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ex cupiditate, quo possimus. Asperiores hic temporibus dolores voluptates vel vero, cumque expedita ipsam aut veritatis perspiciatis dicta, iste minus, optio facilis?"); $manager->persist($comment1); $manager->flush(); } public function getOrder(){ return 2; } }
<?php namespace OAuthBundle\DataFixtures\ORM; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\FixtureInterface; use Doctrine\Common\Persistence\ObjectManager; use Doctrine\Common\DataFixtures\OrderedFixtureInterface; use WordPressBundle\Entity\Comment; class LoadCommentData extends AbstractFixture implements OrderedFixtureInterface { public function load(ObjectManager $manager) { $comment1 = new Comment(); $comment1->setCommentPostId(1); $comment1->setCommentAuthor("Doctor strange"); $comment1->setCommentAuthorEmail("doctor@strange.com"); $comment1->setCommentAuthorUrl("http://doctorstrange.com"); $comment1->setCommentDate(new \DateTime("now")); $comment1->setCommentDateGmt(new \DateTime("now")); $comment1->setCommentContent("Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ex cupiditate, quo possimus. Asperiores hic temporibus dolores voluptates vel vero, cumque expedita ipsam aut veritatis perspiciatis dicta, iste minus, optio facilis?"); $manager->persist($comment1); $manager->flush(); } public function getOrder(){ return 2; } }
Add check for websocket URI
'use strict'; function EoleWebsocketClient(autobahn, webSocketUri, $q) { if (!webSocketUri.match(/wss?:\/\//)) { throw 'Websocket URI must start with "ws://" or "wss://", got "'+webSocketUri+'".'; } /** * @param {String} accessToken * * @returns {Promise} A socket session promise. */ this.openSocket = function (accessToken) { return $q(function (resolve, reject) { var successCallback = function (session) { resolve(session); }; var failCallback = function (code, reason, detail) { reject([code, reason, detail]); }; var options = { maxRetries: 0, retryDelay: 2000 }; var authenticatedUri = webSocketUri+'?access_token='+accessToken; autobahn.connect(authenticatedUri, successCallback, failCallback, options); }); }; }
'use strict'; function EoleWebsocketClient(autobahn, webSocketUri, $q) { /** * @param {String} accessToken * * @returns {Promise} A socket session promise. */ this.openSocket = function (accessToken) { return $q(function (resolve, reject) { var successCallback = function (session) { resolve(session); }; var failCallback = function (code, reason, detail) { reject([code, reason, detail]); }; var options = { maxRetries: 0, retryDelay: 2000 }; var authenticatedUri = webSocketUri+'?access_token='+accessToken; autobahn.connect(authenticatedUri, successCallback, failCallback, options); }); }; }
Remove a bit of logging
import socketio from 'socket.io-client' import log from 'services/log' import foodsharing from 'services/foodsharing' export let io = null export const subscribers = [] export default { /* * Subscribe to the websocket receive all messages * Returns an unsubscribe function */ subscribe (fn) { subscribers.push(fn) return () => { let idx = subscribers.indexOf(fn) if (idx !== -1) subscribers.splice(idx, 1) } }, /* * Connects to the socket.io socket if not already * Returns a promise that resolves when connected */ connect () { if (io) return Promise.resolve() return new Promise((resolve, reject) => { io = socketio({ path: '/foodsharing/socket' }) io.on('connect', () => { io.emit('register') log.info('connected to websocket!') resolve() }) io.on('conv', data => { if (!data.o) return let message = foodsharing.convertMessage(JSON.parse(data.o)) subscribers.forEach(fn => fn(message)) }) }) }, /* * Disconnect from socket.io */ disconnect () { if (!io) return io.disconnect() io = null } }
import socketio from 'socket.io-client' import log from 'services/log' import foodsharing from 'services/foodsharing' export let io = null export const subscribers = [] export default { /* * Subscribe to the websocket receive all messages * Returns an unsubscribe function */ subscribe (fn) { subscribers.push(fn) return () => { let idx = subscribers.indexOf(fn) if (idx !== -1) subscribers.splice(idx, 1) } }, /* * Connects to the socket.io socket if not already * Returns a promise that resolves when connected */ connect () { if (io) return Promise.resolve() return new Promise((resolve, reject) => { io = socketio({ path: '/foodsharing/socket' }) io.on('connect', () => { io.emit('register') log.info('connected to websocket!') resolve() }) io.on('conv', data => { if (!data.o) return log.info('recv', data) let message = foodsharing.convertMessage(JSON.parse(data.o)) subscribers.forEach(fn => fn(message)) }) }) }, /* * Disconnect from socket.io */ disconnect () { if (!io) return io.disconnect() io = null } }
Add data holder for realm service
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.identity.oidc.session.internal; import org.osgi.service.http.HttpService; import org.wso2.carbon.user.core.service.RealmService; public class OIDCSessionManagementComponentServiceHolder { private static HttpService httpService; private static RealmService realmService; private OIDCSessionManagementComponentServiceHolder() { } public static HttpService getHttpService() { return httpService; } public static void setHttpService(HttpService httpService) { OIDCSessionManagementComponentServiceHolder.httpService = httpService; } public static void setRealmService(RealmService realmService) { OIDCSessionManagementComponentServiceHolder.realmService = realmService; } public static RealmService getRealmService() { return realmService; } }
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.identity.oidc.session.internal; import org.osgi.service.http.HttpService; public class OIDCSessionManagementComponentServiceHolder { private static HttpService httpService; private OIDCSessionManagementComponentServiceHolder() { } public static HttpService getHttpService() { return httpService; } public static void setHttpService(HttpService httpService) { OIDCSessionManagementComponentServiceHolder.httpService = httpService; } }
Fix incorrect Javascript for changing Share API settings
$(document).ready(function(){ $('#loglevel').change(function(){ $.post(OC.filePath('settings','ajax','setloglevel.php'), { level: $(this).val() },function(){ OC.Log.reload(); } ); }); $('#backgroundjobs input').change(function(){ if($(this).attr('checked')){ var mode = $(this).val(); if (mode == 'ajax' || mode == 'webcron' || mode == 'cron') { OC.AppConfig.setValue('core', 'backgroundjobs_mode', mode); } } }); $('#shareAPIEnabled').change(function() { $('.shareAPI td:not(#enable)').toggle(); }); $('#shareAPI input').change(function() { if ($(this).attr('type') == 'checkbox') { if (this.checked) { var value = 'yes'; } else { var value = 'no'; } } else { var value = $(this).val() } OC.AppConfig.setValue('core', $(this).attr('name'), value); }); });
$(document).ready(function(){ $('#loglevel').change(function(){ $.post(OC.filePath('settings','ajax','setloglevel.php'), { level: $(this).val() },function(){ OC.Log.reload(); } ); }); $('#backgroundjobs input').change(function(){ if($(this).attr('checked')){ var mode = $(this).val(); if (mode == 'ajax' || mode == 'webcron' || mode == 'cron') { OC.AppConfig.setValue('core', 'backgroundjobs_mode', mode); } } }); $('#shareAPIEnabled').change(function() { $('.shareAPI td:not(#enable)').toggle(); }); $('#shareAPI input').change(function() { if ($(this).attr('type') == 'radio') { console.log('radio'); } if ($(this).attr('type') == 'checkbox') { console.log('checked'); } OC.AppConfig.setValue('core', 'shareapi_', $(this).val()); }); });
Add the current working directory for the user scripts to the main process. Preparation for possible handling of require
import safeEval from 'safe-eval'; import dir from 'node-dir'; import path from 'path'; import {ipcRenderer} from 'electron'; const babel = require('babel-core'); const babelOptions = { presets: ['es2015'] } let scriptDirectory = process.env.script; let options = { match: /.js$/, exclude: /^\./, recursive: false } if (path.isAbsolute(scriptDirectory)) { dir.readFiles(scriptDirectory, options, parseFile, success); } else { throw new Error('Path for user script is not absolute.'); } function parseFile (err, content, next) { if(err) throw err; let code; try { code = babel.transform(content, babelOptions).code; } catch(e) { if(e.name === 'TypeError') { // TODO: Handle syntax error and show it to the user console.log(e); } else { throw e; } } finally { ipcRenderer.send('code', {code, dir: scriptDirectory}); } next(); } function success (err, files) { if(err) throw err; console.log("Finished reading all files!"); }
import safeEval from 'safe-eval'; import dir from 'node-dir'; import path from 'path'; import {ipcRenderer} from 'electron'; const babel = require('babel-core'); const babelOptions = { presets: ['es2015'] } let scriptDirectory = process.env.script; let options = { match: /.js$/, exclude: /^\./, recursive: false } if (path.isAbsolute(scriptDirectory)) { dir.readFiles(scriptDirectory, options, parseFile, success); } else { throw new Error('Path for user script is not absolute.'); } function parseFile (err, content, next) { if(err) throw err; let code; try { code = babel.transform(content, babelOptions).code; } catch(e) { if(e.name === 'TypeError') { // TODO: Handle syntax error and show it to the user console.log(e); } else { throw e; } } finally { ipcRenderer.send('code', {code}); } next(); } function success (err, files) { if(err) throw err; console.log("Finished reading all files!"); }
Make use of existing config and override if values provided
var _ = require('underscore'); //returns the process object with the passed data for pagination and sorting var buildQueryConfig = function(req, config) { var sort = req.query.sort, order = req.query.order, filter = req.query.filter, select = req.query.select, skip = req.query.skip, limit = req.query.limit, page = req.query.page, perPage = config.perPage || 20, idAttribute = req.params.idAttribute, conditions = config.conditions || {}, options = config.conditions || {}, fields = config.fields || ''; //sort order if (sort && (order === 'desc' || order === 'descending' || order === '-1')) { options.sort = '-' + sort; } if (skip) { options.skip = skip; } if (limit) { options.limit = limit; } //pagination if (page) { options.skip = page * perPage; options.limit = perPage; } //to find unique record for update, remove and findOne if (idAttribute) { conditions[config.idAttribute || '_id'] = idAttribute; } if (select) { fields = select.replace(/,/g, ' '); } return { conditions: conditions, fields: fields, options: options }; }; module.exports = { buildQueryConfig: buildQueryConfig };
var _ = require('underscore'); //returns the process object with the passed data for pagination and sorting var buildQueryConfig = function(req, config) { var sort = req.query.sort, order = req.query.order, filter = req.query.filter, select = req.query.select, skip = req.query.skip, limit = req.query.limit, page = req.query.page, perPage = config.perPage || 20, idAttribute = req.params.idAttribute, conditions = {}, options = {}, fields; //sort order if (sort && (order === 'desc' || order === 'descending' || order === '-1')) { options.sort = '-' + sort; } if (skip) { options.skip = skip; } if (limit) { options.limit = limit; } //pagination if (page) { options.skip = page * perPage; options.limit = perPage; } if (idAttribute) { conditions[config.idAttribute || '_id'] = idAttribute; } fields = select ? select.replace(/,/g, ' ') : ''; return { conditions: conditions, fields: fields, options: options }; }; module.exports = { buildQueryConfig: buildQueryConfig };
Use raw string for regular expression.
import re from urlparse import urlsplit class URLParser(object): """A minimal URL parser and splitter.""" scheme_re = re.compile(r'^(\S+?)://') def get_scheme(self, url): match = self.scheme_re.match(url) if match is not None: return match.group(1) return '' def is_url(self, url): return bool(self.get_scheme(url)) def split(self, url): scheme = self.get_scheme(url) if scheme: # Split all URLs like HTTP URLs url = 'http%s' % url[len(scheme):] ignored, host, path, qs, frag = urlsplit(url) user, host = self._split_host(host) return scheme, user, host, path, qs, frag return '', '', '', url, '', '' def _split_host(self, host): if '@' in host: return host.split('@', 1) return '', host
import re from urlparse import urlsplit class URLParser(object): """A minimal URL parser and splitter.""" scheme_re = re.compile('^(\S+?)://') def get_scheme(self, url): match = self.scheme_re.match(url) if match is not None: return match.group(1) return '' def is_url(self, url): return bool(self.get_scheme(url)) def split(self, url): scheme = self.get_scheme(url) if scheme: # Split all URLs like http URLs url = 'http%s' % url[len(scheme):] ignored, host, path, qs, frag = urlsplit(url) user, host = self._split_host(host) return scheme, user, host, path, qs, frag return '', '', '', url, '', '' def _split_host(self, host): if '@' in host: return host.split('@', 1) return '', host
Add toString for better logging/output
package com.fundynamic.d2tm.game.math; public class Vector2D<T extends Number> { private final T x, y; public static Vector2D zero() { return new Vector2D(0, 0); } public Vector2D(T x, T y) { this.x = x; this.y = y; } public T getX() { return x; } public T getY() { return y; } public Vector2D<Float> move(float xVelocity, float yVelocity, float speed) { float newX = x.floatValue() + (speed * xVelocity); float newY = y.floatValue() + (speed * yVelocity); return new Vector2D<>(newX, newY); } public Vector2D<Integer> toInt() { int newX = x.intValue(); int newY = y.intValue(); return new Vector2D<>(newX, newY); } @Override public String toString() { return "Vector2D{" + "x=" + x + ", y=" + y + '}'; } }
package com.fundynamic.d2tm.game.math; public class Vector2D<T extends Number> { private final T x, y; public static Vector2D zero() { return new Vector2D(0, 0); } public Vector2D(T x, T y) { this.x = x; this.y = y; } public T getX() { return x; } public T getY() { return y; } public Vector2D<Float> move(float xVelocity, float yVelocity, float speed) { float newX = x.floatValue() + (speed * xVelocity); float newY = y.floatValue() + (speed * yVelocity); return new Vector2D<>(newX, newY); } public Vector2D<Integer> toInt() { int newX = x.intValue(); int newY = y.intValue(); return new Vector2D<>(newX, newY); } }
Check for missing config file name
'use strict'; const path = require('path'); module.exports = (() => { // const akasha = require('../index'); const Command = require('cmnd').Command; class CopyAssetsCommand extends Command { constructor() { super('copy-assets'); } help() { return { description: 'Copy assets into output directory', args: [ 'config_file' ], }; } run(args, flags, vflags, callback) { if (!args[0]) callback(new Error("copy-assets: no config file name given")); const config = require(path.join(__dirname, args[0])); config.copyAssets() .then(() => { callback(null); }) .catch(err => { callback(err); }); } } return CopyAssetsCommand; })();
'use strict'; const path = require('path'); module.exports = (() => { // const akasha = require('../index'); const Command = require('cmnd').Command; class CopyAssetsCommand extends Command { constructor() { super('copy-assets'); } help() { return { description: 'Copy assets into output directory', args: [ 'config_file' ], }; } run(args, flags, vflags, callback) { const config = require(path.join(__dirname, args[0])); config.copyAssets() .then(() => { callback(null); }) .catch(err => { callback(err); }); } } return CopyAssetsCommand; })();
Fix SCSS name in fulpfile
// Run 'gulp' to do the important stuff var gulp = require('gulp'), prefixer = require('gulp-autoprefixer'), sass = require('gulp-sass'), livereload = require('gulp-livereload'), nodemon = require('gulp-nodemon'), jshint = require('gulp-jshint'), connect = require('gulp-connect'); var path = require('path'); gulp.task('sass', function () { gulp .src('./scss/styleselect.scss') .pipe(sass({ paths: ['scss'] })) .pipe(prefixer('last 2 versions', 'ie 9')) .pipe(gulp.dest('./css')) .pipe( connect.reload() ); }); // The default task (called when you run `gulp`) gulp.task('default', function() { gulp.run('sass'); // Watch files and run tasks if they change gulp.watch('./scss/styleselect.scss', function(event) { gulp.run('sass'); }); connect.server({ // root: ['_public'], port: 4242, livereload: true }); });
// Run 'gulp' to do the important stuff var gulp = require('gulp'), prefixer = require('gulp-autoprefixer'), sass = require('gulp-sass'), livereload = require('gulp-livereload'), nodemon = require('gulp-nodemon'), jshint = require('gulp-jshint'), connect = require('gulp-connect'); var path = require('path'); gulp.task('sass', function () { gulp .src('./scss/style.scss') .pipe(sass({ paths: ['scss'] })) .pipe(prefixer('last 2 versions', 'ie 9')) .pipe(gulp.dest('./css')) .pipe( connect.reload() ); }); // The default task (called when you run `gulp`) gulp.task('default', function() { gulp.run('sass'); // Watch files and run tasks if they change gulp.watch('./scss/*.scss', function(event) { gulp.run('sass'); }); connect.server({ // root: ['_public'], port: 4242, livereload: true }); });
Use np.mean instead for unweighted mean Signed-off-by: Lizhou Sha <d6acb26e253550574bc1141efa0eb5e6de15daeb@mit.edu>
import astropy.io.fits as fits import numpy as np import sys from .util import stack_fits_data METHOD_MAP = {"median": lambda x: np.median(x, axis=0, overwrite_input=True), "average": lambda x: np.mean(x, axis=0), "sum": lambda x: np.sum(x, axis=0)} def create_parser(subparsers): parser_combine = subparsers.add_parser("combine", help="combine help") parser_combine.add_argument("-m", "--method", choices=["median", "average", "sum"], required=True) parser_combine.add_argument("-o", "--output", metavar="OUTFILE", default=sys.stdout.buffer) parser_combine.add_argument("file", nargs="+") parser_combine.set_defaults(func=main) def main(args): image_stack = stack_fits_data(args.file) result = METHOD_MAP[args.method](image_stack) hdu = fits.PrimaryHDU(result) hdu.writeto(args.output)
import astropy.io.fits as fits import numpy as np import sys from .util import stack_fits_data METHOD_MAP = {"median": lambda x: np.median(x, axis=0, overwrite_input=True), "average": lambda x: np.average(x, axis=0), "sum": lambda x: np.sum(x, axis=0)} def create_parser(subparsers): parser_combine = subparsers.add_parser("combine", help="combine help") parser_combine.add_argument("-m", "--method", choices=["median", "average", "sum"], required=True) parser_combine.add_argument("-o", "--output", metavar="OUTFILE", default=sys.stdout.buffer) parser_combine.add_argument("file", nargs="+") parser_combine.set_defaults(func=main) def main(args): image_stack = stack_fits_data(args.file) result = METHOD_MAP[args.method](image_stack) hdu = fits.PrimaryHDU(result) hdu.writeto(args.output)
Switch to new music server
export const OFFICIAL_SERVER_URL = 'https://music4.bemuse.ninja/server' export async function load(serverUrl, { fetch = global.fetch } = {}) { const indexUrl = getServerIndexFileUrl(serverUrl) const data = await fetch(indexUrl).then((response) => response.json()) if (Array.isArray(data.songs)) { return data } else if (Array.isArray(data.charts)) { // Single-song server const dir = indexUrl.replace(/[^/]*$/, '') return { songs: [{ ...data, id: 'song', path: dir }] } } else { throw new Error( `Invalid server file at ${indexUrl}: Does not contain "songs" array.` ) } } export function getServerIndexFileUrl(serverUrl) { if (serverUrl.endsWith('/bemuse-song.json')) { return serverUrl } return serverUrl.replace(/\/(?:index\.json)?$/, '') + '/index.json' }
export const OFFICIAL_SERVER_URL = 'https://music.bemuse.ninja/live' export async function load(serverUrl, { fetch = global.fetch } = {}) { const indexUrl = getServerIndexFileUrl(serverUrl) const data = await fetch(indexUrl).then((response) => response.json()) if (Array.isArray(data.songs)) { return data } else if (Array.isArray(data.charts)) { // Single-song server const dir = indexUrl.replace(/[^/]*$/, '') return { songs: [{ ...data, id: 'song', path: dir }] } } else { throw new Error( `Invalid server file at ${indexUrl}: Does not contain "songs" array.` ) } } export function getServerIndexFileUrl(serverUrl) { if (serverUrl.endsWith('/bemuse-song.json')) { return serverUrl } return serverUrl.replace(/\/(?:index\.json)?$/, '') + '/index.json' }
Write test for duplicate kinds
package stow_test import ( "errors" "net/url" "testing" "github.com/cheekybits/is" "github.com/graymeta/stow" ) func TestKindByURL(t *testing.T) { is := is.New(t) u, err := url.Parse("test://container/item") is.NoErr(err) kind, err := stow.KindByURL(u) is.NoErr(err) is.Equal(kind, testKind) } func TestKinds(t *testing.T) { is := is.New(t) stow.Register("example", nil, nil) is.Equal(stow.Kinds(), []string{"test", "example"}) } func TestIsCursorEnd(t *testing.T) { is := is.New(t) is.True(stow.IsCursorEnd("")) is.False(stow.IsCursorEnd("anything")) } func TestErrNotSupported(t *testing.T) { is := is.New(t) err := errors.New("something") is.False(stow.IsNotSupported(err)) err = stow.NotSupported("feature") is.True(stow.IsNotSupported(err)) } func TestDuplicateKinds(t *testing.T) { is := is.New(t) stow.Register("example", nil, nil) is.Equal(stow.Kinds(), []string{"test", "example"}) stow.Register("example", nil, nil) is.Equal(stow.Kinds(), []string{"test", "example"}) }
package stow_test import ( "errors" "net/url" "testing" "github.com/cheekybits/is" "github.com/graymeta/stow" ) func TestKindByURL(t *testing.T) { is := is.New(t) u, err := url.Parse("test://container/item") is.NoErr(err) kind, err := stow.KindByURL(u) is.NoErr(err) is.Equal(kind, testKind) } func TestKinds(t *testing.T) { is := is.New(t) stow.Register("example", nil, nil) is.Equal(stow.Kinds(), []string{"test", "example"}) } func TestIsCursorEnd(t *testing.T) { is := is.New(t) is.True(stow.IsCursorEnd("")) is.False(stow.IsCursorEnd("anything")) } func TestErrNotSupported(t *testing.T) { is := is.New(t) err := errors.New("something") is.False(stow.IsNotSupported(err)) err = stow.NotSupported("feature") is.True(stow.IsNotSupported(err)) }
Add clears to common declarations
const commonDeclarations = { boxSizing: [ 'border-box' ], display: [ 'block', 'inline-block', 'inline', 'table', 'table-cell', 'none' ], float: [ 'none', 'left', 'right' ], clear: [ 'none', 'left', 'right', 'both' ], textAlign: [ 'left', 'center', 'right', 'justify' ], fontWeight: [ 'bold', 'normal' ], textDecoration: [ 'none', 'underline' ], whiteSpace: [ 'nowrap' ], listStyle: [ 'none' ], overflow: [ 'hidden', 'scroll' ], margin: [ 0 ], marginTop: [ 0 ], marginRight: [ 0 ], marginBottom: [ 0 ], marginLeft: [ 0 ], padding: [ 0 ], paddingTop: [ 0 ], paddingRight: [ 0 ], paddingBottom: [ 0 ], paddingLeft: [ 0 ], maxWidth: [ '100%' ], height: [ 'auto' ], verticalAlign: [ 'top', 'middle', 'bottom', 'baseline' ], position: [ 'relative', 'absolute', 'fixed' ], borderRadius: [ 0 ] } export default commonDeclarations
const commonDeclarations = { boxSizing: [ 'border-box' ], display: [ 'block', 'inline-block', 'inline', 'table', 'table-cell', 'none' ], float: [ 'none', 'left', 'right' ], textAlign: [ 'left', 'center', 'right', 'justify' ], fontWeight: [ 'bold', 'normal' ], textDecoration: [ 'none', 'underline' ], whiteSpace: [ 'nowrap' ], listStyle: [ 'none' ], overflow: [ 'hidden', 'scroll' ], margin: [ 0 ], marginTop: [ 0 ], marginRight: [ 0 ], marginBottom: [ 0 ], marginLeft: [ 0 ], padding: [ 0 ], paddingTop: [ 0 ], paddingRight: [ 0 ], paddingBottom: [ 0 ], paddingLeft: [ 0 ], maxWidth: [ '100%' ], height: [ 'auto' ], verticalAlign: [ 'top', 'middle', 'bottom', 'baseline' ], position: [ 'relative', 'absolute', 'fixed' ], borderRadius: [ 0 ] } export default commonDeclarations
Add io_profile in cli test
package cli import ( "testing" "github.com/libopenstorage/openstorage/api" "github.com/stretchr/testify/require" ) func TestCmdMarshalProto(t *testing.T) { volumeSpec := &api.VolumeSpec{ Size: 64, Format: api.FSType_FS_TYPE_EXT4, } data := cmdMarshalProto(volumeSpec, false) require.Equal( t, `{ "ephemeral": false, "size": "64", "format": "ext4", "block_size": "0", "ha_level": "0", "cos": "none", "io_profile": "IO_PROFILE_SEQUENTIAL", "dedupe": false, "snapshot_interval": 0, "shared": false, "aggregation_level": 0, "encrypted": false, "passphrase": "", "snapshot_schedule": "", "scale": 0, "sticky": false }`, data, ) }
package cli import ( "testing" "github.com/libopenstorage/openstorage/api" "github.com/stretchr/testify/require" ) func TestCmdMarshalProto(t *testing.T) { volumeSpec := &api.VolumeSpec{ Size: 64, Format: api.FSType_FS_TYPE_EXT4, } data := cmdMarshalProto(volumeSpec, false) require.Equal( t, `{ "ephemeral": false, "size": "64", "format": "ext4", "block_size": "0", "ha_level": "0", "cos": "none", "dedupe": false, "snapshot_interval": 0, "shared": false, "aggregation_level": 0, "encrypted": false, "passphrase": "", "snapshot_schedule": "", "scale": 0, "sticky": false }`, data, ) }
Add META with 'order_separator' key to Japanese spelling This is required due to a change in how separators are loaded in spellnum.py.
# -*- coding: utf-8 -*- """Japanese rules and tables for the spellnum module""" RULES = """ 1x = 十{x} ab = {a}十{b} 1xx = {100}{x} axx = {a}{100}{x} axxx = {a}千{x} (a)xxxx = {a}{x} """ NUMBERS = { 0: '零', 1: '一', 2: '二', 3: '三', 4: '四', 5: '五', 6: '六', 7: '七', 8: '八', 9: '九', 10: '十', 100: '百', } ORDERS = [ '', '万', '億', 'billón', 'trillón', 'quadrillón', 'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion', 'decillion', 'undecillion', 'duodecillion', 'tredecillion', 'quattuordecillion', 'quindecillion' ] META = { 'order_separator': '' }
# -*- coding: utf-8 -*- """Japanese rules and tables for the spellnum module""" RULES = """ 1x = 十{x} ab = {a}十{b} 1xx = {100}{x} axx = {a}{100}{x} axxx = {a}千{x} (a)xxxx = {a}{x} """ NUMBERS = { 0: '零', 1: '一', 2: '二', 3: '三', 4: '四', 5: '五', 6: '六', 7: '七', 8: '八', 9: '九', 10: '十', 100: '百', } ORDERS = [ '', '万', '億', 'billón', 'trillón', 'quadrillón', 'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion', 'decillion', 'undecillion', 'duodecillion', 'tredecillion', 'quattuordecillion', 'quindecillion' ] ORDER_SEP = ''
Set port as an environment variable
#!/usr/bin/env node var weechat = require('weechat'), notify = require('osx-notifier'), client; var properties = { server: process.env.SERVER, port: process.env.PORT, password: process.env.PASSWORD, ssl: false, nicks: process.env.NICKS.split(',') }; var raiseNotification = function(from, message) { notify({ type: 'info', title: 'WeeChat', subtitle: from, message: message, group: 'WeeChat' }); }; var connect = function() { return weechat.connect(properties.server, properties.port, properties.password, properties.ssl, function() { console.log('Connected.'); }); }; client = connect(); client.on('line', function(line) { var from = weechat.noStyle(line.prefix); var message = weechat.noStyle(line.message); var containsNick = properties.nicks.some(function(nick) { return message.indexOf(nick) !== -1; }); var isPrivate = line.tags_array.indexOf('notify_private') !== -1; var isSelf = from === properties.nick; // Make sure the message is either a highlight or a PM: if ((!isSelf && containsNick) || isPrivate) { raiseNotification(from, message); } });
#!/usr/bin/env node var weechat = require('weechat'), notify = require('osx-notifier'), client; var properties = { server: process.env.SERVER, port: 8001, password: process.env.PASSWORD, ssl: false, nicks: process.env.NICKS.split(',') }; var raiseNotification = function(from, message) { notify({ type: 'info', title: 'WeeChat', subtitle: from, message: message, group: 'WeeChat' }); }; var connect = function() { return weechat.connect(properties.server, properties.port, properties.password, properties.ssl, function() { console.log('Connected.'); }); }; client = connect(); client.on('line', function(line) { var from = weechat.noStyle(line.prefix); var message = weechat.noStyle(line.message); var containsNick = properties.nicks.some(function(nick) { return message.indexOf(nick) !== -1; }); var isPrivate = line.tags_array.indexOf('notify_private') !== -1; var isSelf = from === properties.nick; // Make sure the message is either a highlight or a PM: if ((!isSelf && containsNick) || isPrivate) { raiseNotification(from, message); } });
Use cache dir based on file location
"use strict"; module.exports = function Browscap (cacheDir) { if (typeof cacheDir === 'undefined') { cacheDir = __dirname + '/sources/'; } this.cacheDir = cacheDir; /** * parses the given user agent to get the information about the browser * * if no user agent is given, it uses {@see \BrowscapPHP\Helper\Support} to get it * * @param userAgent the user agent string */ this.getBrowser = function(userAgent) { var Ini = require('./parser'); var Quoter = require('./helper/quoter'); var quoter = new Quoter(); var GetPattern = require('./helper/pattern'); var BrowscapCache = require('browscap-js-cache'); var cache = new BrowscapCache(this.cacheDir); var GetData = require('./helper/data'); var patternHelper = new GetPattern(cache); var dataHelper = new GetData(cache, quoter); var parser = new Ini(patternHelper, dataHelper); return parser.getBrowser(userAgent); }; };
"use strict"; module.exports = function Browscap (cacheDir) { if (typeof cacheDir === 'undefined') { cacheDir = './sources/'; } this.cacheDir = cacheDir; /** * parses the given user agent to get the information about the browser * * if no user agent is given, it uses {@see \BrowscapPHP\Helper\Support} to get it * * @param userAgent the user agent string */ this.getBrowser = function(userAgent) { var Ini = require('./parser'); var Quoter = require('./helper/quoter'); var quoter = new Quoter(); var GetPattern = require('./helper/pattern'); var BrowscapCache = require('browscap-js-cache'); var cache = new BrowscapCache(this.cacheDir); var GetData = require('./helper/data'); var patternHelper = new GetPattern(cache); var dataHelper = new GetData(cache, quoter); var parser = new Ini(patternHelper, dataHelper); return parser.getBrowser(userAgent); }; };
Update licence header + Introduction of docstrings
#!/bin/env python # A-John-Shots - Python module/library for saving Security Hash Algorithms into JSON format. # Copyright (C) 2017 Funilrys - Nissar Chababy <contact at funilrys dot com> # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # Original Version: https://github.com/funilrys/A-John-Shots from .core import Core def get(path, **args): """ A simple script to get Security Hash Algorithms into JSON format :param path: A string, the path of the file or the directory we have to return. :param search: A string, the pattern the file have to match in ordrer to be included in the results :param output: A bool, Print on screen (False), print on file (True) :param output_destination: A string, the destination of the results :param algorithm: A string, the algorithm to use. Possibility: all, sha1, sha224, sha384, sha512 :param exclude: A list, the list of path, filename or in general, a pattern to exclude """ return Core(path, **args).get()
#!/bin/env python # A-John-Shots - Python module/library for saving Security Hash Algorithms into JSON format. # Copyright (C) 2017 Funilrys - Nissar Chababy <contact at funilrys dot com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Original Version: https://github.com/funilrys/A-John-Shots from .core import Core def get(path, **args): return Core(path, **args).get()
Create new API key on launching a new stack
import response from 'cfn-response' import SNS from 'aws/sns' import { Settings } from 'model/settings' export async function handle (event, context, callback) { if (event.RequestType === 'Update' || event.RequestType === 'Delete') { response.send(event, context, response.SUCCESS) return } const { AdminPageURL: adminPageURL, StatusPageURL: statusPageURL, CognitoPoolID: cognitoPoolID, IncidentNotificationTopic: incidentNotificationTopic } = event.ResourceProperties const settings = new Settings() try { if (statusPageURL) { await settings.setStatusPageURL(statusPageURL) } } catch (error) { // setStatusPageURL always fails due to the unknown SNS topic. So ignore the error here. // TODO: improve error handling. There may be other kinds of errors. console.warn(error.message) } try { await new SNS().notifyIncidentToTopic(incidentNotificationTopic) if (adminPageURL) { await settings.setAdminPageURL(adminPageURL) } if (cognitoPoolID) { await settings.setCognitoPoolID(cognitoPoolID) } await settings.createApiKey() response.send(event, context, response.SUCCESS) } catch (error) { console.log(error.message) console.log(error.stack) response.send(event, context, response.FAILED) } }
import response from 'cfn-response' import SNS from 'aws/sns' import { Settings } from 'model/settings' export async function handle (event, context, callback) { if (event.RequestType === 'Update' || event.RequestType === 'Delete') { response.send(event, context, response.SUCCESS) return } const { AdminPageURL: adminPageURL, StatusPageURL: statusPageURL, CognitoPoolID: cognitoPoolID, IncidentNotificationTopic: incidentNotificationTopic } = event.ResourceProperties const settings = new Settings() try { if (statusPageURL) { await settings.setStatusPageURL(statusPageURL) } } catch (error) { // failed due to the unknown SNS topic. console.warn(error.message) } try { await new SNS().notifyIncidentToTopic(incidentNotificationTopic) if (adminPageURL) { await settings.setAdminPageURL(adminPageURL) } if (cognitoPoolID) { await settings.setCognitoPoolID(cognitoPoolID) } response.send(event, context, response.SUCCESS) } catch (error) { console.log(error.message) console.log(error.stack) response.send(event, context, response.FAILED) } }
Refactor auth middleware to be more readable
import express from 'express' import bodyParser from 'body-parser' import auth from './lib/auth.js' const PORT = process.env.PORT || 8080 const API_KEY = process.env.API_KEY || 'abc123' const SALT = process.env.SALT || 'def456' const app = express() // Authentication middleware const authMiddleware = (req, res, next) => { const givenApiKey = req.query['api-key'] const authorized = auth({ given: givenApiKey, expected: API_KEY, salt: SALT }) if (authorized) { next() } else { res.status(401) res.send('Invalid API key') } } app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended: true })) app.use(authMiddleware) // POST message app.post('/message', (req, res) => { res.status(202) res.send('send message') }) app.listen(PORT, () => { console.log(`Server running on port ${PORT}`) })
import express from 'express' import bodyParser from 'body-parser' import auth from './lib/auth.js' const PORT = process.env.PORT || 8080 const API_KEY = process.env.API_KEY || 'abc123' const SALT = process.env.SALT || 'def456' const app = express() // Authentication middleware const authMiddleware = (req, res, next) => { const givenApiKey = req.query['api-key'] if (auth({ given: givenApiKey, expected: API_KEY, salt: SALT })) { next() } else { res.status(401) res.send('Invalid API key') } } app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended: true })) app.use(authMiddleware) // POST message app.post('/message', (req, res) => { res.status(202) res.send('send message') }) app.listen(PORT, () => { console.log(`Server running on port ${PORT}`) })
Fix regex in test case
var expect = require('expect'); module.exports = function chunk2(callback) { function forEachElement(el) { var src = el.getAttribute('src') || el.getAttribute('href'); var integrity = el.getAttribute('integrity'); if (src) { var match = src.match(/[^\/]+\.(js|css)/); if (match && integrity && integrity.match(/^sha\d+-/)) { resourcesWithIntegrity.push(match[0].toString()); } } } try { var resourcesWithIntegrity = []; Array.prototype.slice.call(document.getElementsByTagName('script')).forEach(forEachElement); Array.prototype.slice.call(document.getElementsByTagName('link')).forEach(forEachElement); expect(resourcesWithIntegrity).toInclude('stylesheet.css'); expect(resourcesWithIntegrity).toInclude('test.js'); expect(resourcesWithIntegrity.filter(function filter(item) { return item.match(/^\d+\.(chunk|bundle).js$/); }).length).toBe(2); expect(window.getComputedStyle(document.getElementsByTagName('body')[0]).backgroundColor).toEqual('rgb(200, 201, 202)'); callback(); } catch (e) { callback(e); } };
var expect = require('expect'); module.exports = function chunk2(callback) { function forEachElement(el) { var src = el.getAttribute('src') || el.getAttribute('href'); var integrity = el.getAttribute('integrity'); if (src) { var match = src.match(/[^\/]+\.(js|css)/); if (match && integrity && integrity.match(/^sha\d+-/)) { resourcesWithIntegrity.push(match[0].toString()); } } } try { var resourcesWithIntegrity = []; Array.prototype.slice.call(document.getElementsByTagName('script')).forEach(forEachElement); Array.prototype.slice.call(document.getElementsByTagName('link')).forEach(forEachElement); expect(resourcesWithIntegrity).toInclude('stylesheet.css'); expect(resourcesWithIntegrity).toInclude('test.js'); expect(resourcesWithIntegrity.filter(function filter(item) { return item.match(/^\d+\.chunk.js$/); }).length).toBe(2); expect(window.getComputedStyle(document.getElementsByTagName('body')[0]).backgroundColor).toEqual('rgb(200, 201, 202)'); callback(); } catch (e) { callback(e); } };
Fix blur issue with auth form validation
import React, { PropTypes } from 'react'; import styles from './AuthPage.css'; function AuthInputField(props) { const { input, type, placeholder, className, meta, } = props; const { dirty, error, } = meta; return ( <div> <div> <input {...input} type={type} placeholder={placeholder} className={className} autoFocus /> {(dirty && error) && <span className={styles.errors}>{error}</span>} </div> </div> ); } AuthInputField.propTypes = { input: PropTypes.object.isRequired, type: PropTypes.string.isRequired, placeholder: PropTypes.string.isRequired, className: PropTypes.string.isRequired, meta: PropTypes.shape({ dirty: PropTypes.bool.isRequired, error: PropTypes.string, }), }; export default AuthInputField;
import React, { PropTypes } from 'react'; import styles from './AuthPage.css'; function AuthInputField(props) { const { input, type, placeholder, className, meta, } = props; const { touched, error, } = meta; return ( <div> <div> <input {...input} type={type} placeholder={placeholder} className={className} autoFocus /> {(touched && error) && <span className={styles.errors}>{error}</span>} </div> </div> ); } AuthInputField.propTypes = { input: PropTypes.object.isRequired, type: PropTypes.string.isRequired, placeholder: PropTypes.string.isRequired, className: PropTypes.string.isRequired, meta: PropTypes.shape({ touched: PropTypes.bool.isRequired, error: PropTypes.string, }), }; export default AuthInputField;
Add some useful binary info
<?php return Affinity\Config::create([ // // The system php command // 'php' => 'php', // // The document root // 'docroot' => 'public', // // The execution mode determines default operation for some processes which should // naturally differ depending on the environment (development vs. production) // 'execution_mode' => IW\EXEC_MODE\DEVELOPMENT, // // Timezone // 'timezone' => 'US/Pacific', // // Debugging information to use. Keeping the debugging destination to NULL will // change the default depending on the execution mode. If the execution mode // is IW\EXEC_MODE\DEVELOPMENT, it will dump errors to the screen. Otherwise it will // use the configured $_SERVER['SERVER_ADMIN'] e-mail address. // 'debugging' => [ 'destination' => NULL, 'error_level' => E_ALL, ], // // The write directory provides a base directory to which the system and services can write // files to. If some of these files need to be public, it is suggested you create relative // symbolic links in the "public" folder. // 'write_directory' => 'writable' ]);
<?php return Affinity\Config::create([ // // The execution mode determines default operation for some processes which should // naturally differ depending on the environment (development vs. production) // 'execution_mode' => IW\EXEC_MODE\DEVELOPMENT, // // Timezone // 'timezone' => 'US/Pacific', // // Debugging information to use. Keeping the debugging destination to NULL will // change the default depending on the execution mode. If the execution mode // is IW\EXEC_MODE\DEVELOPMENT, it will dump errors to the screen. Otherwise it will // use the configured $_SERVER['SERVER_ADMIN'] e-mail address. // 'debugging' => [ 'destination' => NULL, 'error_level' => E_ALL, ], // // The write directory provides a base directory to which the system and services can write // files to. If some of these files need to be public, it is suggested you create relative // symbolic links in the "public" folder. // 'write_directory' => 'writable' ]);
[form] Add checking befor getEntity value..
var assign = require('object-assign'); var isFunction = require('lodash/lang/isFunction'); var actionMixin = { /** * Get the entity identifier for the form loading. * @returns {object} - The identifier of the entity. */ _getId: function formGetId() { if(this.getId){ return this.getId(); } return this.state.id; }, /** * Get the constructed entity from the state. * @returns {object} - the entity informations. */ _getEntity: function formGetEntity(){ if(this.getEntity){ return this.getEntity(); } //Build the entity value from the ref getVaue. var htmlData = {}; for(var r in this.refs){ //todo @pierr see if this is sufficient. if(this.refs[r] && isFunction(this.refs[r].getValue)){ htmlData[r] = this.refs[r].getValue(); } } return assign({}, this.state, htmlData); }, /** * Load data action call. */ _loadData: function formLoadData() { this.action.load(this._getId()); } }; module.exports = actionMixin;
var assign = require('object-assign'); var actionMixin = { /** * Get the entity identifier for the form loading. * @returns {object} - The identifier of the entity. */ _getId: function formGetId() { if(this.getId){ return this.getId(); } return this.state.id; }, /** * Get the constructed entity from the state. * @returns {object} - the entity informations. */ _getEntity: function formGetEntity(){ if(this.getEntity){ return this.getEntity(); } //Build the entity value from the ref getVaue. var htmlData = {}; for(var r in this.refs){ htmlData[r] = this.refs[r].getValue(); } return assign({}, this.state, htmlData); }, /** * Load data action call. */ _loadData: function formLoadData() { this.action.load(this._getId()); } }; module.exports = actionMixin;
Allow retrieving list of supported charsets
'use strict'; // eslint-disable-next-line import/no-internal-modules const encodings = require('iconv-lite/encodings'); const { omitBy } = require('../utilities'); const { DEFAULT_INPUT_CHARSET } = require('./constants'); const { validateCharset } = require('./validate'); const { decodeCharset } = require('./transform'); // Normalize charset, including adding defaults and validating const getCharset = function (charset, { format } = {}) { const charsetA = addDefaultCharset({ charset, format }); const charsetB = charsetA.toLowerCase(); validateCharset({ charset: charsetB, format }); const charsetC = createInstance({ charset: charsetB, title: charsetA }); return charsetC; }; // Add default charsets, including the format's default charset const addDefaultCharset = function ({ charset, format }) { const formatCharset = findFormatCharset({ format }); return charset || formatCharset || DEFAULT_INPUT_CHARSET; }; const findFormatCharset = function ({ format }) { if (format === undefined) { return; } return format.getCharset(); }; // Returns a charset adapter object const createInstance = function ({ charset, title }) { const decode = decodeCharset.bind(null, charset); return { name: charset, title, decode }; }; // Get list of supported charset const getCharsets = function () { // Remove charsets that are just aliases, to keep return value small const charsets = omitBy(encodings, value => typeof value === 'string'); const charsetsA = Object.keys(charsets); return charsetsA; }; module.exports = { getCharset, getCharsets, };
'use strict'; const { DEFAULT_INPUT_CHARSET } = require('./constants'); const { validateCharset } = require('./validate'); const { decodeCharset } = require('./transform'); // Normalize charset, including adding defaults and validating const getCharset = function (charset, { format } = {}) { const charsetA = addDefaultCharset({ charset, format }); const charsetB = charsetA.toLowerCase(); validateCharset({ charset: charsetB, format }); const charsetC = createInstance({ charset: charsetB, title: charsetA }); return charsetC; }; // Add default charsets, including the format's default charset const addDefaultCharset = function ({ charset, format }) { const formatCharset = findFormatCharset({ format }); return charset || formatCharset || DEFAULT_INPUT_CHARSET; }; const findFormatCharset = function ({ format }) { if (format === undefined) { return; } return format.getCharset(); }; // Returns a charset adapter object const createInstance = function ({ charset, title }) { const decode = decodeCharset.bind(null, charset); return { name: charset, title, decode }; }; module.exports = { getCharset, };
Disable jobs overview for anonymous users
from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import TemplateView from daiquiri.core.views import ModelPermissionMixin, AnonymousAccessMixin from daiquiri.core.utils import get_model_field_meta from .models import QueryJob, Example class QueryView(AnonymousAccessMixin, TemplateView): template_name = 'query/query.html' anonymous_setting = 'QUERY_ANONYMOUS' class JobsView(LoginRequiredMixin, TemplateView): template_name = 'query/jobs.html' def get_context_data(self, **kwargs): context = super(JobsView, self).get_context_data(**kwargs) context['phases'] = QueryJob.PHASE_CHOICES return context class ExamplesView(ModelPermissionMixin, TemplateView): template_name = 'query/examples.html' permission_required = 'daiquiri_query.view_example' def get_context_data(self, **kwargs): context = super(ExamplesView, self).get_context_data(**kwargs) context['meta'] = { 'Example': get_model_field_meta(Example) } return context
from django.views.generic import TemplateView from daiquiri.core.views import ModelPermissionMixin, AnonymousAccessMixin from daiquiri.core.utils import get_model_field_meta from .models import QueryJob, Example class QueryView(AnonymousAccessMixin, TemplateView): template_name = 'query/query.html' anonymous_setting = 'QUERY_ANONYMOUS' class JobsView(AnonymousAccessMixin, TemplateView): template_name = 'query/jobs.html' anonymous_setting = 'QUERY_ANONYMOUS' def get_context_data(self, **kwargs): context = super(JobsView, self).get_context_data(**kwargs) context['phases'] = QueryJob.PHASE_CHOICES return context class ExamplesView(ModelPermissionMixin, TemplateView): template_name = 'query/examples.html' permission_required = 'daiquiri_query.view_example' def get_context_data(self, **kwargs): context = super(ExamplesView, self).get_context_data(**kwargs) context['meta'] = { 'Example': get_model_field_meta(Example) } return context
DevTools: Fix forwarding keyboard shortcuts from target page This was regressed by crrev.com/c/devtools/devtools-frontend/+/1942290 which removed an unused variable in response to a linting rule. That variable referenced a call to construct a ForwardedInputEventHandler instance. That constructor has a side-effect of registering event listeners with the host and still needs to be run. Restoring the call to the constructor fixes the issue. Bug: 1049910 Change-Id: I6338164fcbbce6cae688d90c6d11cd76ed719f1e Reviewed-on: https://chromium-review.googlesource.com/c/devtools/devtools-frontend/+/2043060 Reviewed-by: Tim van der Lippe <dba8716ee7f8d16236046f74d2167cb94410f6ed@chromium.org> Reviewed-by: Robert Paveza <7787129de3d0cb4911c68d958db3023863584560@microsoft.com> Commit-Queue: Tony Ross <d5807c9a1621d46cc76cd6770054768aff0ae774@microsoft.com>
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import * as Host from '../host/host.js'; import {KeyboardShortcut} from './KeyboardShortcut.js'; import {ForwardedShortcut} from './ShortcutRegistry.js'; /** * @unrestricted */ export class ForwardedInputEventHandler { constructor() { Host.InspectorFrontendHost.InspectorFrontendHostInstance.events.addEventListener( Host.InspectorFrontendHostAPI.Events.KeyEventUnhandled, this._onKeyEventUnhandled, this); } /** * @param {!Common.Event} event */ _onKeyEventUnhandled(event) { const data = event.data; const type = /** @type {string} */ (data.type); const key = /** @type {string} */ (data.key); const keyCode = /** @type {number} */ (data.keyCode); const modifiers = /** @type {number} */ (data.modifiers); if (type !== 'keydown') { return; } self.UI.context.setFlavor(ForwardedShortcut, ForwardedShortcut.instance); self.UI.shortcutRegistry.handleKey(KeyboardShortcut.makeKey(keyCode, modifiers), key); self.UI.context.setFlavor(ForwardedShortcut, null); } } new ForwardedInputEventHandler();
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import * as Host from '../host/host.js'; import {KeyboardShortcut} from './KeyboardShortcut.js'; import {ForwardedShortcut} from './ShortcutRegistry.js'; /** * @unrestricted */ export class ForwardedInputEventHandler { constructor() { Host.InspectorFrontendHost.InspectorFrontendHostInstance.events.addEventListener( Host.InspectorFrontendHostAPI.Events.KeyEventUnhandled, this._onKeyEventUnhandled, this); } /** * @param {!Common.Event} event */ _onKeyEventUnhandled(event) { const data = event.data; const type = /** @type {string} */ (data.type); const key = /** @type {string} */ (data.key); const keyCode = /** @type {number} */ (data.keyCode); const modifiers = /** @type {number} */ (data.modifiers); if (type !== 'keydown') { return; } self.UI.context.setFlavor(ForwardedShortcut, ForwardedShortcut.instance); self.UI.shortcutRegistry.handleKey(KeyboardShortcut.makeKey(keyCode, modifiers), key); self.UI.context.setFlavor(ForwardedShortcut, null); } }
Allow for more flexible url pattern
var Backbone = require('backbone'); var url = require('url'); "use strict"; exports.HistoryUpdate = Backbone.View.extend({ initialize : function () { console.log('HistoryUpdate:initialize'); this.listenTo(this.model, "change:asset", this.assetChanged); this.listenTo(this.model, "change:activeTemplate", this.assetChanged); // note that we don't listen for a change in the collection as // this could lead to an invalid URL (e.g. change the collection to // something else, URL immediately changes, user saves before asset // loads) }, assetChanged: function () { var u = url.parse(window.location.href.replace('#', '?'), true); u.search = null; if (this.model.activeTemplate()) { u.query.t = this.model.activeTemplate(); } if (this.model.activeCollection()) { u.query.c = this.model.activeCollection(); } if (this.model.assetIndex() !== undefined) { u.query.i = this.model.assetIndex() + 1; } history.replaceState(null, null, url.format(u).replace('?', '#')); } });
var Backbone = require('backbone'); var url = require('url'); "use strict"; exports.HistoryUpdate = Backbone.View.extend({ initialize : function () { console.log('HistoryUpdate:initialize'); this.listenTo(this.model, "change:asset", this.assetChanged); this.listenTo(this.model, "change:activeTemplate", this.assetChanged); // note that we don't listen for a change in the collection as // this could lead to an invalid URL (e.g. change the collection to // something else, URL immediately changes, user saves before asset // loads) }, assetChanged: function () { var u = url.parse(window.location.href.replace('#', '?'), true); u.search = null; if (this.model.activeTemplate() == undefined || this.model.activeCollection() == undefined || this.model.assetIndex() == undefined) { // only want to set full valid states. return } u.query.t = this.model.activeTemplate(); u.query.c = this.model.activeCollection(); u.query.i = this.model.assetIndex() + 1; history.replaceState(null, null, url.format(u).replace('?', '#')); } });
Improve color display, remove gray from the texts
// ==UserScript== // @name 网易云音乐海外助手 // @namespace http://www.sudodev.cn/music-163-access-abroad/ // @updateURL http://git.oschina.net/bobshi/NetEaseMusicHelper/raw/master/netease_music_helper.user.js // @version 0.2 // @description 让海外的用户能正常听网易云音乐 // @author Bob // @match http://music.163.com/* // @grant none // @require http://code.jquery.com/jquery-latest.js // ==/UserScript== window.GAbroad=false; /**Then remove the gray color**/ $( window ).load(function() { $(".js-dis").removeClass('js-dis'); }); /** 如果是在浏览器控制台,你也可以把这句代码:window.GAboard=window.contentFrame.GAbroad = false; 执行,目前来说,可以达到相同的效果 **/
// ==UserScript== // @name 网易云音乐海外助手 // @namespace http://www.sudodev.cn/music-163-access-abroad/ // @updateURL http://git.oschina.net/bobshi/NetEaseMusicHelper/raw/master/netease_music_helper.user.js // @version 0.2 // @description 让海外的用户能正常听网易云音乐 // @author Bob // @match http://music.163.com/* // @grant none // ==/UserScript== window.GAbroad=false; /** 如果是在浏览器控制台,你也可以把这句代码:window.GAboard=window.contentFrame.GAbroad = false; 执行,目前来说,可以达到相同的效果 **/
Restructure redis returner, since it did notwork before anyway
''' Return data to a redis server To enable this returner the minion will need the python client for redis installed and the following values configured in the minion or master config, these are the defaults: redis.db: '0' redis.host: 'salt' redis.port: 6379 ''' # Import python libs import json try: import redis has_redis = True except ImportError: has_redis = False def __virtual__(): if not has_redis: return False return 'redis_return' def _get_serv(): ''' Return a redis server object ''' return redis.Redis( host=__salt__['config.option']('redis.host'), port=__salt__['config.option']('redis.port'), db=__salt__['config.option']('redis.db')) def returner(ret): ''' Return data to a redis data store ''' serv = _get_serv() serv.set('{0}:{1}'.format(ret['id'], ret['jid']), json.dumps(ret)) serv.lpush('{0}:{1}'.format(ret['id'], ret['fun']), ret['jid']) serv.sadd('minions', ret['id'])
''' Return data to a redis server To enable this returner the minion will need the python client for redis installed and the following values configured in the minion or master config, these are the defaults: redis.db: '0' redis.host: 'salt' redis.port: 6379 ''' # Import python libs import json try: import redis has_redis = True except ImportError: has_redis = False def __virtual__(): if not has_redis: return False return 'redis_return' def _get_serv(): ''' Return a redis server object ''' return redis.Redis( host=__salt__['config.option']('redis.host'), port=__salt__['config.option']('redis.port'), db=__salt__['config.option']('redis.db')) def returner(ret): ''' Return data to a redis data store ''' serv = _get_serv() serv.sadd('{0}:jobs'.format(ret['id'])) serv.set('{0}:{1}'.format(ret['jid'], json.dumps(ret['return']))) serv.sadd('jobs', ret['jid']) serv.sadd(ret['jid'], ret['id'])
Use full paths & print our current command fully
#!/usr/bin/env python import subprocess import argparse import os parser = argparse.ArgumentParser(description="Tweet some Train Statuses!") parser.add_argument("-s", "--station", dest="station", type=str, help="Station Short Code. Ex: 'SLM'") parser.add_argument("-t", "--train", dest="train", type=int, help="Train Number. Ex: '500'") parser.add_argument("-d", "--date", dest="date", type=str, help="Date. MM/DD/YYYY") parser.set_defaults(station=None, train=None, date=None) args = parser.parse_args() def main(): def run_command(cmd_array, shell=False): print "Executing `{}`".format(cmd_array) p = subprocess.Popen(cmd_array, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=shell) out, err = p.communicate() return out command = ['phantomjs', "{}/trainStatus.js".format(os.getcwd())] if args.station: command.append(str(args.station)) if args.train: command.append(str(args.train)) if args.date: command.append(str(args.date)) text = run_command(command) tweet = text.split("-" * 3) result = run_command(['node', "{}/twitter.js".format(os.getcwd()), tweet[1]]) print result if __name__ == "__main__": main()
#!/usr/bin/env python import subprocess import argparse parser = argparse.ArgumentParser(description="Tweet some Train Statuses!") parser.add_argument("-s", "--station", dest="station", type=str, help="Station Short Code. Ex: 'SLM'") parser.add_argument("-t", "--train", dest="train", type=int, help="Train Number. Ex: '500'") parser.add_argument("-d", "--date", dest="date", type=str, help="Date. MM/DD/YYYY") parser.set_defaults(station=None, train=None, date=None) args = parser.parse_args() def main(): def run_command(cmd_array, shell=False): p = subprocess.Popen(cmd_array, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=shell) out, err = p.communicate() return out command = ['phantomjs', 'trainStatus.js'] if args.station: command.append(str(args.station)) if args.train: command.append(str(args.train)) if args.date: command.append(str(args.date)) print "Executing {}".format(command) text = run_command(command) tweet = text.split("-" * 3) result = run_command(['node', 'twitter.js', tweet[1]]) print result if __name__ == "__main__": main()
Add note about virtualenv support
import sys import sysconfig import site if __name__ == '__main__': # This is a hack due to the distutils in debian/ubuntu's python3 being misconfigured # see discussion https://github.com/opencog/atomspace/issues/1782 # # If the bug is fixed, most of this script could be replaced by: # # from distutils.sysconfig import get_python_lib; print(get_python_lib(plat_specific=True, prefix=prefix)) # # However, using this would not respect a python virtual environments, so in a way this is better! prefix = sys.argv[1] # use sites if the prefix is recognized and the sites module is available # (virtualenv is missing getsitepackages()) if hasattr(site, 'getsitepackages'): paths = [p for p in site.getsitepackages() if p.startswith(prefix)] if len(paths) == 1: print(paths[0]) exit(0) # use sysconfig platlib as the fall back print(sysconfig.get_paths()['platlib'])
import sys import sysconfig import site if __name__ == '__main__': # This is a hack due to the distutils in debian/ubuntu's python3 being misconfigured # see discussion https://github.com/opencog/atomspace/issues/1782 # # If the bug is fixed, this script could be replaced by: # # from distutils.sysconfig import get_python_lib; print(get_python_lib(plat_specific=True, prefix=prefix)) prefix = sys.argv[1] # use sites if the prefix is recognized and the sites module is available # (virtualenv is missing getsitepackages()) if hasattr(site, 'getsitepackages'): paths = [p for p in site.getsitepackages() if p.startswith(prefix)] if len(paths) == 1: print(paths[0]) exit(0) # use sysconfig platlib as the fall back print(sysconfig.get_paths()['platlib'])
Add semicolons and update comment
/** * Directly export with short aliases to support browserify. */ exports.dot = exports.dotCase = require('dot-case'); exports.swap = exports.swapCase = require('swap-case'); exports.path = exports.pathCase = require('path-case'); exports.upper = exports.upperCase = require('upper-case'); exports.lower = exports.lowerCase = require('lower-case'); exports.camel = exports.camelCase = require('camel-case'); exports.snake = exports.snakeCase = require('snake-case'); exports.title = exports.titleCase = require('title-case'); exports.param = exports.paramCase = require('param-case'); exports.pascal = exports.pascalCase = require('pascal-case'); exports.constant = exports.constantCase = require('constant-case'); exports.sentence = exports.sentenceCase = require('sentence-case'); exports.isUpper = exports.isUpperCase = require('is-upper-case'); exports.isLower = exports.isLowerCase = require('is-lower-case'); exports.ucFirst = exports.upperCaseFirst = require('upper-case-first');
/** * Straight exports with short alias, to support browserify. * */ exports.dot = exports.dotCase = require('dot-case') exports.swap = exports.swapCase = require('swap-case') exports.path = exports.pathCase = require('path-case') exports.upper = exports.upperCase = require('upper-case') exports.lower = exports.lowerCase = require('lower-case') exports.camel = exports.camelCase = require('camel-case') exports.snake = exports.snakeCase = require('snake-case') exports.title = exports.titleCase = require('title-case') exports.param = exports.paramCase = require('param-case') exports.pascal = exports.pascalCase = require('pascal-case') exports.constant = exports.constantCase = require('constant-case') exports.sentence = exports.sentenceCase = require('sentence-case') exports.isUpper = exports.isUpperCase = require('is-upper-case') exports.isLower = exports.isLowerCase = require('is-lower-case') exports.ucFirst = exports.upperCaseFirst = require('upper-case-first')
Remove quotes only when attributes do not contains whitespaces
<?php namespace RenatoMarinho\LaravelPageSpeed\Middleware; class RemoveQuotes extends PageSpeed { public function apply($buffer) { $replace = [ '/ src="(.\S*?)"/' => ' src=$1', '/ width="(.\S*?)"/' => ' width=$1', '/ height="(.\S*?)"/' => ' height=$1', '/ name="(.\S*?)"/' => ' name=$1', '/ charset="(.\S*?)"/' => ' charset=$1', '/ align="(.\S*?)"/' => ' align=$1', '/ border="(.\S*?)"/' => ' border=$1', '/ crossorigin="(.\S*?)"/' => ' crossorigin=$1', '/ type="(.\S*?)"/' => ' type=$1', '/\/>/' => '>', ]; return $this->replace($replace, $buffer); } }
<?php namespace RenatoMarinho\LaravelPageSpeed\Middleware; class RemoveQuotes extends PageSpeed { public function apply($buffer) { $replace = [ '/ src="(.*?)"/' => ' src=$1', '/ width="(.*?)"/' => ' width=$1', '/ height="(.*?)"/' => ' height=$1', '/ name="(.*?)"/' => ' name=$1', '/ charset="(.*?)"/' => ' charset=$1', '/ align="(.*?)"/' => ' align=$1', '/ border="(.*?)"/' => ' border=$1', '/ crossorigin="(.*?)"/' => ' crossorigin=$1', '/ type="(.*?)"/' => ' type=$1', '/\/>/' => '>', ]; return $this->replace($replace, $buffer); } }
Fix formatting errors reported by flake8.
import json import requests class RPCClient(object): def __init__(self, hostname, port): self.url = 'http://' + str(hostname) + ':' + str(port) + '/mopidy/rpc' self.id = 0 def _do_rpc(self, method, params=None): self.id += 1 data = {'method': method, 'jsonrpc': '2.0', 'id': self.id} if params is not None: data['params'] = params return requests.request('POST', self.url, data=json.dumps(data), headers={'Content-Type': 'application/json'}) def set_repeat(self): self._do_rpc('core.tracklist.set_repeat', {'value': True}) def get_current_track_uri(self): response = self._do_rpc('core.playback.get_current_tl_track') return response.json()['result']['track']['uri']
import json import requests class RPCClient(object): def __init__(self, hostname, port): self.url = 'http://' + str(hostname) + ':' + str(port) + '/mopidy/rpc' self.id = 0 def _do_rpc(self, method, params=None): self.id += 1 data = { 'method': method, 'jsonrpc': '2.0', 'id': self.id } if params is not None: data['params'] = params return requests.request('POST', self.url, data=json.dumps(data), headers={'Content-Type': 'application/json'}) def set_repeat(self): self._do_rpc('core.tracklist.set_repeat', {'value': True}) def get_current_track_uri(self): response = self._do_rpc('core.playback.get_current_tl_track') return response.json()['result']['track']['uri']
chore(test): Use common ts compiler options in karma test and webpack build
module.exports = function (config) { config.set({ basePath: '', frameworks: ['mocha', 'sinon-chrome', 'karma-typescript'], files: [ 'src/ts/**/*.ts' ], exclude: [ 'src/ts/constants.ts' ], preprocessors: { 'src/ts/**/*.ts': ['karma-typescript'] }, client: { captureConsole: false, mocha: { opts: 'mocha.opts' } }, reporters: ['mocha'], karmaTypescriptConfig: { bundlerOptions: { entrypoints: /\.spec\.ts$/ }, compilerOptions: require('./tsconfig').compilerOptions, reports: { 'html': 'coverage', 'text': '' } }, port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['ChromeHeadless'], singleRun: true, concurrency: Infinity }); };
module.exports = function (config) { config.set({ basePath: '', frameworks: ['mocha', 'sinon-chrome', 'karma-typescript'], files: [ 'src/ts/**/*.ts' ], exclude: [ 'src/ts/constants.ts' ], preprocessors: { 'src/ts/**/*.ts': ['karma-typescript'] }, client: { captureConsole: false, mocha: { opts: 'mocha.opts' } }, reporters: ['mocha'], karmaTypescriptConfig: { bundlerOptions: { entrypoints: /\.spec\.ts$/, }, compilerOptions: { target: 'es2015' }, reports: { 'html': 'coverage', 'text': '' } }, port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['ChromeHeadless'], singleRun: true, concurrency: Infinity }); };
Reduce log spam from diesel.
import diesel from aspen.server import BaseEngine from diesel.protocols import wsgi class Engine(BaseEngine): diesel_app = None # a diesel diesel_app instance def bind(self): self.diesel_app = wsgi.WSGIApplication( self.website , self.website.address[1] , self.website.address[0] ) def start(self): self.diesel_app.run() def stop(self): try: if self.diesel_app is not None: self.diesel_app.halt() except diesel.app.ApplicationEnd: pass # Only you can prevent log spam. def start_restarter(self, check_all): def loop(): while True: check_all() diesel.sleep(0.5) self.diesel_app.add_loop(diesel.Loop(loop))
import diesel from aspen.server import BaseEngine from diesel.protocols import wsgi class Engine(BaseEngine): app = None # a diesel app instance def bind(self): self.app = wsgi.WSGIApplication( self.website , self.website.address[1] , self.website.address[0] ) def start(self): self.app.run() def stop(self): try: self.app.halt() except diesel.app.ApplicationEnd: pass # Only you can prevent log spam. def start_restarter(self, check_all): def loop(): while True: check_all() diesel.sleep(0.5) self.app.add_loop(diesel.Loop(loop))
Fix issue with missing username
#! /usr/bin/env node 'use strict'; import {processIM, processChannel, processGroup, saveData} from './commons.js'; import PleasantProgress from 'pleasant-progress'; export function slackHistoryExport(args) { const progress = new PleasantProgress(); progress.start('working'); if(args.type === 'dm') { processIM(args.token, args.username).then(history => { saveData(history,args,progress,args.username); }).catch(error => { console.log(error.stack); progress.stop(); process.exit(1); }); } else if (args.type === 'channel') { processChannel(args.token, args.channel).then(history => { saveData(history,args, progress,args.channel); }).catch((error) => { progress.stop(); console.log(error); console.log(error.stack); }); } else if (args.type === 'group') { processGroup(args.token, args.group).then(history => { saveData(history,args, progress,args.group); }).catch((error) => { progress.stop(); console.log(error); console.log(error.stack); }); } }
#! /usr/bin/env node 'use strict'; import {processIM, processChannel, processGroup, saveData} from './commons.js'; import PleasantProgress from 'pleasant-progress'; export function slackHistoryExport(args) { const progress = new PleasantProgress(); progress.start('working'); if(args.type === 'dm') { processIM(args.token, args.username).then(history => { saveData(history,args,progress,args.filename); }).catch(error => { console.log(error.stack); progress.stop(); process.exit(1); }); } else if (args.type === 'channel') { processChannel(args.token, args.channel).then(history => { saveData(history,args, progress,args.channel); }).catch((error) => { progress.stop(); console.log(error); console.log(error.stack); }); } else if (args.type === 'group') { processGroup(args.token, args.group).then(history => { saveData(history,args, progress,args.group); }).catch((error) => { progress.stop(); console.log(error); console.log(error.stack); }); } }
Fix on soundcloudToHtml method name
<?php /** * Laravel4-SirTrevorJs * * @link https://github.com/caouecs/Laravel4-SirTrevorJS */ namespace Caouecs\Sirtrevorjs\Converter; /** * Sound for Sir Trevor Js * * @package Caouecs\Sirtrevorjs\Converter */ class SoundConverter { /** * List of types for sound * * @access protected * @var array */ protected $types = array( "spotify" ); /** * Soundcloud block * * @access public * @return string */ public function soundcloudToHtml() { $theme = (isset($this->config['soundcloud']) && $this->config['soundcloud'] === "full") ? "full" : "small"; return $this->view("sound.soundcloud.".$theme, array( "remote" => $this->data['remote_id'] )); } /** * Spotify block * * @access public * @return string */ public function spotifyToHtml() { return $this->view("sound.spotify", array( "remote" => $this->data['remote_id'], "options" => $this->config['spotify'] )); } }
<?php /** * Laravel4-SirTrevorJs * * @link https://github.com/caouecs/Laravel4-SirTrevorJS */ namespace Caouecs\Sirtrevorjs\Converter; /** * Sound for Sir Trevor Js * * @package Caouecs\Sirtrevorjs\Converter */ class SoundConverter { /** * List of types for sound * * @access protected * @var array */ protected $types = array( "spotify" ); /** * Soundcloud block * * @access public * @return string */ public function soundcloud() { $theme = (isset($this->config['soundcloud']) && $this->config['soundcloud'] === "full") ? "full" : "small"; return $this->view("sound.soundcloud.".$theme, array( "remote" => $this->data['remote_id'] )); } /** * Spotify block * * @access public * @return string */ public function spotifyToHtml() { return $this->view("sound.spotify", array( "remote" => $this->data['remote_id'], "options" => $this->config['spotify'] )); } }
Include version from package.json in build output file name
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), compress: { main: { options: { archive: 'GeocachingUtils_<%= pkg.version %>.zip' }, files: [ { src: ['source/**'], dest: '' } ] } }, jshint: { options: { curly: true, eqeqeq: true, eqnull: true, browser: true, esnext: true, bitwise: true, globals: { jQuery: true }, ignores: [ 'node_modules/**/*.js', 'source/js/lib/**/*.js' ] }, all: ['**/*.js'] } }); grunt.loadNpmTasks('grunt-contrib-compress'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.registerTask('build', ['jshint']); grunt.registerTask('package', ['compress']); grunt.registerTask('default', ['build', 'package']); };
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), compress: { main: { options: { archive: 'Geocaching_Utils.zip' }, files: [ { src: ['source/**'], dest: '' } ] } }, jshint: { options: { curly: true, eqeqeq: true, eqnull: true, browser: true, esnext: true, bitwise: true, globals: { jQuery: true }, ignores: [ 'node_modules/**/*.js', 'source/js/lib/**/*.js' ] }, all: ['**/*.js'] } }); grunt.loadNpmTasks('grunt-contrib-compress'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.registerTask('build', ['jshint']); grunt.registerTask('package', ['compress']); grunt.registerTask('default', ['build', 'package']); };
Allow for comments in the sql file that do not start the line.
import os.path from django.core.management.commands import syncdb from django.db import models, connection, transaction try: from south.management.commands import syncdb except ImportError: pass from ...models import Schema, template_schema class Command(syncdb.Command): def handle_noargs(self, **options): # Ensure we have the clone_schema() function clone_schema_file = os.path.join(os.path.abspath(__file__ + '/../../../'), 'sql', 'clone_schema.sql') clone_schema_function = " ".join([x.strip() for x in open(clone_schema_file).readlines() if not x.strip().startswith('--')]) clone_schema_function = clone_schema_function.replace("'%'", "'%%'") cursor = connection.cursor() cursor.execute(clone_schema_function) # Ensure we have a __template__ schema. template_schema.create_schema() # Set the search path, so we find created models correctly cursor = connection.cursor() cursor.execute("SET search_path TO public,__template__;") super(Command, self).handle_noargs(**options) # Ensure all existing schemata exist (in case we imported them using loaddata or something) for schema in Schema.objects.all(): schema.create_schema()
import os.path from django.core.management.commands import syncdb from django.db import models, connection, transaction try: from south.management.commands import syncdb except ImportError: pass from ...models import Schema, template_schema class Command(syncdb.Command): def handle_noargs(self, **options): # Ensure we have the clone_schema() function clone_schema_file = os.path.join(os.path.abspath(__file__ + '/../../../'), 'sql', 'clone_schema.sql') clone_schema_function = " ".join([x.strip() for x in open(clone_schema_file).readlines() if not x.startswith('--')]) clone_schema_function = clone_schema_function.replace("'%'", "'%%'") cursor = connection.cursor() cursor.execute(clone_schema_function) # Ensure we have a __template__ schema. template_schema.create_schema() # Set the search path, so we find created models correctly cursor = connection.cursor() cursor.execute("SET search_path TO public,__template__;") super(Command, self).handle_noargs(**options) # Ensure all existing schemata exist (in case we imported them using loaddata or something) for schema in Schema.objects.all(): schema.create_schema()
Add temp button in candidate section
import React from 'react' import './candidatesection.css' import { Route } from 'react-router-dom' import { Button } from 'semantic-ui-react' export default class CandidateSection extends React.Component { constructor () { super() this.state = { data : [] } } componentDidMount () { this.loadAllCandidate() } loadAllCandidate () { } render () { return ( <Route render={({ history }) => ( <div className='wrapper style1 candidate'> <div className='container-atas'> <div className='row title'> <h1>Kandidat</h1> </div> <div className='row description'> <p>Kandidat yang turut meramaikan pemilu</p> </div> <Button fluid size='huge' onClick={() => { history.push('/election/dkijakarta/candidate/1') }}> Temp Candidate Detail Page</Button> </div> </div> )} /> ) } }
import React from 'react' import './candidatesection.css' export default class CandidateSection extends React.Component { constructor () { super() this.state = { data : [] } } componentDidMount () { this.loadAllCandidate() } loadAllCandidate () { } render () { return ( <div className='wrapper style1 candidate'> <div className='container-atas'> <div className='row title'> <h1>Kandidat</h1> </div> <div className='row description'> <p>Kandidat yang turut meramaikan pemilu</p> </div> </div> </div> ) } }
Add description usage for ExpireDate class
<?php /** * Description of Date * * Usage: * <code> * $expire_date = new Merchant_Billing_ExpiryDate(5, 2010); * </code> * Public methods: * + is_expired() returns a boolean about expiration of given data * + expiration() returns expiration date as Unix timestamp * * * * @package Aktive Merchant * @author Andreas Kollaros * @license http://www.opensource.org/licenses/mit-license.php */ class Merchant_Billing_ExpiryDate { private $year; private $month; public function __construct($month, $year) { $this->year = $year; $this->month = (int) $month; } public function is_expired (){ return ( time() > $this->expiration() ) ; } public function expiration (){ return strtotime($this->year."-".$this->month."-".$this->month_days()." 23:59:59"); } private function month_days(){ $mdays = array(null,31,28,31,30,31,30,31,31,30,31,30,31); if ( $this->is_leap() ) $mdays[2] = 29; return $mdays[$this->month]; } private function is_leap(){ $time = strtotime($this->year."-02-29"); $time_array = localtime($time); if ( $time_array[4] == 1 ) return true; return false; } } ?>
<?php /** * Description of Date * * @package Aktive Merchant * @author Andreas Kollaros * @license http://www.opensource.org/licenses/mit-license.php */ class Merchant_Billing_ExpiryDate { private $year; private $month; public function __construct($month, $year) { $this->year = $year; $this->month = (int) $month; } public function is_expired (){ return ( time() > $this->expiration() ) ; } public function expiration (){ return strtotime($this->year."-".$this->month."-".$this->month_days()."23:59:59"); } private function month_days(){ $mdays = array(null,31,28,31,30,31,30,31,31,30,31,30,31); if ( $this->is_leap() ) $mdays[2] = 29; return $mdays[$this->month]; } private function is_leap(){ $time = strtotime($this->year."-02-29"); $time_array = localtime($time); if ( $time_array[4] == 1 ) return true; return false; } } ?>
Remove person from organization serializer
from rest_framework import serializers from bluebottle.utils.model_dispatcher import get_organization_model, get_organizationmember_model ORGANIZATION_MODEL = get_organization_model() MEMBER_MODEL = get_organizationmember_model() ORGANIZATION_FIELDS = ( 'id', 'name', 'slug', 'address_line1', 'address_line2', 'city', 'state', 'country', 'postal_code', 'phone_number', 'email') class OrganizationSerializer(serializers.ModelSerializer): class Meta: model = ORGANIZATION_MODEL fields = ORGANIZATION_FIELDS class ManageOrganizationSerializer(OrganizationSerializer): slug = serializers.SlugField(required=False) name = serializers.CharField(required=True) email = serializers.EmailField(required=False) class Meta: model = ORGANIZATION_MODEL fields = ORGANIZATION_FIELDS + ('partner_organizations', 'created', 'updated')
from rest_framework import serializers from bluebottle.utils.model_dispatcher import get_organization_model, get_organizationmember_model ORGANIZATION_MODEL = get_organization_model() MEMBER_MODEL = get_organizationmember_model() ORGANIZATION_FIELDS = ( 'id', 'name', 'slug', 'address_line1', 'address_line2', 'city', 'state', 'country', 'postal_code', 'phone_number', 'email', 'person') class OrganizationSerializer(serializers.ModelSerializer): class Meta: model = ORGANIZATION_MODEL fields = ORGANIZATION_FIELDS class ManageOrganizationSerializer(OrganizationSerializer): slug = serializers.SlugField(required=False) name = serializers.CharField(required=True) email = serializers.EmailField(required=False) class Meta: model = ORGANIZATION_MODEL fields = ORGANIZATION_FIELDS + ('partner_organizations', 'created', 'updated')
Use strict was causing invalid javascript on bundling
this.ckan.module('collapsible', function($) { return { initialize: function() { this.activateCollapsibles() }, activateCollapsibles: function() { var elements = $('.collapsible'); for (var i = 0; i < elements.length; i++) { elements[i].addEventListener('click', function () { this.classList.toggle('collapsible-active'); var content = this.nextElementSibling; var icons = $('.collapsible-icon'); if (content.style.display === 'block') { content.style.display = 'none'; for (var i = 0; i < icons.length; i++) { icons[i].classList.remove("fa-chevron-up") icons[i].classList.add("fa-chevron-down") } } else { content.style.display = 'block'; for (var i = 0; i < icons.length; i++) { icons[i].classList.remove("fa-chevron-down") icons[i].classList.add("fa-chevron-up") } } }); } } } })
'use strict'; this.ckan.module('collapsible', function($) { return { initialize: function() { this.activateCollapsibles() }, activateCollapsibles: function() { var elements = $('.collapsible'); for (var i = 0; i < elements.length; i++) { elements[i].addEventListener('click', function () { this.classList.toggle('collapsible-active'); var content = this.nextElementSibling; var icons = $('.collapsible-icon'); if (content.style.display === 'block') { content.style.display = 'none'; for (var i = 0; i < icons.length; i++) { icons[i].classList.remove("fa-chevron-up") icons[i].classList.add("fa-chevron-down") } } else { content.style.display = 'block'; for (var i = 0; i < icons.length; i++) { icons[i].classList.remove("fa-chevron-down") icons[i].classList.add("fa-chevron-up") } } }); } } } })
Add flickr api key and secret options
export default { authToken: process.env.AUTH_TOKEN || 'secret', env: process.env.NODE_ENV, flickr: { apiKey: process.env.FLICKR_API_KEY || '123abc', secret: process.env.FLICKR_SECRET || '123abc' }, host: process.env.HOST || 'localhost', github: { apiUrl: 'https://api.github.com', username: process.env.GITHUB_USERNAME || 'username', accessToken: process.env.GITHUB_ACCESS_TOKEN || '123abc' }, jobs: { frequency: { githubActivity: process.env.JOBS_FREQUENCY_GITHUB || '00 */1 * * * *', updateCache: process.env.JOBS_FREQUENCY_CACHE || '00 */2 * * * *' } }, mongo: { url: process.env.MONGO_URL || 'mongodb://localhost:27017/FranVarney' }, port: process.env.PORT || 8000 }
export default { authToken: process.env.AUTH_TOKEN || 'secret', env: process.env.NODE_ENV, host: process.env.HOST || 'localhost', github: { apiUrl: 'https://api.github.com', username: process.env.GITHUB_USERNAME || 'username', accessToken: process.env.GITHUB_ACCESS_TOKEN || '123abc' }, jobs: { frequency: { githubActivity: process.env.JOBS_FREQUENCY_GITHUB || '00 */1 * * * *', updateCache: process.env.JOBS_FREQUENCY_CACHE || '00 */2 * * * *' } }, mongo: { url: process.env.MONGO_URL || 'mongodb://localhost:27017/FranVarney' }, port: process.env.PORT || 8000 }
Fix for high level registration test. * Exported single components now have compiled render function, not a template property.
import Vue from 'vue' import { default as VueMdl, MdlCheckbox, MdlBadge, components, directives } from '../../../src/vue-mdl' describe('Register', () => { it('exports single components', () => { MdlCheckbox.should.exist.and.be.an.Object MdlCheckbox.should.have.property('render') }) it('exports single directives', () => { MdlBadge.should.exist.and.be.an.Object MdlBadge.should.have.property('bind') }) it('exports all components', () => { components.should.exist.and.be.an.Object components.should.have.property('MdlCheckbox') components.MdlCheckbox.should.eql(MdlCheckbox) }) it('exports all directives', () => { directives.should.exist.and.be.an.Object directives.should.have.property('MdlBadge') directives.MdlBadge.should.eql(MdlBadge) }) it('exports a Vue plugin', () => { VueMdl.should.have.property('install') ;(() => Vue.use(VueMdl)).should.not.throw() }) it('has registered components', () => { Vue.component('MdlCheckbox').should.exist }) it('has registered directives', () => { Vue.directive('MdlBadge').should.exist }) })
import Vue from 'vue' import { default as VueMdl, MdlCheckbox, MdlBadge, components, directives } from '../../../src/vue-mdl' describe('Register', () => { it('exports single components', () => { MdlCheckbox.should.exist.and.be.an.Object MdlCheckbox.should.have.property('template') }) it('exports single directives', () => { MdlBadge.should.exist.and.be.an.Object MdlBadge.should.have.property('bind') }) it('exports all components', () => { components.should.exist.and.be.an.Object components.should.have.property('MdlCheckbox') components.MdlCheckbox.should.eql(MdlCheckbox) }) it('exports all directives', () => { directives.should.exist.and.be.an.Object directives.should.have.property('MdlBadge') directives.MdlBadge.should.eql(MdlBadge) }) it('exports a Vue plugin', () => { VueMdl.should.have.property('install') ;(() => Vue.use(VueMdl)).should.not.throw() }) it('has registered components', () => { Vue.component('MdlCheckbox').should.exist }) it('has registered directives', () => { Vue.directive('MdlBadge').should.exist }) })
Add simplified factory for channel
package org.realityforge.replicant.client; import arez.Arez; import arez.annotations.ArezComponent; import arez.annotations.Observable; import java.util.Objects; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * The Channel object contains the address of the channel and the optional filter for the channel. */ @ArezComponent public abstract class Channel { @Nonnull private final ChannelAddress _address; @Nullable private Object _filter; @Nonnull public static Channel create( @Nonnull final ChannelAddress address ) { return create( address, null ); } @Nonnull public static Channel create( @Nonnull final ChannelAddress address, @Nullable final Object filter ) { return new Arez_Channel( address, filter ); } Channel( @Nonnull final ChannelAddress address, @Nullable final Object filter ) { _address = Objects.requireNonNull( address ); _filter = filter; } @Nonnull public ChannelAddress getAddress() { return _address; } @Observable @Nullable public Object getFilter() { return _filter; } public void setFilter( @Nullable final Object filter ) { _filter = filter; } @Override public String toString() { if ( Arez.areNamesEnabled() ) { return "Channel[" + _address + " :: Filter=" + FilterUtil.filterToString( _filter ) + "]"; } else { return super.toString(); } } }
package org.realityforge.replicant.client; import arez.Arez; import arez.annotations.ArezComponent; import arez.annotations.Observable; import java.util.Objects; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * The Channel object contains the address of the channel and the optional filter for the channel. */ @ArezComponent public abstract class Channel { @Nonnull private final ChannelAddress _address; @Nullable private Object _filter; @Nonnull public static Channel create( @Nonnull final ChannelAddress address, @Nullable final Object filter ) { return new Arez_Channel( address, filter ); } Channel( @Nonnull final ChannelAddress address, @Nullable final Object filter ) { _address = Objects.requireNonNull( address ); _filter = filter; } @Nonnull public ChannelAddress getAddress() { return _address; } @Observable @Nullable public Object getFilter() { return _filter; } public void setFilter( @Nullable final Object filter ) { _filter = filter; } @Override public String toString() { if ( Arez.areNamesEnabled() ) { return "Channel[" + _address + " :: Filter=" + FilterUtil.filterToString( _filter ) + "]"; } else { return super.toString(); } } }
Make logs directory, simplify log to goat-yyyy-mm-dd.log
package goat import ( "bufio" "fmt" "log" "os" "time" ) func LogMng(doneChan chan bool, logChan chan string) { // Create log directory and file, and pull current date to add to logfile name now := time.Now() os.Mkdir("logs", os.ModeDir|os.ModePerm) logFile, err := os.Create(fmt.Sprintf("logs/goat-%d-%d-%d.log", now.Year(), now.Month(), now.Day())) if err != nil { fmt.Println(err) } // create a logger that will use the writer created above logger := log.New(bufio.NewWriter(logFile), "", log.Lmicroseconds|log.Lshortfile) amIDone := false msg := "" // wait for errer to be passed on the logChan channel or the done chan for !amIDone { select { case amIDone = <-doneChan: logFile.Close() case msg = <-logChan: logger.Println(msg) } } }
package goat import ( "bufio" "fmt" "log" "os" "time" ) func LogMng(doneChan chan bool, logChan chan string) { // create log file and pull current time to add to logfile name currentTime := time.Now().String() logFile, err := os.Create("GoatLog" + currentTime + ".log") if err != nil { fmt.Println(err) } writer := bufio.NewWriter(logFile) // create a logger that will use the writer created above logger := log.New(writer, "", log.Lmicroseconds|log.Lshortfile) amIDone := false msg := "" // wait for errer to be passed on the logChan channel or the done chan for !amIDone { select { case amIDone = <-doneChan: logFile.Close() case msg = <-logChan: logger.Println(msg) } } }
Use nose's test generator function
#!/usr/bin/env python #encoding:utf-8 #author:dbr/Ben #project:tvnamer #repository:http://github.com/dbr/tvnamer #license:Creative Commons GNU GPL v2 # http://creativecommons.org/licenses/GPL/2.0/ """Test tvnamer's filename parser """ import os import sys from copy import copy import unittest sys.path.append(os.path.join(os.path.abspath(sys.path[0]), "..")) from utils import FileParser from test_files import files def check_test(curtest): """Runs test case, used by test_generator """ parser = FileParser(curtest['input']) theep = parser.parse() assert theep.seriesname.lower() == curtest['seriesname'].lower() assert theep.seasonnumber == curtest['seasonnumber'] assert theep.episodenumber == curtest['episodenumber'] def test_generator(): """Generates test for each test case in test_files.py """ for category, testcases in files.items(): for testindex, curtest in enumerate(testcases): cur_tester = lambda x: check_test(x) cur_tester.description = '%s_%d' % (category, testindex) yield (cur_tester, curtest) if __name__ == '__main__': import nose nose.main()
#!/usr/bin/env python #encoding:utf-8 #author:dbr/Ben #project:tvnamer #repository:http://github.com/dbr/tvnamer #license:Creative Commons GNU GPL v2 # http://creativecommons.org/licenses/GPL/2.0/ """Test tvnamer's filename parser """ import os import sys import unittest sys.path.append(os.path.join(os.path.abspath(sys.path[0]), "..")) from utils import FileParser, warn from tvnamer_exceptions import InvalidFilename from test_files import files class test_filenames(unittest.TestCase): def setUp(self): pass def test_go(self): for category, testcases in files.items(): for curtest in testcases: parser = FileParser(curtest['input']) theep = parser.parse() self.assertEquals(theep.seasonnumber, curtest['seasonnumber']) self.assertEquals(theep.episodenumber, curtest['episodenumber']) if __name__ == '__main__': unittest.main()
Revert "Removed the "enabled" property since we're doing real deletes now" This reverts commit 5309419656a4b33115c44693a9941553359dce1a.
package ca.corefacility.bioinformatics.irida.web.controller.test.unit.support; import java.util.Date; import ca.corefacility.bioinformatics.irida.model.IridaThing; /** * * @author Franklin Bristow <franklin.bristow@phac-aspc.gc.ca> */ public class IdentifiableTestEntity implements IridaThing, Comparable<IdentifiableTestEntity> { Long id; private Date createdDate; private Date modifiedDate; public IdentifiableTestEntity() { } public Long getId() { return this.id; } public void setId(Long identifier) { this.id = identifier; } @Override public int compareTo(IdentifiableTestEntity o) { return createdDate.compareTo(o.createdDate); } @Override public Date getTimestamp() { return createdDate; } @Override public void setTimestamp(Date timestamp) { this.createdDate = timestamp; } @Override public String getLabel() { return null; } @Override public boolean isEnabled() { return true; } @Override public void setEnabled(boolean valid) { } public Date getModifiedDate() { return modifiedDate; } public void setModifiedDate(Date modifiedDate) { this.modifiedDate = modifiedDate; } }
package ca.corefacility.bioinformatics.irida.web.controller.test.unit.support; import java.util.Date; import ca.corefacility.bioinformatics.irida.model.IridaThing; /** * * @author Franklin Bristow <franklin.bristow@phac-aspc.gc.ca> */ public class IdentifiableTestEntity implements IridaThing, Comparable<IdentifiableTestEntity> { Long id; private Date createdDate; private Date modifiedDate; public IdentifiableTestEntity() { } public Long getId() { return this.id; } public void setId(Long identifier) { this.id = identifier; } @Override public int compareTo(IdentifiableTestEntity o) { return createdDate.compareTo(o.createdDate); } @Override public Date getTimestamp() { return createdDate; } @Override public void setTimestamp(Date timestamp) { this.createdDate = timestamp; } @Override public String getLabel() { return null; } public Date getModifiedDate() { return modifiedDate; } public void setModifiedDate(Date modifiedDate) { this.modifiedDate = modifiedDate; } }
Make this derive from the correct type
import werkzeug.debug import werkzeug.serving from jacquard.commands import BaseCommand from jacquard.service import get_wsgi_app class RunServer(BaseCommand): help = "run a (local, debug) server" def add_arguments(self, parser): parser.add_argument( '-p', '--port', type=int, default=8888, help="port to bind to", ) parser.add_argument( '-b', '--bind', type=str, default='::1', help="address to bind to", ) def handle(self, config, options): app = get_wsgi_app(config) werkzeug.serving.run_simple( options.bind, options.port, app, use_reloader=True, use_debugger=True, use_evalex=True, threaded=False, processes=1, )
import werkzeug.debug import werkzeug.serving from jacquard.commands import BaseCommand from jacquard.service import get_wsgi_app class RunServer(object): help = "run a (local, debug) server" def add_arguments(self, parser): parser.add_argument( '-p', '--port', type=int, default=8888, help="port to bind to", ) parser.add_argument( '-b', '--bind', type=str, default='::1', help="address to bind to", ) def handle(self, config, options): app = get_wsgi_app(config) werkzeug.serving.run_simple( options.bind, options.port, app, use_reloader=True, use_debugger=True, use_evalex=True, threaded=False, processes=1, )
Remove unintentional commas from argument list
#!/usr/bin/env python """Create a shop with article and order sequences. :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ import click from byceps.services.shop.sequence import service as sequence_service from byceps.services.shop.shop import service as shop_service from byceps.util.system import get_config_filename_from_env_or_exit from _util import app_context @click.command() @click.argument('shop_id') @click.argument('title') @click.argument('email_config_id') @click.argument('article_prefix') @click.argument('order_prefix') def execute(shop_id, title, email_config_id, article_prefix, order_prefix): shop = shop_service.create_shop(shop_id, title, email_config_id) sequence_service.create_article_number_sequence(shop.id, article_prefix) sequence_service.create_order_number_sequence(shop.id, order_prefix) click.secho('Done.', fg='green') if __name__ == '__main__': config_filename = get_config_filename_from_env_or_exit() with app_context(config_filename): execute()
#!/usr/bin/env python """Create a shop with article and order sequences. :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ import click from byceps.services.shop.sequence import service as sequence_service from byceps.services.shop.shop import service as shop_service from byceps.util.system import get_config_filename_from_env_or_exit from _util import app_context @click.command() @click.argument('shop_id',) @click.argument('title') @click.argument('email_config_id',) @click.argument('article_prefix') @click.argument('order_prefix') def execute(shop_id, title, email_config_id, article_prefix, order_prefix): shop = shop_service.create_shop(shop_id, title, email_config_id) sequence_service.create_article_number_sequence(shop.id, article_prefix) sequence_service.create_order_number_sequence(shop.id, order_prefix) click.secho('Done.', fg='green') if __name__ == '__main__': config_filename = get_config_filename_from_env_or_exit() with app_context(config_filename): execute()
Update now returns the account info
var Account = require('../../app/models/account'); exports.update = function (req, res) { Account.findById(req.params.id, function (err, account) { if (!account) return next(new Error('Could not load Document')); else { if (req.body.foreName) { account.foreName = req.body.foreName } if (req.body.sureName) { account.sureName = req.body.sureName } if (req.body.phoneNumber) { account.phoneNumber = req.body.phoneNumber } account.save(function (err) { if (err) res.json({ message: 'Error' }); else res.json(account); }); } }); }
var Account = require('../../app/models/account'); exports.update = function (req, res) { Account.findById(req.params.id, function (err, account) { if (!account) return next(new Error('Could not load Document')); else { if (req.body.foreName) { account.foreName = req.body.foreName } if (req.body.sureName) { account.sureName = req.body.sureName } if (req.body.phoneNumber) { account.phoneNumber = req.body.phoneNumber } account.save(function (err) { if (err) res.json({ message: 'Error' }); else res.json({ message: 'Account Updated' }); }); } }); }
Add missing spotbugs annotations in xpath-impl Somehow we have been missing this annotation import, fix that up. Change-Id: Ib39814bca421b6518f7e1bb0e8c8ec38350747fb Signed-off-by: Robert Varga <91ae5aa8c7a9f7e57b701db766e23e544aaa6ae9@pantheon.tech>
/* * Copyright (c) 2020 PANTHEON.tech, s.r.o. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ import org.opendaylight.yangtools.yang.xpath.api.YangXPathParserFactory; import org.opendaylight.yangtools.yang.xpath.impl.AntlrXPathParserFactory; module org.opendaylight.yangtools.yang.xpath.impl { exports org.opendaylight.yangtools.yang.xpath.impl.di; provides YangXPathParserFactory with AntlrXPathParserFactory; requires java.xml; requires org.opendaylight.yangtools.yang.common; requires org.opendaylight.yangtools.yang.xpath.api; requires org.opendaylight.yangtools.yang.xpath.antlr; requires org.slf4j; // Annotations requires static com.github.spotbugs.annotations; requires static javax.inject; requires static metainf.services; requires static org.eclipse.jdt.annotation; requires static org.osgi.service.component.annotations; }
/* * Copyright (c) 2020 PANTHEON.tech, s.r.o. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ import org.opendaylight.yangtools.yang.xpath.api.YangXPathParserFactory; import org.opendaylight.yangtools.yang.xpath.impl.AntlrXPathParserFactory; module org.opendaylight.yangtools.yang.xpath.impl { exports org.opendaylight.yangtools.yang.xpath.impl.di; provides YangXPathParserFactory with AntlrXPathParserFactory; requires java.xml; requires org.opendaylight.yangtools.yang.common; requires org.opendaylight.yangtools.yang.xpath.api; requires org.opendaylight.yangtools.yang.xpath.antlr; requires org.slf4j; // Annotations requires static javax.inject; requires static metainf.services; requires static org.eclipse.jdt.annotation; requires static org.osgi.service.component.annotations; }
Make the httpreason template tag return empty string on *any* exception.
from django import template from django.template.defaultfilters import stringfilter, yesno from django.http.response import REASON_PHRASES register = template.Library() @register.filter @stringfilter def truthy(value, arg=None): """Wraps django's yesno filter to allow for JavaScript-style true or false string values.""" truthiness = None if value.lower() == 'true': truthiness = True elif value.lower() == 'false': truthiness = False return yesno(truthiness, arg) @register.filter def httpreason(value, arg=False): """ Uses django's REASON_PHRASES to change a status_code into a textual reason. Optional True/False argument allows you to return a string with code number *and* phrase. Defaults to False""" try: value_int = int(value) except Exception: return '' phrase = REASON_PHRASES.get(value_int, 'UNKNOWN STATUS CODE') if arg: phrase = '{0}: {1}'.format(value, phrase) return phrase
from django import template from django.template.defaultfilters import stringfilter, yesno from django.http.response import REASON_PHRASES register = template.Library() @register.filter @stringfilter def truthy(value, arg=None): """Wraps django's yesno filter to allow for JavaScript-style true or false string values.""" truthiness = None if value.lower() == 'true': truthiness = True elif value.lower() == 'false': truthiness = False return yesno(truthiness, arg) @register.filter def httpreason(value, arg=False): """ Uses django's REASON_PHRASES to change a status_code into a textual reason. Optional True/False argument allows you to return a string with code number *and* phrase. Defaults to False""" try: value_int = int(value) except TypeError: return '' phrase = REASON_PHRASES.get(value_int, 'UNKNOWN STATUS CODE') if arg: phrase = '{0}: {1}'.format(value, phrase) return phrase
Update DotEnv registration to version 4
<?php declare(strict_types=1); /** * This file is part of Laravel Zero. * * (c) Nuno Maduro <enunomaduro@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace LaravelZero\Framework\Bootstrap; use Dotenv\Dotenv; use LaravelZero\Framework\Application; use LaravelZero\Framework\Contracts\BoostrapperContract; use LaravelZero\Framework\Providers\Build\Build; /** * @internal */ final class BuildLoadEnvironmentVariables implements BoostrapperContract { /** * @var \LaravelZero\Framework\Providers\Build\Build */ private $build; /** * BuildLoadEnvironmentVariables constructor. * * @param \LaravelZero\Framework\Providers\Build\Build $build */ public function __construct(Build $build) { $this->build = $build; } /** * {@inheritdoc} */ public function bootstrap(Application $app): void { /* * Override environment variables with the environment file along side the Phar file. */ if ($this->build->shouldUseEnvironmentFile()) { Dotenv::createMutable($this->build->getDirectoryPath(), $this->build->environmentFile())->load(); } } }
<?php declare(strict_types=1); /** * This file is part of Laravel Zero. * * (c) Nuno Maduro <enunomaduro@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace LaravelZero\Framework\Bootstrap; use Dotenv\Dotenv; use LaravelZero\Framework\Application; use LaravelZero\Framework\Contracts\BoostrapperContract; use LaravelZero\Framework\Providers\Build\Build; /** * @internal */ final class BuildLoadEnvironmentVariables implements BoostrapperContract { /** * @var \LaravelZero\Framework\Providers\Build\Build */ private $build; /** * BuildLoadEnvironmentVariables constructor. * * @param \LaravelZero\Framework\Providers\Build\Build $build */ public function __construct(Build $build) { $this->build = $build; } /** * {@inheritdoc} */ public function bootstrap(Application $app): void { /* * Override environment variables with the environment file along side the Phar file. */ if ($this->build->shouldUseEnvironmentFile()) { Dotenv::create($this->build->getDirectoryPath(), $this->build->environmentFile())->overload(); } } }
Remove reference to container variable
<?php namespace Noback\PHPUnitTestServiceContainer\PHPUnit; use Noback\PHPUnitTestServiceContainer\ServiceContainer; use Noback\PHPUnitTestServiceContainer\ServiceContainerInterface; use Noback\PHPUnitTestServiceContainer\ServiceProviderInterface; /** * Extend from this test case to make use of a service container in your tests */ abstract class AbstractTestCaseWithServiceContainer extends \PHPUnit_Framework_TestCase { /** * @var ServiceContainerInterface */ protected $container; /** * Return an array of ServiceProviderInterface instances you want to use in this test case * * @return ServiceProviderInterface[] */ abstract protected function getServiceProviders(); /** * When overriding this method, make sure you call parent::setUp() */ protected function setUp() { $this->container = new ServiceContainer(); foreach ($this->getServiceProviders() as $serviceProvider) { $this->container->register($serviceProvider); } } /** * When overriding this method, make sure you call parent::tearDown() */ protected function tearDown() { $this->container->tearDown(); $this->container = null; } }
<?php namespace Noback\PHPUnitTestServiceContainer\PHPUnit; use Noback\PHPUnitTestServiceContainer\ServiceContainer; use Noback\PHPUnitTestServiceContainer\ServiceContainerInterface; use Noback\PHPUnitTestServiceContainer\ServiceProviderInterface; /** * Extend from this test case to make use of a service container in your tests */ abstract class AbstractTestCaseWithServiceContainer extends \PHPUnit_Framework_TestCase { /** * @var ServiceContainerInterface */ protected $container; /** * Return an array of ServiceProviderInterface instances you want to use in this test case * * @return ServiceProviderInterface[] */ abstract protected function getServiceProviders(); /** * When overriding this method, make sure you call parent::setUp() */ protected function setUp() { $this->container = new ServiceContainer(); foreach ($this->getServiceProviders() as $serviceProvider) { $this->container->register($serviceProvider); } } /** * When overriding this method, make sure you call parent::tearDown() */ protected function tearDown() { $this->container->tearDown(); } }
Make development status be Alpha.
#!/usr/bin/env python from distutils.core import setup import dougrain base_url = "http://github.com/wharris/dougrain/" setup( name = 'dougrain', version = dougrain.__version__, description = 'HAL JSON parser and generator', author = 'Will Harris', author_email = 'will@greatlibrary.net', url = base_url, packages = ['dougrain'], provides = ['dougrain'], long_description=open("README.md").read(), install_requires = ['uritemplate >= 0.5.1'], classifiers = [ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD Licencse', 'Programming Language :: Python', 'Operating System :: POSIX', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
#!/usr/bin/env python from distutils.core import setup import dougrain base_url = "http://github.com/wharris/dougrain/" setup( name = 'dougrain', version = dougrain.__version__, description = 'HAL JSON parser and generator', author = 'Will Harris', author_email = 'will@greatlibrary.net', url = base_url, packages = ['dougrain'], provides = ['dougrain'], long_description=open("README.md").read(), install_requires = ['uritemplate >= 0.5.1'], classifiers = [ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD Licencse', 'Programming Language :: Python', 'Operating System :: POSIX', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
Use ES5 functions instead of arrow functions
var data = require('./data'); var accounting = require('accounting'); var CurrencyFormatter = function() { this.defaultCurrency = { symbol: '', thousandsSeparator: ',', decimalSeparator: '.', symbolOnLeft: true, spaceBetweenAmountAndSymbol: false, decimalDigits: 2 } } CurrencyFormatter.prototype.format = function (value, options) { var currency = data.find(function(c) { return c.code === options.code; }) || this.defaultCurrency; var symbolOnLeft = currency.symbolOnLeft; var spaceBetweenAmountAndSymbol = currency.spaceBetweenAmountAndSymbol; var format = ""; if (symbolOnLeft) { format = spaceBetweenAmountAndSymbol ? "%s %v" : "%s%v" } else { format = spaceBetweenAmountAndSymbol ? "%v %s" : "%v%s" } return accounting.formatMoney(value, { symbol: options.symbol || currency.symbol, decimal: options.decimal || currency.decimalSeparator, thousand: options.thousand || currency.thousandsSeparator, precision: options.precision || currency.decimalDigits, format: options.format || format }) } CurrencyFormatter.prototype.findCurrency = function (currencyCode) { return data.find(function(c) { return c.code === currencyCode; }); } module.exports = new CurrencyFormatter();
var data = require('./data'); var accounting = require('accounting'); var CurrencyFormatter = function() { this.defaultCurrency = { symbol: '', thousandsSeparator: ',', decimalSeparator: '.', symbolOnLeft: true, spaceBetweenAmountAndSymbol: false, decimalDigits: 2 } } CurrencyFormatter.prototype.format = function (value, options) { var currency = data.find(c => c.code === options.code) || this.defaultCurrency; var symbolOnLeft = currency.symbolOnLeft; var spaceBetweenAmountAndSymbol = currency.spaceBetweenAmountAndSymbol; var format = ""; if (symbolOnLeft) { format = spaceBetweenAmountAndSymbol ? "%s %v" : "%s%v" } else { format = spaceBetweenAmountAndSymbol ? "%v %s" : "%v%s" } return accounting.formatMoney(value, { symbol: options.symbol || currency.symbol, decimal: options.decimal || currency.decimalSeparator, thousand: options.thousand || currency.thousandsSeparator, precision: options.precision || currency.decimalDigits, format: options.format || format }) } CurrencyFormatter.prototype.findCurrency = function (currencyCode) { return data.find(c => c.code === currencyCode); } module.exports = new CurrencyFormatter();
Update code to follow new Eslint rules, eslint-plugin-jsx-a11y
import React from 'react'; import Navbar from '../Navbar/NavbarComponent'; import Footer from '../Footer/FooterContainer'; import './App.scss'; export default class App extends React.Component { static propTypes = { children: React.PropTypes.object.isRequired, viewer: React.PropTypes.object.isRequired }; render() { return ( <div className='app'> <Navbar /> <div className='greeting'> <h1>Sawasdee, Sawasdee!</h1> <p>Always a pleasure scaffolding your apps</p> <img src={require('../../assets/yeoman.png')} alt='yeoman' /> </div> <div className='content'> {this.props.children} </div> <Footer viewer={this.props.viewer} /> </div> ); } }
import React from 'react'; import Navbar from '../Navbar/NavbarComponent'; import Footer from '../Footer/FooterContainer'; import './App.scss'; export default class App extends React.Component { static propTypes = { children: React.PropTypes.object.isRequired, viewer: React.PropTypes.object.isRequired }; render() { return ( <div className='app'> <Navbar /> <div className='greeting'> <h1>Sawasdee, Sawasdee!</h1> <p>Always a pleasure scaffolding your apps</p> <img src={require('../../assets/yeoman.png')} /> </div> <div className='content'> {this.props.children} </div> <Footer viewer={this.props.viewer} /> </div> ); } }