text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Test for infinite beam QC
import os import unittest2 as unittest from tkp.quality.restoringbeam import beam_invalid from tkp.testutil.decorators import requires_data from tkp import accessors from tkp.testutil.data import DATAPATH fits_file = os.path.join(DATAPATH, 'quality/noise/bad/home-pcarrol-msss-3C196a-analysis-band6.corr.fits') @requires_data(fits_file) class TestRestoringBeam(unittest.TestCase): def test_header(self): image = accessors.open(fits_file) (semimaj, semimin, theta) = image.beam self.assertFalse(beam_invalid(semimaj, semimin)) # TODO: this is for FOV calculation and checking #data = tkp.quality.restoringbeam.parse_fits(image) #frequency = image.freq_eff #wavelength = scipy.constants.c/frequency #d = 32.25 #fwhm = tkp.lofar.beam.fwhm(wavelength, d) #fov = tkp.lofar.beam.fov(fwhm) def test_infinite(self): smaj, smin, theta = float('inf'), float('inf'), float('inf') self.assertTrue(beam_invalid(smaj, smin, theta)) if __name__ == '__main__': unittest.main()
import os import unittest2 as unittest from tkp.quality.restoringbeam import beam_invalid from tkp.testutil.decorators import requires_data from tkp import accessors from tkp.testutil.data import DATAPATH fits_file = os.path.join(DATAPATH, 'quality/noise/bad/home-pcarrol-msss-3C196a-analysis-band6.corr.fits') @requires_data(fits_file) class TestRestoringBeam(unittest.TestCase): def test_header(self): image = accessors.open(fits_file) (semimaj, semimin, theta) = image.beam self.assertFalse(beam_invalid(semimaj, semimin)) # TODO: this is for FOV calculation and checking #data = tkp.quality.restoringbeam.parse_fits(image) #frequency = image.freq_eff #wavelength = scipy.constants.c/frequency #d = 32.25 #fwhm = tkp.lofar.beam.fwhm(wavelength, d) #fov = tkp.lofar.beam.fov(fwhm) if __name__ == '__main__': unittest.main()
Fix inclusione css foundation dopo lo spostamento
<!DOCTYPE html> <!--[if IE 8]> <html class="no-js lt-ie9" lang="en"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]--> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <title>@lang('gorilla.app_name')</title> {{ HTML::style('static/css/normalize.css') }} {{ HTML::style('static/css/plugins/foundation/foundation.min.css') }} {{ HTML::style('static/css/admin.css') }} {{ HTML::script('static/js/modernizr.min.js') }} </head> <body id="auth"> <div class="row"> <div class="large-4 large-centered columns"> <h1 class="gorilla text-center">@lang('gorilla.app_name')</h1> @yield('content') </div> </div> <!-- scripts --> {{ HTML::script('static/js/jquery.min.js') }} {{ HTML::script('static/js/plugins/foundation/foundation.min.js') }} {{ HTML::script('static/js/plugins/placeholder/jquery.placeholder.min.js') }} {{ HTML::script('static/js/admin.js') }} @yield('bottom_scripts') </body> </html>
<!DOCTYPE html> <!--[if IE 8]> <html class="no-js lt-ie9" lang="en"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]--> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <title>@lang('gorilla.app_name')</title> {{ HTML::style('static/css/normalize.css') }} {{ HTML::style('static/css/foundation.min.css') }} {{ HTML::style('static/css/admin.css') }} {{ HTML::script('static/js/modernizr.min.js') }} </head> <body id="auth"> <div class="row"> <div class="large-4 large-centered columns"> <h1 class="gorilla text-center">@lang('gorilla.app_name')</h1> @yield('content') </div> </div> <!-- scripts --> {{ HTML::script('static/js/jquery.min.js') }} {{ HTML::script('static/js/plugins/foundation/foundation.min.js') }} {{ HTML::script('static/js/plugins/placeholder/jquery.placeholder.min.js') }} {{ HTML::script('static/js/admin.js') }} @yield('bottom_scripts') </body> </html>
Increase test timeout to 60s
/* * Copyright 2018 New Vector Ltd * * 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.matrix.androidsdk.common; public class TestConstants { public static final String TESTS_HOME_SERVER_URL = "http://10.0.2.2:8080"; // Time out to use when waiting for server response public static final int AWAIT_TIME_OUT_MILLIS = 60_000; public static final String USER_ALICE = "Alice"; public static final String USER_BOB = "Bob"; public static final String USER_SAM = "Sam"; public static final String PASSWORD = "password"; }
/* * Copyright 2018 New Vector Ltd * * 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.matrix.androidsdk.common; public class TestConstants { public static final String TESTS_HOME_SERVER_URL = "http://10.0.2.2:8080"; // Time out to use when waiting for server response public static final int AWAIT_TIME_OUT_MILLIS = 30000; public static final String USER_ALICE = "Alice"; public static final String USER_BOB = "Bob"; public static final String USER_SAM = "Sam"; public static final String PASSWORD = "password"; }
FIX Removal of existing lock timer on form load
jQuery.entwine("editlock", function($) { var lockTimer = 0; $('.cms-edit-form').entwine({ RecordID: null, RecordClass: null, LockURL: null, onmatch: function() { // clear any previously bound lock timer if (lockTimer) { clearTimeout(lockTimer); } if(this.hasClass('edit-locked')){ this.showLockMessage(); }else{ this.setRecordID(this.data('recordid')); this.setRecordClass(this.data('recordclass')); this.setLockURL(this.data('lockurl')); this.lockRecord(); } }, lockRecord: function() { if(!this.getRecordID() || !this.getRecordClass() || !this.getLockURL()){ return false; } var data = { RecordID: this.getRecordID(), RecordClass: this.getRecordClass() }; $.post(this.getLockURL(), data).done(function(result){ lockTimer = setTimeout(function(){$('.cms-edit-form').lockRecord()},10000); }); }, showLockMessage: function(){ this.find('p.message').first().after('<p/>') .addClass('message warning') .css('overflow', 'hidden') .html(this.data('lockedmessage')) .show(); } }); });
jQuery.entwine("editlock", function($) { $('.cms-edit-form').entwine({ RecordID: null, RecordClass: null, LockURL: null, onmatch: function() { if(this.hasClass('edit-locked')){ this.showLockMessage(); }else{ this.setRecordID(this.data('recordid')); this.setRecordClass(this.data('recordclass')); this.setLockURL(this.data('lockurl')); this.lockRecord(); } }, lockRecord: function() { if(!this.getRecordID() || !this.getRecordClass() || !this.getLockURL()){ return false; } var data = { RecordID: this.getRecordID(), RecordClass: this.getRecordClass() }; $.post(this.getLockURL(), data).done(function(result){ setTimeout(function(){$('.cms-edit-form').lockRecord()},10000); }); }, showLockMessage: function(){ this.find('p.message').first().after('<p/>') .addClass('message warning') .css('overflow', 'hidden') .html(this.data('lockedmessage')) .show(); } }); });
Make Trunks have opposite directions in the included lanes
""" Copyright (C) 2017 Open Source Robotics Foundation 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. """ from road import Road class Trunk(Road): def __init__(self, name=None): super(Trunk, self).__init__(name) self.add_lane(2) self.add_lane(-2, reversed=True) def accept(self, generator): generator.start_trunk(self) for lane in self.lanes(): lane.accept(generator) generator.end_trunk(self)
""" Copyright (C) 2017 Open Source Robotics Foundation 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. """ from road import Road class Trunk(Road): def __init__(self, name=None): super(Trunk, self).__init__(name) self.add_lane(2) self.add_lane(-2) def accept(self, generator): generator.start_trunk(self) for lane in self.lanes(): lane.accept(generator) generator.end_trunk(self)
Use SQLAlchemy extension in Flask app.
""" Flask server app. """ import datetime as dt import sys import flask from flask.ext.sqlalchemy import SQLAlchemy import coils import mapping # Load configuration file. CONFIG = sys.argv[1] if len(sys.argv)>=2 else 'wabbit.cfg' config = coils.Config(CONFIG) # Initialize Flask and SQLAlchemy. app = flask.Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://{}:{}@{}/{}'.format( config['username'], config['password'], config['host'], config['db_name']) db = SQLAlchemy(app) @app.route('/') def index(): """Render the index page.""" return flask.render_template('index.html') @app.route('/info') def info(): """Return JSON of server info.""" now = dt.datetime.now() datum = db.session.query(mapping.Datum).\ filter(mapping.Datum.name=='size')[0] return flask.jsonify(server_time=now, db_size=datum.value) if __name__ == '__main__': app.run()
""" Flask server app. """ import datetime as dt import sys import flask import sqlalchemy as sa import coils import tables import mapping app = flask.Flask(__name__) # Load configuration file. CONFIG = sys.argv[1] if len(sys.argv)>=2 else 'wabbit.cfg' config = coils.Config(CONFIG) @app.route('/') def index(): """Render the index page.""" return flask.render_template('index.html') @app.route('/info') def info(): """Return JSON of server info.""" # Connect to database engine. engine = sa.create_engine( 'mysql://{}:{}@{}/{}'.format( config['username'], config['password'], config['host'], config['db_name'])) Session = sa.orm.sessionmaker(bind=engine) session = Session() now = dt.datetime.now() datum = session.query(mapping.Datum).\ filter(mapping.Datum.name=='size')[0] return flask.jsonify(server_time=now, db_size=datum.value) if __name__ == '__main__': app.run()
Delete references field to fix userId and groupId bugs
module.exports = { up: (queryInterface, Sequelize) => queryInterface.createTable('Messages', { id: { allowNull: false, autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER }, content: { type: Sequelize.STRING }, createdAt: { allowNull: false, type: Sequelize.DATE }, updatedAt: { allowNull: false, type: Sequelize.DATE }, userId: { type: Sequelize.INTEGER, onDelete: 'CASCADE' }, groupId: { type: Sequelize.INTEGER, onDelete: 'CASCADE' }, }), down(queryInterface /* , Sequelize */) { queryInterface.dropTable('Messages'); } };
module.exports = { up: (queryInterface, Sequelize) => queryInterface.createTable('Messages', { id: { allowNull: false, autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER }, content: { type: Sequelize.STRING }, createdAt: { allowNull: false, type: Sequelize.DATE }, updatedAt: { allowNull: false, type: Sequelize.DATE }, userId: { type: Sequelize.INTEGER, onDelete: 'CASCADE', references: { model: 'Users', key: 'id', as: 'userId', }, }, groupId: { type: Sequelize.INTEGER, onDelete: 'CASCADE', references: { model: 'Groups', key: 'id', as: 'groupId', }, }, }), down(queryInterface /* , Sequelize */) { queryInterface.dropTable('Messages'); } };
Add all-krajee.js to Select2 Assets
<?php /** * @copyright Copyright &copy; Kartik Visweswaran, Krajee.com, 2014 - 2015 * @package yii2-widgets * @subpackage yii2-widget-select2 * @version 2.0.2 */ namespace kartik\select2; use Yii; /** * Asset bundle for Select2 Widget * * @author Kartik Visweswaran <kartikv2@gmail.com> * @since 1.0 */ class Select2Asset extends \kartik\base\AssetBundle { /** * @inheritdoc */ public function init() { $this->setSourcePath(__DIR__ . '/assets'); $this->setupAssets('css', ['css/select2']); $this->setupAssets('js', ['js/all-krajee', 'js/select2.full', 'js/select2-krajee']); parent::init(); } }
<?php /** * @copyright Copyright &copy; Kartik Visweswaran, Krajee.com, 2014 - 2015 * @package yii2-widgets * @subpackage yii2-widget-select2 * @version 2.0.2 */ namespace kartik\select2; use Yii; /** * Asset bundle for Select2 Widget * * @author Kartik Visweswaran <kartikv2@gmail.com> * @since 1.0 */ class Select2Asset extends \kartik\base\AssetBundle { /** * @inheritdoc */ public function init() { $this->setSourcePath(__DIR__ . '/assets'); $this->setupAssets('css', ['css/select2']); $this->setupAssets('js', ['js/select2.full', 'js/select2-krajee']); parent::init(); } }
Use decimal instead of int for money
# -*- coding: utf-8 -*- from __future__ import annotations from datetime import date from decimal import Decimal from typing import List, Optional from sipa.model.pycroft.unserialize import unserializer @unserializer class UserData: id: int user_id: str login: str name: str status: UserStatus room: str mail: str cache: bool properties: List[str] traffic_history: List[TrafficHistoryEntry] interfaces: List[Interface] finance_balance: Decimal finance_history: List[FinanceHistoryEntry] # TODO implement `cls.Meta.custom_constructors`, use `parse_date` for this last_finance_update: str # TODO introduce properties once they can be excluded membership_end_date: str @unserializer class UserStatus: member: bool traffic_exceeded: bool network_access: bool account_balanced: bool violation: bool @unserializer class Interface: id: int mac: str ips: List[str] @unserializer class TrafficHistoryEntry: timestamp: str ingress: Optional[int] egress: Optional[int] @unserializer class FinanceHistoryEntry: valid_on: str amount: Decimal description: str
# -*- coding: utf-8 -*- from __future__ import annotations from datetime import date from decimal import Decimal from typing import List, Optional from sipa.model.pycroft.unserialize import unserializer @unserializer class UserData: id: int user_id: str login: str name: str status: UserStatus room: str mail: str cache: bool properties: List[str] traffic_history: List[TrafficHistoryEntry] interfaces: List[Interface] finance_balance: Decimal finance_history: List[FinanceHistoryEntry] # TODO implement `cls.Meta.custom_constructors`, use `parse_date` for this last_finance_update: str # TODO introduce properties once they can be excluded membership_end_date: str @unserializer class UserStatus: member: bool traffic_exceeded: bool network_access: bool account_balanced: bool violation: bool @unserializer class Interface: id: int mac: str ips: List[str] @unserializer class TrafficHistoryEntry: timestamp: str ingress: Optional[int] egress: Optional[int] @unserializer class FinanceHistoryEntry: valid_on: str amount: int description: str
Remove Parser, export Encoder and Decoder
/** * Library version. */ exports.version = '0.0.1'; /** * Constructors. */ exports.Batch = require('./batch'); exports.Decoder = require('./decoder'); exports.Encoder = require('./encoder'); exports.Socket = require('./sockets/sock'); exports.Queue = require('./sockets/queue'); exports.PubSocket = require('./sockets/pub'); exports.SubSocket = require('./sockets/sub'); exports.PushSocket = require('./sockets/push'); exports.PullSocket = require('./sockets/pull'); exports.EmitterSocket = require('./sockets/emitter'); /** * Socket types. */ exports.types = { stream: exports.Socket, queue: exports.Queue, pub: exports.PubSocket, sub: exports.SubSocket, push: exports.PushSocket, pull: exports.PullSocket, emitter: exports.EmitterSocket }; /** * Codecs. */ exports.codec = require('./codecs'); /** * Return a new socket of the given `type`. * * @param {String} type * @param {Object} options * @return {Socket} * @api public */ exports.socket = function(type, options){ var fn = exports.types[type]; if (!fn) throw new Error('invalid socket type "' + type + '"'); return new fn(options); };
/** * Library version. */ exports.version = '0.0.1'; /** * Constructors. */ exports.Batch = require('./batch'); exports.Parser = require('./parser'); exports.Socket = require('./sockets/sock'); exports.Queue = require('./sockets/queue'); exports.PubSocket = require('./sockets/pub'); exports.SubSocket = require('./sockets/sub'); exports.PushSocket = require('./sockets/push'); exports.PullSocket = require('./sockets/pull'); exports.EmitterSocket = require('./sockets/emitter'); /** * Socket types. */ exports.types = { stream: exports.Socket, queue: exports.Queue, pub: exports.PubSocket, sub: exports.SubSocket, push: exports.PushSocket, pull: exports.PullSocket, emitter: exports.EmitterSocket }; /** * Codecs. */ exports.codec = require('./codecs'); /** * Return a new socket of the given `type`. * * @param {String} type * @param {Object} options * @return {Socket} * @api public */ exports.socket = function(type, options){ var fn = exports.types[type]; if (!fn) throw new Error('invalid socket type "' + type + '"'); return new fn(options); };
Use ruby style instance variables for Method
<?php namespace Phuby; class Method extends Object { static function initialized($self) { $self->attr_reader('receiver'); } function initialize($unbound, $receiver) { $this->{'@unbound'} = $unbound; $this->{'@receiver'} = $receiver; } function call($args = null) { return call_user_func_array($this->to_proc(), func_get_args()); } function inspect() { return '<'.get_called_class().': '.get_class($this->{'@receiver'}).'#'.$this->{'@unbound'}->name().'>'; } function splat($args) { return call_user_func_array([$this, 'call'], $args); } function to_proc() { return $this->{'@unbound'}->to_proc()->bindTo($this->{'@receiver'}); } function unbind() { return $this->{'@unbound'}; } }
<?php namespace Phuby; class Method extends Object { protected $unbound; protected $receiver; function initialize($unbound, $receiver) { $this->unbound = $unbound; $this->receiver = $receiver; } function call($args = null) { return call_user_func_array($this->to_proc(), func_get_args()); } function inspect() { return '<'.get_called_class().': '.get_class($this->receiver).'#'.$this->unbound->name().'>'; } function receiver() { return $this->receiver; } function splat($args) { return call_user_func_array([$this, 'call'], $args); } function to_proc() { return $this->unbound->to_proc()->bindTo($this->receiver); } function unbind() { return $this->unbound; } }
Remove old test code, test non API paginated request early return
<?php namespace BryanCrowe\ApiPagination\Test; use BryanCrowe\ApiPagination\Controller\Component\ApiPaginationComponent; use Cake\Controller\ComponentRegistry; use Cake\Controller\Controller; use Cake\Core\Plugin; use Cake\Event\Event; use Cake\Network\Request; use Cake\Network\Response; use Cake\TestSuite\TestCase; /** * ApiPaginationComponentTest class */ class ApiPaginationComponentTest extends TestCase { /** * setUp method * * @return void */ public function setUp() { parent::setUp(); } /** * tearDown method * * @return void */ public function tearDown() { parent::tearDown(); } public function testNonApiPaginatedRequest() { $request = new Request('/'); $response = $this->getMock('Cake\Network\Response'); $controller = new Controller($request, $response); $apiPaginationComponent = new ApiPaginationComponent($controller->components()); $event = new Event('Controller.beforeRender', $controller); $this->assertNull($apiPaginationComponent->beforeRender($event)); } }
<?php namespace BryanCrowe\ApiPagination\Test; use BryanCrowe\ApiPagination\Controller\Component\ApiPaginationComponent; use Cake\Controller\ComponentRegistry; use Cake\Controller\Controller; use Cake\Core\Plugin; use Cake\Network\Request; use Cake\Network\Response; use Cake\TestSuite\TestCase; /** * ApiPaginationComponentTest class */ class ApiPaginationComponentTest extends TestCase { /** * setUp method * * @return void */ public function setUp() { parent::setUp(); } /** * tearDown method * * @return void */ public function tearDown() { parent::tearDown(); unset($this->component, $this->controller); } public function testInit() { $request = new Request('/'); $response = $this->getMock('Cake\Network\Response'); $controller = new Controller($request, $response); $controller->loadComponent('BryanCrowe/ApiPagination.ApiPagination'); $expected = [ 'key' => 'pagination', 'aliases' => [], 'visible' => [] ]; $result = $controller->ApiPagination->config(); $this->assertSame($expected, $result); } }
Use cast_id instead of id. This seems to get rid of duplicate keys for the 'casts' tab of a Movie. Before, Guardians of the Galaxy Vol 2 would have duplicate keys.
import React, { PropTypes } from 'react'; import { Text, View, Image } from 'react-native'; import styles from './styles/Casts'; import { TMDB_IMG_URL } from '../../../constants/api'; const Casts = ({ info, getTabHeight }) => { let computedHeight = (80 + 15) * info.casts.cast.length; // (castImage.height + castContainer.marginBottom) computedHeight += 447 + 40; // Header height + container ((20 paddingVertical) = 40) return ( <View style={styles.container} onLayout={getTabHeight.bind(this, 'casts', computedHeight)}> { info.casts.cast.map(item => ( <View key={item.cast_id} style={styles.castContainer}> <Image source={{ uri: `${TMDB_IMG_URL}/w185/${item.profile_path}` }} style={styles.castImage} /> <View style={styles.characterContainer}> <Text style={styles.characterName}> {item.name} </Text> <Text style={styles.asCharacter}> {item.character && `as ${item.character}`} </Text> </View> </View> )) } </View> ); }; Casts.propTypes = { info: PropTypes.object.isRequired, getTabHeight: PropTypes.func.isRequired }; export default Casts;
import React, { PropTypes } from 'react'; import { Text, View, Image } from 'react-native'; import styles from './styles/Casts'; import { TMDB_IMG_URL } from '../../../constants/api'; const Casts = ({ info, getTabHeight }) => { let computedHeight = (80 + 15) * info.casts.cast.length; // (castImage.height + castContainer.marginBottom) computedHeight += 447 + 40; // Header height + container ((20 paddingVertical) = 40) return ( <View style={styles.container} onLayout={getTabHeight.bind(this, 'casts', computedHeight)}> { info.casts.cast.map(item => ( <View key={item.id} style={styles.castContainer}> <Image source={{ uri: `${TMDB_IMG_URL}/w185/${item.profile_path}` }} style={styles.castImage} /> <View style={styles.characterContainer}> <Text style={styles.characterName}> {item.name} </Text> <Text style={styles.asCharacter}> {item.character && `as ${item.character}`} </Text> </View> </View> )) } </View> ); }; Casts.propTypes = { info: PropTypes.object.isRequired, getTabHeight: PropTypes.func.isRequired }; export default Casts;
Make the Guitar Society __str__ Method a bit more Logical
# -*- coding: utf-8 -*- from django.db import models from django_countries.fields import CountryField class GuitarSociety(models.Model): """ Represents a single guitar society. .. versionadded:: 0.1 """ #: the name of the society #: ..versionadded:: 0.1 name = models.CharField(max_length=1024) #: the society's url #: ..versionadded:: 0.1 link = models.URLField(max_length=255) #: The country in which the society resides #: .. versionadded:: 0.1 country = CountryField() #: A free form "city" or "region" field used to display where #: exactly the society is within a country #: .. versionadded:: 0.1 region = models.CharField(max_length=512, null=True, default=None, blank=True) def __str__(self): return self.name def __repr__(self): return 'GuitarSociety("{}")'.format(self.name)
# -*- coding: utf-8 -*- from django.db import models from django_countries.fields import CountryField class GuitarSociety(models.Model): """ Represents a single guitar society. .. versionadded:: 0.1 """ #: the name of the society #: ..versionadded:: 0.1 name = models.CharField(max_length=1024) #: the society's url #: ..versionadded:: 0.1 link = models.URLField(max_length=255) #: The country in which the society resides #: .. versionadded:: 0.1 country = CountryField() #: A free form "city" or "region" field used to display where #: exactly the society is within a country #: .. versionadded:: 0.1 region = models.CharField(max_length=512, null=True, default=None, blank=True) def __str__(self): return 'GuitarSociety(name="{}", link="{}")'.format(self.name, self.link)
Change the usage sentence to be EN
import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.Job; public class WordCountDriver { public static void main(String[] args) throws Exception { if (args.length != 2) { System.out.printf("Usage : WordCountDriver <inputdir> <outputdir>\n"); System.exit(-1); } Job job = new Job(); job.setJarByClass(WordCountDriver.class); job.setJobName("Word Count"); FileInputFormat.setInputPaths(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); job.setMapperClass(WordCountMapper.class); job.setReducerClass(WordCountReducer.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(IntWritable.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); boolean success = job.waitForCompletion(true); System.exit(success ? 0 : 1); } }
import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.Job; public class WordCountDriver { public static void main(String[] args) throws Exception { if (args.length != 2) { System.out.printf("Format de la ligne de commande : WordCount <input dir> <outputdir>\n"); System.exit(-1); } Job job = new Job(); job.setJarByClass(WordCountDriver.class); job.setJobName("Word Count"); FileInputFormat.setInputPaths(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); job.setMapperClass(WordCountMapper.class); job.setReducerClass(WordCountReducer.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(IntWritable.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); boolean success = job.waitForCompletion(true); System.exit(success ? 0 : 1); } }
Create zookeeper node if it doesn't exist
# Polls Adzerk for current list of flights and saves the current targeting # information to zookeeper (to be run periodically with upstart) import adzerk_api import json from pylons import app_globals as g KEYWORD_NODE = "/keyword-targets" def update_global_keywords(): active_flights = adzerk_api.Flight.list(is_active=True) keyword_target = set() # Count the number of flights targeting each sub/keyword for flight in active_flights: for keyword_list in flight.Keywords.split('\n'): for keyword in keyword_list.split(','): ks = keyword.strip() if ks.startswith('k.') or ks.startswith('!k.'): keyword_target.add(ks) # Store results in zookeeper if g.zookeeper: g.zookeeper.ensure_path(KEYWORD_NODE) g.zookeeper.set(KEYWORD_NODE, json.dumps(list(keyword_target)))
# Polls Adzerk for current list of flights and saves the current targeting # information to zookeeper (to be run periodically with upstart) import adzerk_api import json from pylons import app_globals as g def update_global_keywords(): active_flights = adzerk_api.Flight.list(is_active=True) keyword_target = set() # Count the number of flights targeting each sub/keyword for flight in active_flights: for keyword_list in flight.Keywords.split('\n'): for keyword in keyword_list.split(','): ks = keyword.strip() if ks.startswith('k.') or ks.startswith('!k.'): keyword_target.add(ks) # Store results in zookeeper if g.zookeeper: g.zookeeper.set("/keyword-targets", json.dumps(list(keyword_target)))
Change NATS desire app message format. Signed-off-by: Momchil Atanasov <32dfc64aa82b4a16510185529922b8f0a0c3fedb@gmail.com>
package models import "encoding/json" type DesireAppRequestFromCC struct { ProcessGuid string `json:"process_guid"` DropletUri string `json:"droplet_uri"` Stack string `json:"stack"` StartCommand string `json:"start_command"` Environment []EnvironmentVariable `json:"environment"` MemoryMB int `json:"memory_mb"` DiskMB int `json:"disk_mb"` FileDescriptors uint64 `json:"file_descriptors"` NumInstances int `json:"num_instances"` Routes []string `json:"routes"` LogGuid string `json:"log_guid"` } func (d DesireAppRequestFromCC) ToJSON() []byte { encoded, _ := json.Marshal(d) return encoded }
package models import "encoding/json" type DesireAppRequestFromCC struct { AppId string `json:"app_id"` AppVersion string `json:"app_version"` DropletUri string `json:"droplet_uri"` Stack string `json:"stack"` StartCommand string `json:"start_command"` Environment []EnvironmentVariable `json:"environment"` MemoryMB int `json:"memory_mb"` DiskMB int `json:"disk_mb"` FileDescriptors uint64 `json:"file_descriptors"` NumInstances int `json:"num_instances"` Routes []string `json:"routes"` } func (d DesireAppRequestFromCC) ToJSON() []byte { encoded, _ := json.Marshal(d) return encoded }
Remove unused variable within component presenter
<?php /* * This file is part of Cachet. * * (c) Alt Three Services Limited * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace CachetHQ\Cachet\Presenters; use CachetHQ\Cachet\Presenters\Traits\TimestampsTrait; class ComponentPresenter extends AbstractPresenter { use TimestampsTrait; /** * Returns the override class name for theming. * * @return string */ public function status_color() { switch ($this->wrappedObject->status) { case 1: return 'greens'; case 2: return 'blues'; case 3: return 'yellows'; case 4: return 'reds'; } } /** * Convert the presenter instance to an array. * * @return string[] */ public function toArray() { return array_merge($this->wrappedObject->toArray(), [ 'created_at' => $this->created_at(), 'updated_at' => $this->updated_at(), 'status_name' => $this->wrappedObject->humanStatus, ]); } }
<?php /* * This file is part of Cachet. * * (c) Alt Three Services Limited * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace CachetHQ\Cachet\Presenters; use CachetHQ\Cachet\Presenters\Traits\TimestampsTrait; class ComponentPresenter extends AbstractPresenter { use TimestampsTrait; /** * Returns the override class name for theming. * * @return string */ public function status_color() { $newStatus = ''; switch ($this->wrappedObject->status) { case 1: return 'greens'; case 2: return 'blues'; case 3: return 'yellows'; case 4: return 'reds'; } } /** * Convert the presenter instance to an array. * * @return string[] */ public function toArray() { return array_merge($this->wrappedObject->toArray(), [ 'created_at' => $this->created_at(), 'updated_at' => $this->updated_at(), 'status_name' => $this->wrappedObject->humanStatus, ]); } }
Handle only /client requests to file serving.
import SimpleHTTPServer import SocketServer class KcaaHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): CLIENT_PREFIX = '/client/' def do_HEAD(self): # Note: HTTP request handlers are not new-style classes. # super() cannot be used. if self.rewrite_to_client_path(): SimpleHTTPServer.SimpleHTTPRequestHandler.do_HEAD(self) def do_GET(self): if self.rewrite_to_client_path(): SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self) def rewrite_to_client_path(self): if self.path.startswith(KcaaHTTPRequestHandler.CLIENT_PREFIX): self.path = '/' + self.path[len( KcaaHTTPRequestHandler.CLIENT_PREFIX):] return True else: return False def setup(args): httpd = SocketServer.TCPServer(('', args.server_port), KcaaHTTPRequestHandler) _, port = httpd.server_address root_url = 'http://127.0.0.1:{}/client/'.format(port) print 'KCAA server ready at {}'.format(root_url) return httpd, root_url
import SimpleHTTPServer import SocketServer class KcaaHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def do_HEAD(self): # Note: HTTP request handlers are not new-style classes. # super() cannot be used. SimpleHTTPServer.SimpleHTTPRequestHandler.do_HEAD(self) def do_GET(self): SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self) def setup(args): httpd = SocketServer.TCPServer(('', args.server_port), KcaaHTTPRequestHandler) _, port = httpd.server_address root_url = 'http://127.0.0.1:{}/web/'.format(port) print 'KCAA server ready at {}'.format(root_url) return httpd, root_url
Add deps for Amazon API and XML handling
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='django-fancypages', version=":versiontools:oscar_mws:", url='https://github.com/tangentlabs/django-oscar-mws', author="Sebastian Vetter", author_email="sebastian.vetter@tangentsnowball.com.au", description="Integrating Oscar with Amazon MWS", long_description='\n\n'.join([ open('README.rst').read(), open('CHANGELOG.rst').read(), ]), keywords="django, Oscar, django-oscar, Amazon, MWS, fulfilment", license='BSD', platforms=['linux'], packages=find_packages(exclude=["sandbox*", "tests*"]), include_package_data=True, install_requires=[ 'django-oscar>=0.5', 'boto>=2.10.0', 'lxml>=3.2.3', ], setup_requires=[ 'versiontools>=1.8', ], # See http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: Unix', 'Programming Language :: Python', ] )
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='django-fancypages', version=":versiontools:oscar_mws:", url='https://github.com/tangentlabs/django-oscar-mws', author="Sebastian Vetter", author_email="sebastian.vetter@tangentsnowball.com.au", description="Integrating Oscar with Amazon MWS", long_description='\n\n'.join([ open('README.rst').read(), open('CHANGELOG.rst').read(), ]), keywords="django, Oscar, django-oscar, Amazon, MWS, fulfilment", license='BSD', platforms=['linux'], packages=find_packages(exclude=["sandbox*", "tests*"]), include_package_data=True, install_requires=[ 'django-oscar>=0.5', ], setup_requires=[ 'versiontools >= 1.8', ], # See http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: Unix', 'Programming Language :: Python', ] )
Use supernet interface for building the appropriate network.
from .. import INETOID, CIDROID, MACADDROID from . import lib try: import ipaddress except ImportError: import ipaddr as ipaddress oid_to_type = { MACADDROID : str, INETOID: ipaddress._IPAddressBase, CIDROID: ipaddress._BaseNetwork, } def inet_pack(ob, pack = lib.net_pack, Constructor = ipaddress.ip_address): a = Constructor(ob) return pack((a.version, None, a.packed)) def cidr_pack(ob, pack = lib.net_pack, Constructor = ipaddress.ip_network): a = Constructor(ob) return pack((a.version, a.prefixlen, a.network_address.packed)) def inet_unpack(data, unpack = lib.net_unpack, Constructor = ipaddress.ip_address): version, mask, data = unpack(data) return Constructor(data) def cidr_unpack(data, unpack = lib.net_unpack, Constructor = ipaddress.ip_network): version, mask, data = unpack(data) return Constructor(data).supernet(new_prefix=mask) oid_to_io = { MACADDROID : (lib.macaddr_pack, lib.macaddr_unpack, str), CIDROID : (cidr_pack, cidr_unpack, str), INETOID : (inet_pack, inet_unpack, str), }
from .. import INETOID, CIDROID, MACADDROID from . import lib try: import ipaddress except ImportError: import ipaddr as ipaddress oid_to_type = { MACADDROID : str, INETOID: ipaddress._IPAddressBase, CIDROID: ipaddress._BaseNetwork, } def inet_pack(ob, pack = lib.net_pack, Constructor = ipaddress.ip_address): a = Constructor(ob) return pack((a.version, None, a.packed)) def cidr_pack(ob, pack = lib.net_pack, Constructor = ipaddress.ip_network): a = Constructor(ob) return pack((a.version, a.prefixlen, a.network_address.packed)) def inet_unpack(data, unpack = lib.net_unpack, Constructor = ipaddress.ip_address): version, mask, data = unpack(data) return Constructor(data) def cidr_unpack(data, unpack = lib.net_unpack, Constructor = ipaddress.ip_network): version, mask, data = unpack(data) r = Constructor(data) r._prefixlen = mask return Constructor(str(r)) oid_to_io = { MACADDROID : (lib.macaddr_pack, lib.macaddr_unpack, str), CIDROID : (cidr_pack, cidr_unpack, str), INETOID : (inet_pack, inet_unpack, str), }
Revert "Use data attribute instead of val()" This reverts commit 680debc53973355b553155bdfae857907af0a259. Ref #471
var EDSN_THRESHOLD = 30; var EdsnSwitch = (function(){ var editing; var validBaseLoads = /^(base_load|base_load_edsn)$/; EdsnSwitch.prototype = { enable: function(){ if(editing){ swapEdsnBaseLoadSelectBoxes(); } }, isEdsn: function(){ return validBaseLoads.test($(this).val()); }, cloneAndAppendProfileSelect: function(){ swapSelectBox.call(this); } }; function swapEdsnBaseLoadSelectBoxes(){ $("tr.base_load_edsn select.name").each(swapSelectBox); }; function swapSelectBox(){ var technology = $(this).val(); var self = this; var unitSelector = $(this).parents("tr").find(".units input"); var units = parseInt(unitSelector.val()); var actual = (units > EDSN_THRESHOLD ? "base_load_edsn" : "base_load"); var select = $(".hidden select." + actual).clone(true, true); $(this).parent().next().html(select); $(this).find("option[value='" + technology + "']").attr('value', actual); unitSelector.off('change').on('change', swapSelectBox.bind(self)); }; function EdsnSwitch(_editing){ editing = _editing; }; return EdsnSwitch; })();
var EDSN_THRESHOLD = 30; var EdsnSwitch = (function(){ var editing; var validBaseLoads = /^(base_load|base_load_edsn)$/; EdsnSwitch.prototype = { enable: function(){ if(editing){ swapEdsnBaseLoadSelectBoxes(); } }, isEdsn: function(){ return validBaseLoads.test($(this).data('type')); }, cloneAndAppendProfileSelect: function(){ swapSelectBox.call(this); } }; function swapEdsnBaseLoadSelectBoxes(){ $("tr.base_load_edsn select.name").each(swapSelectBox); }; function swapSelectBox(){ var technology = $(this).val(); var self = this; var unitSelector = $(this).parents("tr").find(".units input"); var units = parseInt(unitSelector.val()); var actual = (units > EDSN_THRESHOLD ? "base_load_edsn" : "base_load"); var select = $(".hidden select." + actual).clone(true, true); $(this).parent().next().html(select); $(this).find("option[value='" + technology + "']").attr('value', actual); unitSelector.off('change').on('change', swapSelectBox.bind(self)); }; function EdsnSwitch(_editing){ editing = _editing; }; return EdsnSwitch; })();
win: Update libchromiumcontent to fix shared workers.
#!/usr/bin/env python import platform import sys NODE_VERSION = 'v0.11.13' BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = '99d263cbd842ba57331ddb975aad742470a4cff4' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }[sys.platform] DIST_ARCH = { '32bit': 'ia32', '64bit': 'x64', }[ARCH] TARGET_PLATFORM = { 'cygwin': 'win32', 'darwin': 'darwin', 'linux2': 'linux', 'win32': 'win32', }[sys.platform]
#!/usr/bin/env python import platform import sys NODE_VERSION = 'v0.11.13' BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = '5d5539f8232bb4d0253438216de11a99159b3c4d' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }[sys.platform] DIST_ARCH = { '32bit': 'ia32', '64bit': 'x64', }[ARCH] TARGET_PLATFORM = { 'cygwin': 'win32', 'darwin': 'darwin', 'linux2': 'linux', 'win32': 'win32', }[sys.platform]
Return username after credential reset
/* * Copyright 2021 Wultra 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 io.getlime.security.powerauth.lib.nextstep.model.response; import io.getlime.security.powerauth.lib.nextstep.model.entity.enumeration.CredentialStatus; import lombok.Data; import javax.validation.constraints.NotNull; /** * Response object used for resetting a credential. * * @author Roman Strobl, roman.strobl@wultra.com */ @Data public class ResetCredentialResponse { @NotNull private String userId; @NotNull private String credentialName; private String username; @NotNull private String credentialValue; @NotNull private CredentialStatus credentialStatus; }
/* * Copyright 2021 Wultra 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 io.getlime.security.powerauth.lib.nextstep.model.response; import io.getlime.security.powerauth.lib.nextstep.model.entity.enumeration.CredentialStatus; import lombok.Data; import javax.validation.constraints.NotNull; /** * Response object used for resetting a credential. * * @author Roman Strobl, roman.strobl@wultra.com */ @Data public class ResetCredentialResponse { @NotNull private String userId; @NotNull private String credentialName; @NotNull private String credentialValue; @NotNull private CredentialStatus credentialStatus; }
Use id instead of name
"""Tests for plugin.py.""" import pytest from ckan.tests import factories import ckan.tests.helpers as helpers from ckan.plugins.toolkit import NotAuthorized @pytest.mark.ckan_config('ckan.plugins', 'apicatalog_routes') @pytest.mark.usefixtures('clean_db', 'with_plugins', 'with_request_context') class TestApicatalogRoutes(object): def test_non_sysadmins_should_not_be_able_to_delete_subsystems(self): user = factories.User() org_users = [{"name": user["name"], "capacity": "admin"}] org = factories.Organization(users=org_users) subsystem = factories.Dataset( owner_org=org["id"] ) context = {'ignore_auth': False, 'user': user['name']} with pytest.raises(NotAuthorized): helpers.call_action('package_delete', context, id=subsystem['name'])
"""Tests for plugin.py.""" import pytest from ckan.tests import factories import ckan.tests.helpers as helpers from ckan.plugins.toolkit import NotAuthorized @pytest.mark.ckan_config('ckan.plugins', 'apicatalog_routes') @pytest.mark.usefixtures('clean_db', 'with_plugins', 'with_request_context') class TestApicatalogRoutes(object): def test_non_sysadmins_should_not_be_able_to_delete_subsystems(self): user = factories.User() org_users = [{"name": user["name"], "capacity": "admin"}] org = factories.Organization(users=org_users) subsystem = factories.Dataset( owner_org=org["id"] ) context = {'ignore_auth': False, 'user': user['name']} with pytest.raises(NotAuthorized): helpers.call_action('package_delete', context, name=subsystem['name'])
Document the view classes and make fix their spacing for pep8.
from shop.views import ShopListView, ShopDetailView from shop_richcatalog.models import Catalog from shop.models import Product class CatalogListView(ShopListView): ''' Display all catalogs in a tree. ''' model = Catalog class CatalogDetailView(ShopDetailView): ''' Display detailed catalog information. ''' model = Catalog def get_context_data(self, **kwargs): ''' Get catalog context data. ''' # get context data from superclass ctx = super(CatalogDetailView, self).get_context_data(**kwargs) # update the context with active products in this catalog product_list = self.object.products.filter(active=True) if product_list: ctx.update({"product_list": product_list}) # return the context return ctx
from shop.views import ShopListView, ShopDetailView from shop_richcatalog.models import Catalog from shop.models import Product class CatalogListView(ShopListView): ''' TODO. ''' model = Catalog #generic_template = "shop_richcatalog/catalog_list.html" class CatalogDetailView(ShopDetailView): ''' TODO. ''' model = Catalog #generic_template = "shop_richcatalog/catalog_detail.html" def get_context_data(self, **kwargs): ''' TODO. ''' # get context data from superclass ctx = super(CatalogDetailView, self).get_context_data(**kwargs) # update the context with active products in this catalog product_list = self.object.products.filter(active=True) if product_list: ctx.update({"product_list": product_list}) # return the context return ctx
Fix bug in IE9 when observed elements are removed from the DOM
// jquery.observe_field.js (function( $ ){ jQuery.fn.observe_field = function(frequency, callback) { frequency = frequency * 1000; // translate to milliseconds return this.each(function(){ var $this = $(this); var prev = $this.val(); var check = function() { if(removed()){ // if removed clear the interval and don't fire the callback if(ti) clearInterval(ti); return; } var val = $this.val(); if(prev != val){ prev = val; $this.map(callback); // invokes the callback on $this } }; var removed = function() { return $this.closest('html').length == 0 }; var reset = function() { if(ti){ clearInterval(ti); ti = setInterval(check, frequency); } }; check(); var ti = setInterval(check, frequency); // invoke check periodically // reset counter after user interaction $this.bind('keyup click mousemove', reset); //mousemove is for selects }); }; })( jQuery );
// jquery.observe_field.js (function( $ ){ jQuery.fn.observe_field = function(frequency, callback) { frequency = frequency * 1000; // translate to milliseconds return this.each(function(){ var $this = $(this); var prev = $this.val(); var check = function() { var val = $this.val(); if(prev != val){ prev = val; $this.map(callback); // invokes the callback on $this } }; var reset = function() { if(ti){ clearInterval(ti); ti = setInterval(check, frequency); } }; check(); var ti = setInterval(check, frequency); // invoke check periodically // reset counter after user interaction $this.bind('keyup click mousemove', reset); //mousemove is for selects }); }; })( jQuery );
Fix display name of Suspense
import { Component } from './component'; import { createElement } from './create-element'; // having a "custom class" here saves 50bytes gzipped export function Suspense(props) {} Suspense.prototype = new Component(); /** * @param {Promise} promise The thrown promise */ Suspense.prototype._childDidSuspend = function(promise) { this.setState({ _loading: true }); const cb = () => { this.setState({ _loading: false }); }; // Suspense ignores errors thrown in Promises as this should be handled by user land code promise.then(cb, cb); }; Suspense.prototype.render = function(props, state) { return state._loading ? props.fallback : props.children; }; export function lazy(loader) { let prom; let component; let error; function Lazy(props) { if (!prom) { prom = loader(); prom.then( (exports) => { component = exports.default; Lazy.displayName = 'Lazy(' + (component.displayName || component.name) + ')'; }, (e) => { error = e; }, ); } if (error) { throw error; } if (!component) { throw prom; } return createElement(component, props); } return Lazy; }
import { Component } from './component'; import { createElement } from './create-element'; // having a "custom class" here saves 50bytes gzipped export function s(props) {} s.prototype = new Component(); /** * @param {Promise} promise The thrown promise */ s.prototype._childDidSuspend = function(promise) { this.setState({ _loading: true }); const cb = () => { this.setState({ _loading: false }); }; // Suspense ignores errors thrown in Promises as this should be handled by user land code promise.then(cb, cb); }; s.prototype.render = function(props, state) { return state._loading ? props.fallback : props.children; }; // exporting s as Suspense instead of naming the class iself Suspense saves 4 bytes gzipped // TODO: does this add the need of a displayName? export const Suspense = s; export function lazy(loader) { let prom; let component; let error; function Lazy(props) { if (!prom) { prom = loader(); prom.then( (exports) => { component = exports.default; Lazy.displayName = 'Lazy(' + (component.displayName || component.name) + ')'; }, (e) => { error = e; }, ); } if (error) { throw error; } if (!component) { throw prom; } return createElement(component, props); } return Lazy; }
Add new constants that are used throughout servlets.
// Copyright 2019 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 com.google.sps.servlets; public final class BlogConstants { public static String MESSAGE_PARAMETER = "text-input"; public static String SENDER_PARAMETER = "sender"; public static String TAG_PARAMETER = "tags"; public static String PARENTID_PARAMETER = "parentID"; public static String BLOG_ENTITY_KIND = "blogMessage"; public static String ID_PARAMETER = "messageId"; public static String TAG_QUERY = "followedTag"; public static String NICKNAME = "nickname"; public static String BLOG_USER = "BlogUser"; public static String ID = "id"; public static String EMAIL = "email"; public static String TIME = "time"; }
// Copyright 2019 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 com.google.sps.servlets; public final class BlogConstants { public static String MESSAGE_PARAMETER = "text-input"; public static String SENDER_PARAMETER = "sender"; public static String TAG_PARAMETER = "tags"; public static String PARENTID_PARAMETER = "parentID"; public static String BLOG_ENTITY_KIND = "blogMessage"; public static String ID_PARAMETER = "messageId"; public static String TAG_QUERY = "followedTag"; public static String NICKNAME = "nickname"; }
Make message id a string
import faker from'faker'; function createMessage(id) { return { id: id.toString(), message: faker.company.catchPhrase(), updated: false, }; } const messages = []; for (let i = 0; i < 10; i++) { messages.push(createMessage(i)); } export default { get() { return messages }, add() { const message = createMessage(messages.length); messages.push(message); return message; }, toggle(messageId) { const toggled = messages[messageId]; toggled.updated = !toggled.updated; messages[messageId] = toggled; return toggled; } }
import faker from'faker'; const messages = []; function createMessage(id) { return { id, message: faker.company.catchPhrase(), updated: false, }; } for (let i = 0; i < 10; i++) { messages.push(createMessage(i)); } export default { get() { return messages }, add() { const message = createMessage(messages.length); messages.push(message); return message; }, toggle(messageId) { const toggled = messages[messageId]; toggled.updated = !toggled.updated; messages[messageId] = toggled; return toggled; } }
Manage case where api installed with --editable
# -*- coding: utf-8 -*- import os import sys from logging.config import fileConfig from wsgiref.simple_server import make_server from paste.deploy import loadapp hostname = 'localhost' port = 2000 def main(): conf_file_path = os.path.join(sys.prefix, 'share', 'openfisca', 'openfisca-web-api', 'development-france.ini') # If openfisca_web_api has been installed with --editable if not os.path.isfile(conf_file_path): import pkg_resources api_sources_path = pkg_resources.get_distribution("openfisca_web_api").location conf_file_path = os.path.join(api_sources_path, 'development-france.ini') fileConfig(conf_file_path) application = loadapp('config:{}'.format(conf_file_path)) httpd = make_server(hostname, port, application) print u'Serving on http://{}:{}/'.format(hostname, port) try: httpd.serve_forever() except KeyboardInterrupt: return if __name__ == '__main__': sys.exit(main())
# -*- coding: utf-8 -*- import os import sys from logging.config import fileConfig from wsgiref.simple_server import make_server from paste.deploy import loadapp hostname = 'localhost' port = 2000 def main(): conf_file_path = os.path.join(sys.prefix, 'share', 'openfisca', 'openfisca-web-api', 'development-france.ini') fileConfig(conf_file_path) application = loadapp('config:{}'.format(conf_file_path)) httpd = make_server(hostname, port, application) print u'Serving on http://{}:{}/'.format(hostname, port) try: httpd.serve_forever() except KeyboardInterrupt: return if __name__ == '__main__': sys.exit(main())
Remove needless `.type = 'text/javascript'` See <https://mathiasbynens.be/notes/async-analytics-snippet#type>.
document.addEventListener('DOMContentLoaded', function(){ var str = "var st = document.createElement('script'); st.src = '"+chrome.extension.getURL('node_modules/traceur/bin/traceur-runtime.js')+"'; (document.head||document.documentElement).appendChild(st);" chrome.devtools.inspectedWindow.eval(str) var editor = CodeMirror.fromTextArea(document.querySelector("textarea"), { lineNumbers: true, matchBrackets: true, continueComments: "Enter", extraKeys: {"Ctrl-Q": "toggleComment"}, tabSize: 2, autoCloseBrackets: true }); editor.setSize(window.innerWidth-20, window.innerHeight - 20); editor.setOption('theme', 'solarized dark'); var deliverContent = function(content){ traceur.options.experimental = true; try { var es5 = traceur.Compiler.script(content); chrome.devtools.inspectedWindow.eval(es5) } catch (e) { chrome.devtools.inspectedWindow.eval("console.error(\"" + e + "\");"); } } document.onkeydown = function(e){ if(e.metaKey && e.which == 13){ deliverContent(editor.getValue()); } } document.querySelector('button').addEventListener('click', function(){ deliverContent(editor.getValue()); }); });
document.addEventListener('DOMContentLoaded', function(){ var str = "var st = document.createElement('script'); st.type = 'text/javascript'; st.src = '"+chrome.extension.getURL('node_modules/traceur/bin/traceur-runtime.js')+"'; (document.head||document.documentElement).appendChild(st);" chrome.devtools.inspectedWindow.eval(str) var editor = CodeMirror.fromTextArea(document.querySelector("textarea"), { lineNumbers: true, matchBrackets: true, continueComments: "Enter", extraKeys: {"Ctrl-Q": "toggleComment"}, tabSize: 2, autoCloseBrackets: true }); editor.setSize(window.innerWidth-20, window.innerHeight - 20); editor.setOption('theme', 'solarized dark'); var deliverContent = function(content){ traceur.options.experimental = true; try { var es5 = traceur.Compiler.script(content); chrome.devtools.inspectedWindow.eval(es5) } catch (e) { chrome.devtools.inspectedWindow.eval("console.error(\"" + e + "\");"); } } document.onkeydown = function(e){ if(e.metaKey && e.which == 13){ deliverContent(editor.getValue()); } } document.querySelector('button').addEventListener('click', function(){ deliverContent(editor.getValue()); }); });
Fix the same bug for release templates
'use strict'; const { get } = require('lodash') ; const ERROR_TEMPLATES = require('./errors'); const releaseMsg = require('./release'); module.exports = (config) => { return (releaseInfo, filterLabels) => { const user = get(config, 'github.user'); const githubToSlakUsernames = get(config, 'slack.githubUsers'); // TODO: add a config setting to notify only if there are filterred issues const attachments = releaseInfo.reduce((acc, repoInfo) => { if (isFailedReleaseAndFilteredChannel(repoInfo.failReason, filterLabels)) return acc; const attachment = repoInfo.failReason ? ERROR_TEMPLATES[repoInfo.failReason] || ERROR_TEMPLATES.UNkNOWN_ERROR : releaseMsg(repoInfo, filterLabels, user, githubToSlakUsernames); if (attachment) { acc.push(Object.assign({}, attachment, { title: repoInfo.repo, title_link: `https://github.com/${user}/${repoInfo.repo}` })); } return acc; }, []); if (attachments.length > 0) { return { attachments }; } }; function isFailedReleaseAndFilteredChannel(failReason, filterLabels) { return failReason && filterLabels && filterLabels.length > 0; } };
'use strict'; const { get } = require('lodash') ; const ERROR_TEMPLATES = require('./errors'); const releaseMsg = require('./release'); module.exports = (config) => { return (releaseInfo, filterLabels) => { const user = get(config, 'github.user'); const githubToSlakUsernames = get(config, 'slack.githubUsers'); // TODO: add a config setting to notify only if there are filterred issues const attachments = releaseInfo.reduce((acc, repoInfo) => { if (isFailedReleaseAndFilteredChannel(repoInfo.failReason, filterLabels)) return acc; const attachment = repoInfo.failReason ? ERROR_TEMPLATES[repoInfo.failReason] || ERROR_TEMPLATES.UNkNOWN_ERROR : releaseMsg(repoInfo, filterLabels, user, githubToSlakUsernames); if (attachment) { attachment.title = repoInfo.repo; attachment.title_link = `https://github.com/${user}/${repoInfo.repo}`; acc.push(attachment); } return acc; }, []); if (attachments.length > 0) { return { attachments }; } }; function isFailedReleaseAndFilteredChannel(failReason, filterLabels) { return failReason && filterLabels && filterLabels.length > 0; } };
fix: Handle the default pattern with the last state when the command is not mathcing.
/* * redbloom * Copyright(c) 2016 Benjamin Bartolome * Apache 2.0 Licensed */ 'use strict'; module.exports = redbloom; var ee = require('event-emitter'); var Immutable = require('immutable'); var Rx = require('rx'); function redbloom(initialState, options) { var state = Immutable.Map(initialState || {}); // eslint-disable-line new-cap var instance = ee({}); var bloomrun = require('bloomrun')(options); bloomrun.default((action, currentState) => { return currentState; }); var observable = Rx.Observable .fromEvent(instance, 'dispatch') .concatMap(action => { var listActions = () => { var listActions = bloomrun.list(action); if (listActions.length == 0) { listActions.push(bloomrun.lookup(action)) } return listActions; } return Rx.Observable .from(listActions()) .map(reducer => reducer.bind(observable, action)); }) .scan((currentState, reducer) => { return reducer(currentState); }, state); observable.handle = (action, reducer) => bloomrun.add(action, reducer); observable.dispatch = action => instance.emit('dispatch', action); return observable; }
/* * redbloom * Copyright(c) 2016 Benjamin Bartolome * Apache 2.0 Licensed */ 'use strict'; module.exports = redbloom; var ee = require('event-emitter'); var Immutable = require('immutable'); var Rx = require('rx'); function redbloom(initialState, options) { var state = Immutable.Map(initialState || {}); // eslint-disable-line new-cap var instance = ee({}); var bloomrun = require('bloomrun')(options); bloomrun.default((action, currentState) => { return currentState; }); var observable = Rx.Observable .fromEvent(instance, 'dispatch') .concatMap(action => { var listActions = () => { var listActions = bloomrun.list(action); if (listActions.length == 0) { listActions.push(bloomrun.lookup(action)) } return listActions; } return Rx.Observable .from(listActions()) .map(reducer => reducer.bind(observable, action)); }) .scan((currentState, reducer) => reducer(currentState), state); observable.handle = (action, reducer) => bloomrun.add(action, reducer); observable.dispatch = action => instance.emit('dispatch', action); return observable; }
Convert to unchecked exception hierarchy
/* * Copyright 2014 Texas A&M Engineering Experiment Station * * 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 edu.tamu.tcat.account; /** * A base exception type for the Account library. */ public class AccountException extends RuntimeException { public AccountException() { } public AccountException(String message) { super(message); } public AccountException(Throwable cause) { super(cause); } public AccountException(String message, Throwable cause) { super(message, cause); } public AccountException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
/* * Copyright 2014 Texas A&M Engineering Experiment Station * * 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 edu.tamu.tcat.account; /** * A base exception type for the Account library. */ public class AccountException extends Exception { public AccountException() { } public AccountException(String message) { super(message); } public AccountException(Throwable cause) { super(cause); } public AccountException(String message, Throwable cause) { super(message, cause); } public AccountException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
[trunk] Convert line endings on Objective C/C++ test source too
#!/usr/bin/python import os import sys def convert_line_endings(file): if '\r\n' in open(file, 'rb').read(): print '%s contains DOS line endings. Converting' % file with open(file, 'rb') as infile: text = infile.read() text = text.replace('\r\n', '\n') with open(file, 'wb') as outfile: outfile.write(text) def processPath(dirPath, ext): for dirpath, dirnames, filenames in os.walk(dirPath): for file in filenames: if os.path.splitext(file)[1] == ext: csPath = os.path.join(dirpath, file) convert_line_endings(csPath) if __name__ == "__main__": if len(sys.argv) > 1: convert_line_endings(sys.argv[1]) else: processPath('.', '.cs') processPath('testpackages', '.h') processPath('testpackages', '.c') processPath('testpackages', '.cpp') processPath('testpackages', '.m') processPath('testpackages', '.mm')
#!/usr/bin/python import os import sys def convert_line_endings(file): if '\r\n' in open(file, 'rb').read(): print '%s contains DOS line endings. Converting' % file with open(file, 'rb') as infile: text = infile.read() text = text.replace('\r\n', '\n') with open(file, 'wb') as outfile: outfile.write(text) def processPath(dirPath, ext): for dirpath, dirnames, filenames in os.walk(dirPath): for file in filenames: if os.path.splitext(file)[1] == ext: csPath = os.path.join(dirpath, file) convert_line_endings(csPath) if __name__ == "__main__": if len(sys.argv) > 1: convert_line_endings(sys.argv[1]) else: processPath('.', '.cs') processPath('testpackages', '.h') processPath('testpackages', '.c') processPath('testpackages', '.cpp')
Remove local information from test settings
/* * grunt-restful * https://github.com/DaneStuckel/grunt-restful * * Copyright (c) 2013 Dane Stuckel * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Project configuration. grunt.initConfig({ // Configuration to be run (and then tested). 'restful': { options: { } } }); // Actually load this plugin's task(s). grunt.loadTasks('tasks'); // These plugins provide necessary tasks. grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-clean'); // Whenever the "test" task is run, first clean the "tmp" dir, then run this // plugin's task(s), then test the result. grunt.registerTask('test', ['restful']); // By default, lint and run all tests. grunt.registerTask('default', ['test']); };
/* * grunt-restful * https://github.com/DaneStuckel/grunt-restful * * Copyright (c) 2013 Dane Stuckel * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Project configuration. grunt.initConfig({ // Configuration to be run (and then tested). 'restful': { options: { uri: 'https://mingle.eng.shaw.ca/api/v2/projects/project_1_4_guide_program/cards/8756.xml', secure: false } } }); // Actually load this plugin's task(s). grunt.loadTasks('tasks'); // These plugins provide necessary tasks. grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-clean'); // Whenever the "test" task is run, first clean the "tmp" dir, then run this // plugin's task(s), then test the result. grunt.registerTask('test', ['restful']); // By default, lint and run all tests. grunt.registerTask('default', ['test']); };
Use formatted flag on astyle to simplify code
# -*- coding: utf-8 -*- """astyle plugin for zazu""" import zazu.styler import zazu.util __author__ = "Nicholas Wiles" __copyright__ = "Copyright 2017" class AstyleStyler(zazu.styler.Styler): """Astyle plugin for code styling""" def style_file(self, file, verbose, dry_run): """Run astyle on a file""" args = ['astyle', '--formatted'] + self.options if dry_run: args.append('--dry-run') args.append(file) output = zazu.util.check_output(args) return file, bool(output) @staticmethod def default_extensions(): return ['*.c', '*.cc', '*.cpp', '*.h', '*.hpp', '*.java'] @staticmethod def type(): return 'astyle'
# -*- coding: utf-8 -*- """astyle plugin for zazu""" import zazu.styler import zazu.util __author__ = "Nicholas Wiles" __copyright__ = "Copyright 2017" class AstyleStyler(zazu.styler.Styler): """Astyle plugin for code styling""" def style_file(self, file, verbose, dry_run): """Run astyle on a file""" args = ['astyle', '-v'] + self.options if dry_run: args.append('--dry-run') args.append(file) output = zazu.util.check_output(args) fix_needed = output.startswith('Formatted ') return file, fix_needed @staticmethod def default_extensions(): return ['*.c', '*.cc', '*.cpp', '*.h', '*.hpp', '*.java'] @staticmethod def type(): return 'astyle'
Fix test caused by htmlmin
angular.module('custom_prefix').run(['$templateCache', function($templateCache) { $templateCache.put('/static/test/fixtures/one.html', "<h1>One</h1>\n" + "\n" + "<p class=\"\">I am one.</p>\n" + "\n" + "<script type=\"text/javascript\">\n" + " // Test\n" + " /* comments */\n" + " var foo = 'bar';\n" + "</script>\n" ); $templateCache.put('/static/test/fixtures/two/two.html', "<h2>Two</h2>\n" + "\n" + "<!-- Comment for two -->\n" + "\n" + "<textarea readonly=\"readonly\">We are two.</textarea>\n" ); }]);
angular.module('custom_prefix').run(['$templateCache', function($templateCache) { $templateCache.put('/static/test/fixtures/one.html', "<h1>One</h1>\n" + "\n" + "<p class=\"\">I am one.</p>\n" + "\n" + "<script type=\"text/javascript\">\n" + " // Test\n" + " /* comments */\n" + " var foo = 'bar';\n" + "</script>" ); $templateCache.put('/static/test/fixtures/two/two.html', "<h2>Two</h2>\n" + "\n" + "<!-- Comment for two -->\n" + "\n" + "<textarea readonly=\"readonly\">We are two.</textarea>" ); }]);
Exclude .DS_Store from package build.
#!/usr/bin/env python from setuptools import setup def readme(): with open('README.rst') as f: return f.read() setup( name='pneumatic', version='0.1.8', description='A bulk upload library for DocumentCloud.', long_description=readme(), classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', ], url='http://pneumatic.readthedocs.io/en/latest/', author='Anthony DeBarros', author_email='practicalsqlbook@gmail.com', license='MIT', packages=['pneumatic'], install_requires=[ 'requests', 'colorama' ], exclude_package_data={'': ['.DS_Store']}, zip_safe=False )
#!/usr/bin/env python from setuptools import setup def readme(): with open('README.rst') as f: return f.read() setup( name='pneumatic', version='0.1.8', description='A bulk upload library for DocumentCloud.', long_description=readme(), classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', ], url='http://pneumatic.readthedocs.io/en/latest/', author='Anthony DeBarros', author_email='practicalsqlbook@gmail.com', license='MIT', packages=['pneumatic'], install_requires=[ 'requests', 'colorama' ], zip_safe=False )
EventPage.js: Change id for email in getProfileUserInfo function
chrome.runtime.onMessage.addListener( function(echo, sender, sendResponse) { var promise = new Promise(function(resolve, reject) { chrome.identity.getProfileUserInfo(function(userInfo) { echo['google_credentials'] = userInfo.email; }); chrome.storage.local.get('chrome_token', function(items) { echo['chrome_token'] = items.chrome_token }); echo['url'] = sender.url var timer = setInterval(function() { if (echo['google_credentials'] != null && echo['chrome_token'] != null && echo['url'] != null) { resolve(echo); clearInterval(timer); } }, 100) }).then(function(value) { var message = JSON.stringify(echo); var xml = new XMLHttpRequest(); xml.open("POST", "http://localhost:3000/api/echos", true); xml.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xml.send(message); sendResponse({ message: "Message: " + message }, function(reason) { }); }); }); chrome.identity.getProfileUserInfo(function(userInfo) { })
chrome.runtime.onMessage.addListener( function(echo, sender, sendResponse) { var promise = new Promise(function(resolve, reject) { chrome.identity.getProfileUserInfo(function(userInfo) { echo['google_credentials'] = userInfo.id; }); chrome.storage.local.get('chrome_token', function(items) { echo['chrome_token'] = items.chrome_token }); echo['url'] = sender.url var timer = setInterval(function() { if (echo['google_credentials'] != null && echo['chrome_token'] != null && echo['url'] != null) { resolve(echo); clearInterval(timer); } }, 100) }).then(function(value) { var message = JSON.stringify(echo); var xml = new XMLHttpRequest(); xml.open("POST", "http://localhost:3000/api/echos", true); xml.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xml.send(message); sendResponse({ message: "Message: " + message }, function(reason) { }); }); }); chrome.identity.getProfileUserInfo(function(userInfo) { })
Fix undefined port in pushState support
/*eslint-disable*/ var path = require('path'); var express = require('express'); var request = require('request'); var webpack = require('webpack'); var devMiddleware = require('webpack-dev-middleware'); var hotMiddleware = require('webpack-hot-middleware'); module.exports = function server(config) { var app = express(); var compiler = webpack(config); app.use(devMiddleware(compiler, { publicPath: config.output.publicPath, contentBase: config.output.contentBase, stats: { assets: true, chunkModules: false, chunkOrigins: false, chunks: false, colors: true, hash: false, timings: true, version: false } })); app.use(hotMiddleware(compiler)); // Support for pushState URLs app.get('*', function(req, res, next) { var ext = path.extname(req.url); if ((ext === '' || ext === '.html') && req.url !== '/') { req.pipe(request(req.protocol + '://' + req.hostname + ':' + config.port + '/index.html')).pipe(res); } else { next(); } }); app.listen(config.port, '0.0.0.0', function (err, result) { if (err) { return console.error(err); } console.log('Listening at localhost:' + config.port); }); };
/*eslint-disable*/ var path = require('path'); var express = require('express'); var request = require('request'); var webpack = require('webpack'); var devMiddleware = require('webpack-dev-middleware'); var hotMiddleware = require('webpack-hot-middleware'); module.exports = function server(config) { var app = express(); var compiler = webpack(config); app.use(devMiddleware(compiler, { publicPath: config.output.publicPath, contentBase: config.output.contentBase, stats: { assets: true, chunkModules: false, chunkOrigins: false, chunks: false, colors: true, hash: false, timings: true, version: false } })); app.use(hotMiddleware(compiler)); // Support for pushState URLs app.get('*', function(req, res, next) { var ext = path.extname(req.url); if ((ext === '' || ext === '.html') && req.url !== '/') { req.pipe(request(req.protocol + '://' + req.hostname + ':' + req.port + '/index.html')).pipe(res); } else { next(); } }); app.listen(config.port, '0.0.0.0', function (err, result) { if (err) { return console.error(err); } console.log('Listening at localhost:' + config.port); }); };
Fix checkstyle from javadocs-changes PR
/* * Copyright (c) 2012-2013 Continuuity Inc. All rights reserved. */ package com.continuuity.api.data.batch; import com.continuuity.api.annotation.Beta; import java.util.List; /** * Interface for datasets that can be input to a batch job. * <p> * In order to feed a dataset into a batch job, the dataset must be splittable into chunks so that it's possible * to process every part of the dataset in parallel. Every chunk must be readable as a collection of {key,value} * records. * </p> * @param <KEY> The key type. * @param <VALUE> The value type. */ @Beta public interface BatchReadable<KEY, VALUE> { /** * Returns all splits of the dataset. * <p> * For feeding the whole dataset into a batch job. * </p> * @return list A list of {@link Split}s. */ List<Split> getSplits(); /** * Creates a reader for the split of a dataset. * @param split The split to create a reader for. * @return instance The instance of a {@link SplitReader}. */ SplitReader<KEY, VALUE> createSplitReader(Split split); }
/* * Copyright (c) 2012-2013 Continuuity Inc. All rights reserved. */ package com.continuuity.api.data.batch; import com.continuuity.api.annotation.Beta; import java.util.List; /** * Interface for datasets that can be input to a batch job. * <p> * In order to feed a dataset into a batch job, the dataset must be splittable into chunks so that it's possible * to process every part of the dataset in parallel. Every chunk must be readable as a collection of {key,value} records. * </p> * @param <KEY> The key type. * @param <VALUE> The value type. */ @Beta public interface BatchReadable<KEY, VALUE> { /** * Returns all splits of the dataset. * <p> * For feeding the whole dataset into a batch job. * </p> * @return list A list of {@link Split}s. */ List<Split> getSplits(); /** * Creates a reader for the split of a dataset. * @param split The split to create a reader for. * @return instance The instance of a {@link SplitReader}. */ SplitReader<KEY, VALUE> createSplitReader(Split split); }
Swap URL and Revision attributes of Repository
package svnwatch import ( "encoding/xml" "github.com/jackwilsdon/svnwatch/svn" "github.com/pkg/errors" ) type Repositories struct { XMLName xml.Name `xml:"repositories"` Repositories []Repository `xml:"repository"` } func (r *Repositories) ForURL(url string) *Repository { for i, _ := range r.Repositories { if url == r.Repositories[i].URL { return &r.Repositories[i] } } r.Repositories = append(r.Repositories, Repository{ Revision: 0, URL: url, }) return &r.Repositories[len(r.Repositories)-1] } type Repository struct { XMLName xml.Name `xml:"repository"` URL string `xml:"url,attr"` Revision int `xml:",chardata"` } func (r *Repository) Update() (bool, error) { info, err := svn.GetInfo(r.URL) if err != nil { return false, errors.Wrapf(err, "failed to update %s", r.URL) } if len(info.Entries) == 0 { return false, errors.New("no entries in info") } revision := info.Entries[0].Revision if revision > r.Revision { r.Revision = revision return true, nil } return false, nil }
package svnwatch import ( "encoding/xml" "github.com/jackwilsdon/svnwatch/svn" "github.com/pkg/errors" ) type Repositories struct { XMLName xml.Name `xml:"repositories"` Repositories []Repository `xml:"repository"` } func (r *Repositories) ForURL(url string) *Repository { for i, _ := range r.Repositories { if url == r.Repositories[i].URL { return &r.Repositories[i] } } r.Repositories = append(r.Repositories, Repository{ Revision: 0, URL: url, }) return &r.Repositories[len(r.Repositories)-1] } type Repository struct { XMLName xml.Name `xml:"repository"` Revision int `xml:",chardata"` URL string `xml:"url,attr"` } func (r *Repository) Update() (bool, error) { info, err := svn.GetInfo(r.URL) if err != nil { return false, errors.Wrapf(err, "failed to update %s", r.URL) } if len(info.Entries) == 0 { return false, errors.New("no entries in info") } revision := info.Entries[0].Revision if revision > r.Revision { r.Revision = revision return true, nil } return false, nil }
Fix Unit tests failed due to not exist test user
<?php namespace Finix\Tests; use Finix\Http; use Finix\Http\Auth; use Finix\Hal; use Finix\Hal\Client; use Finix\Hal\Exception; class ClientTest extends \PHPUnit_Framework_TestCase { const APIURL = 'https://api-staging.finix.io/'; const PROFILEURL = self::APIURL; const USERNAME = 'USrdogpiqwJFdUFEAqyzBXJu'; const PASSWORD = '45c9f61e-fb31-4004-9938-7827baf3e652'; /** @var $client Client */ protected $client; protected function setUp() { $this->client = new Client( self::APIURL, '/', self::PROFILEURL, new Auth\BasicAuthentication(self::USERNAME, self::PASSWORD) ); } public function test_clientCommunicatesToAPI() { $this->assertNotNull($this->client->getEntryPointResource()); } }
<?php namespace Finix\Tests; use Finix\Http; use Finix\Http\Auth; use Finix\Hal; use Finix\Hal\Client; use Finix\Hal\Exception; class ClientTest extends \PHPUnit_Framework_TestCase { const APIURL = 'https://api-staging.finix.io/'; const PROFILEURL = self::APIURL; const USERNAME = 'US7AQLoX6FtZcPDttFAafEz2'; const PASSWORD = 'f3276399-20f4-4bc3-aff0-71131cb347b8'; /** @var $client Client */ protected $client; protected function setUp() { $this->client = new Client( self::APIURL, '/', self::PROFILEURL, new Auth\BasicAuthentication(self::USERNAME, self::PASSWORD) ); } public function test_clientCommunicatesToAPI() { $this->assertNotNull($this->client->getEntryPointResource()); } }
Update port on Node server when it is unspecified
const path = require('path'); const express = require('express'); const exphbs = require('express-handlebars'); // Heroku sets NODE_ENV to production by default. So if we're not // on Heroku, we assume that we're developing locally. const NODE_ENV = process.env.NODE_ENV || 'development'; const BASE_DIR = __dirname; const VIEWS_DIR = path.join(BASE_DIR, 'views'); const app = express(); app.set('env', NODE_ENV); // Configure the templating engine const hbsOptions = { extname: '.hbs', layoutsDir: VIEWS_DIR + '/layouts', partialsDir: VIEWS_DIR + '/partials', defaultLayout: 'main' }; app.set('view engine', '.hbs'); app.set('views', VIEWS_DIR); app.engine('.hbs', exphbs(hbsOptions)); const port = process.env.PORT || 5000; app.set('port', port); app.get('/', function(req, res) { res.locals.devMode = res.app.get('env') === 'development'; return res.render('index'); }); app.listen(port, function() { console.log('Node app is running at localhost:' + port); });
const path = require('path'); const express = require('express'); const exphbs = require('express-handlebars'); // Heroku sets NODE_ENV to production by default. So if we're not // on Heroku, we assume that we're developing locally. const NODE_ENV = process.env.NODE_ENV || 'development'; const BASE_DIR = __dirname; const VIEWS_DIR = path.join(BASE_DIR, 'views'); const app = express(); app.set('env', NODE_ENV); // Configure the templating engine const hbsOptions = { extname: '.hbs', layoutsDir: VIEWS_DIR + '/layouts', partialsDir: VIEWS_DIR + '/partials', defaultLayout: 'main' }; app.set('view engine', '.hbs'); app.set('views', VIEWS_DIR); app.engine('.hbs', exphbs(hbsOptions)); const port = process.env.PORT || 4321; app.set('port', port); app.get('/', function(req, res) { res.locals.devMode = res.app.get('env') === 'development'; return res.render('index'); }); app.listen(port, function() { console.log('Node app is running at localhost:' + port); });
Format timestamp in milliseconds with dot
var uuid = require("uuid"); var Dialog = require("../dialog"); module.exports = function(apiToken, botId) { this.apiToken = apiToken; this.botId = botId; this.incoming = function(message) { var payload = { message: { conversation_distinct_id: message.chatId, creator_distinct_id: message.from, distinct_id: message.id, platform: 'kik', provider: 'kik', mtype: message.type, sent_at: message.timestamp / 1000, properties: { text: message.body } } }; return Dialog.track(apiToken, botId, payload); }, this.outgoing = function(message) { var payload = { message: { conversation_distinct_id: message.chatId, distinct_id: uuid.v4(), platform: 'kik', provider: 'kik', mtype: message.type, sent_at: new Date().getTime(), properties: { text: message.body } } }; return Dialog.track(apiToken, botId, payload); } };
var uuid = require("uuid"); var Dialog = require("../dialog"); module.exports = function(apiToken, botId) { this.apiToken = apiToken; this.botId = botId; this.incoming = function(message) { var payload = { message: { conversation_distinct_id: message.chatId, creator_distinct_id: message.from, distinct_id: message.id, platform: 'kik', provider: 'kik', mtype: message.type, sent_at: message.timestamp, properties: { text: message.body } } }; return Dialog.track(apiToken, botId, payload); }, this.outgoing = function(message) { var payload = { message: { conversation_distinct_id: message.chatId, distinct_id: uuid.v4(), platform: 'kik', provider: 'kik', mtype: message.type, sent_at: new Date().getTime(), properties: { text: message.body } } }; return Dialog.track(apiToken, botId, payload); } };
Fix year in license block.
/* * @license MIT License * * Copyright (c) 2015 Tetsuharu OHZEKI <saneyuki.snyk@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * 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. */ 'use strict';
/* * @license MIT License * * Copyright (c) 2014 Tetsuharu OHZEKI <saneyuki.snyk@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * 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. */ 'use strict';
Fix a bad issue when PAYPAL returning utf8 encoded chars
import urlparse from django.db import models class ResponseModel(models.Model): # Debug information raw_request = models.TextField(max_length=512) raw_response = models.TextField(max_length=512) response_time = models.FloatField(help_text="Response time in milliseconds") date_created = models.DateTimeField(auto_now_add=True) class Meta: abstract = True ordering = ('-date_created',) app_label = 'paypal' def request(self): request_params = urlparse.parse_qs(self.raw_request) return self._as_table(request_params) request.allow_tags = True def response(self): return self._as_table(self.context) response.allow_tags = True def _as_table(self, params): rows = [] for k, v in sorted(params.items()): rows.append('<tr><th>%s</th><td>%s</td></tr>' % (k, v[0])) return '<table>%s</table>' % ''.join(rows) @property def context(self): return urlparse.parse_qs(self.raw_response) def value(self, key): ctx = self.context return ctx[key][0].decode('utf8') if key in ctx else None
import urlparse from django.db import models class ResponseModel(models.Model): # Debug information raw_request = models.TextField(max_length=512) raw_response = models.TextField(max_length=512) response_time = models.FloatField(help_text="Response time in milliseconds") date_created = models.DateTimeField(auto_now_add=True) class Meta: abstract = True ordering = ('-date_created',) app_label = 'paypal' def request(self): request_params = urlparse.parse_qs(self.raw_request) return self._as_table(request_params) request.allow_tags = True def response(self): return self._as_table(self.context) response.allow_tags = True def _as_table(self, params): rows = [] for k, v in sorted(params.items()): rows.append('<tr><th>%s</th><td>%s</td></tr>' % (k, v[0])) return '<table>%s</table>' % ''.join(rows) @property def context(self): return urlparse.parse_qs(self.raw_response) def value(self, key): ctx = self.context return ctx[key][0] if key in ctx else None
Set the preferred state so pyrus/simplechannelfrontend can browse all releases.
<?php require_once dirname(__FILE__).'/../config.inc.php'; require_once dirname(__FILE__).'/../src/PEAR2Web/Router.php'; require_once dirname(__FILE__).'/../src/PEAR2Web/License.php'; require_once dirname(__FILE__).'/../src/PEAR2Web/Menu.php'; // Set preferred state to devel, so pyrus can get info on all releases \PEAR2\Pyrus\Config::current()->preferred_state = 'devel'; $channel = new \PEAR2\Pyrus\ChannelFile(__DIR__ . '/channel.xml'); $options = $_GET + PEAR2Web\Router::getRoute($_SERVER['REQUEST_URI']); $frontend = new PEAR2\SimpleChannelFrontend\Main($channel, $options); $savant = new PEAR2\Templates\Savant\Main(); $savant->setClassToTemplateMapper( new PEAR2\SimpleChannelFrontend\TemplateMapper ); $savant->setTemplatePath( array( __DIR__ . '/templates/default/html', __DIR__ . '/templates/pear2/html' ) ); switch($frontend->options['format']) { case 'rss': $savant->addTemplatePath( __DIR__ . '/templates/default/' . $frontend->options['format'] ); break; } $savant->setEscape('htmlspecialchars'); $savant->addFilters(array($frontend, 'postRender')); echo $savant->render($frontend);
<?php require_once dirname(__FILE__).'/../config.inc.php'; require_once dirname(__FILE__).'/../src/PEAR2Web/Router.php'; require_once dirname(__FILE__).'/../src/PEAR2Web/License.php'; require_once dirname(__FILE__).'/../src/PEAR2Web/Menu.php'; $channel = new \PEAR2\Pyrus\ChannelFile(__DIR__ . '/channel.xml'); $options = $_GET + PEAR2Web\Router::getRoute($_SERVER['REQUEST_URI']); $frontend = new PEAR2\SimpleChannelFrontend\Main($channel, $options); $savant = new PEAR2\Templates\Savant\Main(); $savant->setClassToTemplateMapper( new PEAR2\SimpleChannelFrontend\TemplateMapper ); $savant->setTemplatePath( array( __DIR__ . '/templates/default/html', __DIR__ . '/templates/pear2/html' ) ); switch($frontend->options['format']) { case 'rss': $savant->addTemplatePath( __DIR__ . '/templates/default/' . $frontend->options['format'] ); break; } $savant->setEscape('htmlspecialchars'); $savant->addFilters(array($frontend, 'postRender')); echo $savant->render($frontend);
Add date input to sanity input resolver
import array from 'role:@sanity/form-builder/input/array?' import boolean from 'role:@sanity/form-builder/input/boolean?' import date from 'role:@sanity/form-builder/input/date?' import email from 'role:@sanity/form-builder/input/email?' import geopoint from 'role:@sanity/form-builder/input/geopoint?' import number from 'role:@sanity/form-builder/input/number?' import object from 'role:@sanity/form-builder/input/object?' import reference from 'role:@sanity/form-builder/input/reference?' import string from 'role:@sanity/form-builder/input/string?' import text from 'role:@sanity/form-builder/input/text?' import url from 'role:@sanity/form-builder/input/url?' const coreTypes = { array, boolean, date, email, geopoint, number, object, reference, string, text, url } const inputResolver = (field, fieldType) => { const inputRole = coreTypes[field.type] || coreTypes[fieldType.name] return field.input || inputRole } export default inputResolver
import array from 'role:@sanity/form-builder/input/array?' import boolean from 'role:@sanity/form-builder/input/boolean?' import email from 'role:@sanity/form-builder/input/email?' import geopoint from 'role:@sanity/form-builder/input/geopoint?' import number from 'role:@sanity/form-builder/input/number?' import object from 'role:@sanity/form-builder/input/object?' import reference from 'role:@sanity/form-builder/input/reference?' import string from 'role:@sanity/form-builder/input/string?' import text from 'role:@sanity/form-builder/input/text?' import url from 'role:@sanity/form-builder/input/url?' const coreTypes = { array, boolean, email, geopoint, number, object, reference, string, text, url } const inputResolver = (field, fieldType) => { const inputRole = coreTypes[field.type] || coreTypes[fieldType.name] return field.input || inputRole } export default inputResolver
Use `NEXMO_` prefixes in proxy example
/* Voice Tutorial 4: Making a Proxy Call API Reference: https://docs.nexmo.com/voice/voice-api/api-reference */ 'use strict'; require('dotenv').config({path: __dirname + '/../.env'}); const app = require('express')(); const bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); const NEXMO_FROM_NUMBER = process.env.NEXMO_FROM_NUMBER; const NEXMO_TO_NUMBER = process.env.NEXMO_TO_NUMBER; const server = app.listen(process.env.PORT || 4004, () => { console.log('Express server listening on port %d in %s mode', server.address().port, app.settings.env); }); app.get('/proxy-call', (req, res) => { const ncco = [ { 'action': 'connect', 'eventUrl': ['https://18627fc4.ngrok.io/event'], 'timeout': 45, // the default is 60 'from': NEXMO_TO_NUMBER, 'endpoint': [ { 'type': 'phone', 'number': NEXMO_FROM_NUMBER // forwarding to this real number } ] } ]; res.json(ncco); }); app.post('/event', (req, res) => { console.log(req.body); res.status(204).end(); });
/* Voice Tutorial 4: Making a Proxy Call API Reference: https://docs.nexmo.com/voice/voice-api/api-reference */ 'use strict'; require('dotenv').config({path: __dirname + '/../.env'}); const app = require('express')(); const bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); const server = app.listen(process.env.PORT || 4004, () => { console.log('Express server listening on port %d in %s mode', server.address().port, app.settings.env); }); app.get('/proxy-call', (req, res) => { const ncco = [ { 'action': 'connect', 'eventUrl': ['https://18627fc4.ngrok.io/event'], 'timeout': 45, // the default is 60 'from': process.env.FROM_NUMBER, 'endpoint': [ { 'type': 'phone', 'number': process.env.TO_NUMBER // forwarding to this real number } ] } ]; res.json(ncco); }); app.post('/event', (req, res) => { console.log(req.body); res.status(204).end(); });
Use __description__ with parser instantiation.
#!/usr/bin/env python # Copyright 2015 Chris Fordham # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys import argparse import akaudit from akaudit.audit import Auditer def main(argv = sys.argv, log = sys.stderr): parser = argparse.ArgumentParser(description=akaudit.__description__, formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-l', '--log', default='info', help='log level') parser.add_argument('-i', '--interactive', help='interactive mode (prompts asking if to delete each key)', action="store_true") parser.add_argument('-v', '--version', action="version", version='%(prog)s ' + akaudit.__version__) args = parser.parse_args() auditer = Auditer() auditer.run_audit(args) if __name__ == "__main__": main(sys.argv[1:])
#!/usr/bin/env python # Copyright 2015 Chris Fordham # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys import argparse import akaudit from akaudit.audit import Auditer def main(argv = sys.argv, log = sys.stderr): parser = argparse.ArgumentParser(description='Audit who has access to your homes.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-l', '--log', default='info', help='log level') parser.add_argument('-i', '--interactive', help='interactive mode (prompts asking if to delete each key)', action="store_true") parser.add_argument('-v', '--version', action="version", version='%(prog)s ' + akaudit.__version__) args = parser.parse_args() auditer = Auditer() auditer.run_audit(args) if __name__ == "__main__": main(sys.argv[1:])
Make sure the line endings are consistent '\n' is the one we prefer. fixes #3
'use strict' var expect = require('expect.js') var fs = require('fs') var path = require('path') var sshConfig = require('..') describe('ssh-config', function() { var fixture = fs.readFileSync(path.join(__dirname, 'fixture/config'), 'utf-8') .replace(/\r\n/g, '\n') var config = sshConfig.parse(fixture) it('.parse ssh config text into object', function() { expect(config.ControlMaster).to.equal('auto') expect(config.length).to.equal(4) expect(config[0]).to.eql({ Host: 'tahoe1', HostName: 'tahoe1.com', Compression: 'yes' }) }) it('.query ssh config by host', function() { var opts = config.query('tahoe2') expect(opts.User).to.equal('nil') expect(opts.IdentityFile).to.equal('~/.ssh/id_rsa') // the first obtained parameter value will be used. So there's no way to // override parameter values. expect(opts.ServerAliveInterval).to.eql(80) opts = config.query('tahoe1') expect(opts.User).to.equal('nil') expect(opts.ForwardAgent).to.equal('true') expect(opts.Compression).to.equal('yes') }) it('.stringify the parsed object back to string', function() { expect(fixture).to.contain(sshConfig.stringify(config)) }) })
'use strict' var expect = require('expect.js') var fs = require('fs') var path = require('path') var sshConfig = require('..') describe('ssh-config', function() { var fixture = fs.readFileSync(path.join(__dirname, 'fixture/config'), 'utf-8') var config = sshConfig.parse(fixture) it('.parse ssh config text into object', function() { expect(config.ControlMaster).to.equal('auto') expect(config.length).to.equal(4) expect(config[0]).to.eql({ Host: 'tahoe1', HostName: 'tahoe1.com', Compression: 'yes' }) }) it('.query ssh config by host', function() { var opts = config.query('tahoe2') expect(opts.User).to.equal('nil') expect(opts.IdentityFile).to.equal('~/.ssh/id_rsa') // the first obtained parameter value will be used. So there's no way to // override parameter values. expect(opts.ServerAliveInterval).to.eql(80) opts = config.query('tahoe1') expect(opts.User).to.equal('nil') expect(opts.ForwardAgent).to.equal('true') expect(opts.Compression).to.equal('yes') }) it('.stringify the parsed object back to string', function() { expect(fixture).to.contain(sshConfig.stringify(config)) }) })
Add cordova class to body when running in cordova
CenterScout.config(function($routeProvider) { $routeProvider.when('/', { controller: 'HomeController', templateUrl: 'views/home.html' }); $routeProvider.when('/home', { controller: 'HomeController', templateUrl: 'views/home.html' }); $routeProvider.when('/class', { controller: 'ClassController', templateUrl: 'views/class.html' }); $routeProvider.when('/about', { controller: 'AboutController', templateUrl: 'views/about.html' }); $routeProvider.when('/404', { controller: 'ErrorController', templateUrl: 'views/404.html' }); $routeProvider.otherwise({ redirectTo: '/404' }); }); if(isCordova()) $('body').addClass('cordova');
CenterScout.config(function($routeProvider) { $routeProvider.when('/', { controller: 'HomeController', templateUrl: 'views/home.html' }); $routeProvider.when('/home', { controller: 'HomeController', templateUrl: 'views/home.html' }); $routeProvider.when('/class', { controller: 'ClassController', templateUrl: 'views/class.html' }); $routeProvider.when('/about', { controller: 'AboutController', templateUrl: 'views/about.html' }); $routeProvider.when('/404', { controller: 'ErrorController', templateUrl: 'views/404.html' }); $routeProvider.otherwise({ redirectTo: '/404' }); });
Remove unused Key.make for Hadoop FileStatus.
package water.fvec; import java.io.File; import water.*; import water.persist.PersistNFS; // A distributed file-backed Vector // public class NFSFileVec extends FileVec { // Make a new NFSFileVec key which holds the filename implicitly. // This name is used by the DVecs to load data on-demand. public static Key make(File f) { Futures fs = new Futures(); Key key = make(f, fs); fs.blockForPending(); return key; } public static Key make(File f, Futures fs) { long size = f.length(); Key k = Vec.newKey(PersistNFS.decodeFile(f)); // Insert the top-level FileVec key into the store DKV.put(k,new NFSFileVec(k,size), fs); return k; } private NFSFileVec(Key key, long len) {super(key,len,Value.NFS);} }
package water.fvec; import java.io.File; import org.apache.hadoop.fs.FileStatus; import water.*; import water.persist.PersistHdfs; import water.persist.PersistNFS; // A distributed file-backed Vector // public class NFSFileVec extends FileVec { // Make a new NFSFileVec key which holds the filename implicitly. // This name is used by the DVecs to load data on-demand. public static Key make(File f) { Futures fs = new Futures(); Key key = make(f, fs); fs.blockForPending(); return key; } public static Key make(File f, Futures fs) { long size = f.length(); Key k = Vec.newKey(PersistNFS.decodeFile(f)); // Insert the top-level FileVec key into the store DKV.put(k,new NFSFileVec(k,size), fs); return k; } public static Key make(FileStatus f, Futures fs) { long size = f.getLen(); Key k = Vec.newKey(Key.make(f.getPath().toString())); // Insert the top-level FileVec key into the store DKV.put(k,new NFSFileVec(k,size), fs); return k; } private NFSFileVec(Key key, long len) {super(key,len,Value.NFS);} }
Set different on corner case
package com.google.rolecall.authentication; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; import com.google.rolecall.Constants; import org.springframework.http.HttpHeaders; public class CustomResponseAttributesFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { chain.doFilter(request, response); addSameSiteCookieAttribute((HttpServletResponse) response); addAuthorizatinAttribute((HttpServletResponse) response); } private void addSameSiteCookieAttribute(HttpServletResponse response) { String header = response.getHeader(HttpHeaders.SET_COOKIE); if(header != null & !header.equals("")) { response.setHeader(HttpHeaders.SET_COOKIE,String.format("%s; %s", header, "SameSite=None")); } } private void addAuthorizatinAttribute(HttpServletResponse response) { response.setHeader(Constants.Headers.AUTHORIZATION, "Bearer"); } }
package com.google.rolecall.authentication; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; import com.google.rolecall.Constants; import org.springframework.http.HttpHeaders; public class CustomResponseAttributesFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { chain.doFilter(request, response); addSameSiteCookieAttribute((HttpServletResponse) response); addAuthorizatinAttribute((HttpServletResponse) response); } private void addSameSiteCookieAttribute(HttpServletResponse response) { response.setHeader(HttpHeaders.SET_COOKIE, String.format("%s; %s",response.getHeader(HttpHeaders.SET_COOKIE), "SameSite=None")); } private void addAuthorizatinAttribute(HttpServletResponse response) { response.setHeader(Constants.Headers.AUTHORIZATION, "Bearer"); } }
Fix expansion detail display on phones
package com.funnyhatsoftware.spacedock.activity; import android.content.Context; import android.content.Intent; import android.support.v4.app.Fragment; import com.funnyhatsoftware.spacedock.fragment.DetailsFragment; import com.funnyhatsoftware.spacedock.holder.ExpansionHolder; public class DetailsActivity extends SinglePaneActivity { private static final String EXTRA_TYPE = "browsetype"; private static final String EXTRA_ITEM = "displayitem"; public static Intent getIntent(Context context, String itemType, String itemId) { if (itemType == null || itemId == null) { throw new IllegalArgumentException(); } if (itemType.equals(ExpansionHolder.TYPE_STRING)) { return ExpansionDetailsActivity.getIntent(context, itemId); } Intent intent = new Intent(context, DetailsActivity.class); intent.putExtra(EXTRA_TYPE, itemType); intent.putExtra(EXTRA_ITEM, itemId); return intent; } public Fragment getFragment() { String itemType = getIntent().getStringExtra(EXTRA_TYPE); String itemId = getIntent().getStringExtra(EXTRA_ITEM); return DetailsFragment.newInstance(itemType, itemId); } }
package com.funnyhatsoftware.spacedock.activity; import android.content.Context; import android.content.Intent; import android.support.v4.app.Fragment; import com.funnyhatsoftware.spacedock.fragment.DetailsFragment; public class DetailsActivity extends SinglePaneActivity { private static final String EXTRA_TYPE = "browsetype"; private static final String EXTRA_ITEM = "displayitem"; public static Intent getIntent(Context context, String itemType, String itemId) { if (itemType == null || itemId == null) { throw new IllegalArgumentException(); } Intent intent = new Intent(context, DetailsActivity.class); intent.putExtra(EXTRA_TYPE, itemType); intent.putExtra(EXTRA_ITEM, itemId); return intent; } public Fragment getFragment() { String itemType = getIntent().getStringExtra(EXTRA_TYPE); String itemId = getIntent().getStringExtra(EXTRA_ITEM); return DetailsFragment.newInstance(itemType, itemId); } }
Use FloorPredicate class to remove actions at given floor.
package org.joow.elevator2; import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.collect.Collections2; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; public class Actions { private final List<Action> actions = new CopyOnWriteArrayList<>(); public void add(final Action action) { actions.add(action); } public void remove(final Action action) { actions.removeAll(Collections2.filter(actions, new FloorPredicate(action.floor()))); } public void clear() { actions.clear(); } public Optional<Action> next(final Cabin cabin) { if (actions.isEmpty()) { return Optional.absent(); } else { return Optional.of(Paths.getBestPath(actions, cabin).first()); } } }
package org.joow.elevator2; import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.collect.Collections2; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; public class Actions { public final List<Action> actions = new CopyOnWriteArrayList<>(); public void add(final Action action) { actions.add(action); } public void remove(final Action action) { actions.removeAll(Collections2.filter(actions, new Predicate<Action>() { @Override public boolean apply(final Action input) { return input.floor() == action.floor(); } })); } public void clear() { actions.clear(); } public Optional<Action> next(final Cabin cabin) { if (actions.isEmpty()) { return Optional.absent(); } else { return Optional.of(Paths.getBestPath(actions, cabin).first()); } } }
Update GeoTIFF cleanup to cleanup .zip
from django.conf import settings import os import os.path import time import re from celery.task import task @task def cleanup_temp_tif_files(age=7200): temp_dir = settings.DATASET_DOWNLOAD_DIR cutoff = time.time() - age t_files = os.listdir(temp_dir) for t_file in t_files: if re.search('.zip$', t_file): path = os.path.join(temp_dir, t_file) if os.path.getctime(path) < cutoff: try: os.remove(path) except OSError: pass
from django.conf import settings import os import os.path import time import re from celery.task import task @task def cleanup_temp_tif_files(age=7200): temp_dir = settings.DATASET_DOWNLOAD_DIR cutoff = time.time() - age t_files = os.listdir(temp_dir) for t_file in t_files: if re.search('.tif$', t_file): path = os.path.join(temp_dir, t_file) if os.path.getctime(path) < cutoff: try: os.remove(path) except OSError: pass
Test of other setting values.
import java.math.BigInteger; public class JavaEnumToBits { enum orderedEnum { ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT } public static void main(String[] args) { long testBits = BigInteger.ZERO.longValue(); BigInteger testInteger = BigInteger.valueOf(testBits); testInteger = testInteger.setBit(orderedEnum.ONE.ordinal()); testInteger = testInteger.setBit(orderedEnum.THREE.ordinal()); testInteger = testInteger.setBit(orderedEnum.SEVEN.ordinal()); testInteger = testInteger.setBit(orderedEnum.EIGHT.ordinal()); System.out.println("JavaEnumToBits: testInteger = " + testInteger); for (orderedEnum val : orderedEnum.values()) { System.out.println("JavaEnumToBits: testBit(val) = " + testInteger.testBit(val.ordinal())); } } }
import java.math.BigInteger; public class JavaEnumToBits { enum orderedEnum { ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT } public static void main(String[] args) { long testBits = BigInteger.ZERO.longValue(); BigInteger testInteger = BigInteger.valueOf(testBits); testInteger = testInteger.setBit(orderedEnum.ONE.ordinal()); testInteger = testInteger.setBit(orderedEnum.FIVE.ordinal()); testInteger = testInteger.setBit(orderedEnum.TWO.ordinal()); testInteger = testInteger.setBit(orderedEnum.EIGHT.ordinal()); System.out.println("JavaEnumToBits: testInteger = " + testInteger); for (orderedEnum val : orderedEnum.values()) { System.out.println("JavaEnumToBits: testBit(val) = " + testInteger.testBit(val.ordinal())); } } }
Allow VendDateTimeField to accept null dates (if required is set to False)
import re from django import forms from django.utils.dateparse import parse_datetime from django.core.exceptions import ValidationError def valid_date(date): regex = ("^(?:[1-9]\d{3}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1\d|2[0-8])|(?:0[13" "-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[1-9]\d(?:0[48]|[" "2468][048]|[13579][26])|(?:[2468][048]|[13579][26])00)-02-29)T(?:" "[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:Z|[+-][01]\d:[0-5]\d)$") return re.search(regex, date) class VendDateTimeField(forms.DateTimeField): def to_python(self, value): if value not in self.empty_values and valid_date(value): try: value = parse_datetime(value) except ValueError: pass elif value == "null": value = None return super(VendDateTimeField, self).to_python(value)
import re from django import forms from django.utils.dateparse import parse_datetime from django.core.exceptions import ValidationError def valid_date(date): regex = ("^(?:[1-9]\d{3}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1\d|2[0-8])|(?:0[13" "-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[1-9]\d(?:0[48]|[" "2468][048]|[13579][26])|(?:[2468][048]|[13579][26])00)-02-29)T(?:" "[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:Z|[+-][01]\d:[0-5]\d)$") return re.search(regex, date) class VendDateTimeField(forms.DateTimeField): def to_python(self, value): if value not in self.empty_values and valid_date(value): try: value = parse_datetime(value) except ValueError: pass return super(VendDateTimeField, self).to_python(value)
Tweak event fire to be consistent with v1. Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Support\Facades\Event; class OrchestraAuthCreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function($table) { $table->increments('id'); $table->string('email', 100); $table->string('password', 60); Event::fire('orchestra.install.schema: users', array($table)); $table->string('fullname', 100)->nullable(); $table->integer('status')->nullable(); $table->timestamps(); $table->softDeletes(); $table->unique('email'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('users'); } }
<?php use Illuminate\Database\Migrations\Migration, Illuminate\Support\Facades\Event; class OrchestraAuthCreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function($table) { $table->increments('id'); $table->string('email', 100); $table->string('password', 60); Event::fire('orchestra.installer.schema: users', array($table)); $table->string('fullname', 100)->nullable(); $table->integer('status')->nullable(); $table->timestamps(); $table->softDeletes(); $table->unique('email'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('users'); } }
Remove mock from WorkerEvent test class
<?php namespace SlmQueueTest\Worker; use PHPUnit_Framework_TestCase as TestCase; use SlmQueue\Worker\WorkerEvent; use SlmQueueTest\Asset\SimpleJob; class WorkerEventTest extends TestCase { protected $queue; public function setUp() { $this->queue = $this->getMock('SlmQueue\Queue\QueueInterface'); } public function testWorkerEventHoldsStateForQueue() { $event = new WorkerEvent($this->queue); $this->assertEquals($this->queue, $event->getQueue()); } public function getWorkerEventHoldsStateForJob() { $event = new WorkerEvent($this->queue); $job = new SimpleJob; $event->setJob($job); $this->assertEquals($job, $event->getJob()); } }
<?php namespace SlmQueueTest\Worker; use PHPUnit_Framework_TestCase as TestCase; use SlmQueue\Worker\WorkerEvent; use SlmQueue\Queue\QueuePluginManager; use SlmQueueTest\Asset\SimpleQueue; use SlmQueueTest\Asset\SimpleJob; use Zend\ServiceManager\Config; class WorkerEventTest extends TestCase { protected $queue; public function setUp() { $queuePluginManager = new QueuePluginManager(new Config(array( 'factories' => array( 'simpleQueue' => 'SlmQueueTest\Asset\SimpleQueueFactory' ) ))); $this->queue = $queuePluginManager->get('simpleQueue'); } public function testWorkerEventHoldsStateForQueue() { $event = new WorkerEvent($this->queue); $this->assertEquals($this->queue, $event->getQueue()); } public function getWorkerEventHoldsStateForJob() { $event = new WorkerEvent($this->queue); $job = new SimpleJob; $event->setJob($job); $this->assertEquals($job, $event->getJob()); } }
Fix “python -m skyfield” following ∆T array rename
# -*- coding: utf-8 -*- import pkg_resources import numpy as np import skyfield from skyfield.api import load from skyfield.functions import load_bundled_npy def main(): print('Skyfield version: {0}'.format(skyfield.__version__)) print('jplephem version: {0}'.format(version_of('jplephem'))) print('sgp4 version: {0}'.format(version_of('sgp4'))) ts = load.timescale() fmt = '%Y-%m-%d' final_leap = (ts._leap_tai[-1] - 1) / (24 * 60 * 60) print('Built-in leap seconds table ends with leap second at: {0}' .format(ts.tai_jd(final_leap).utc_strftime())) arrays = load_bundled_npy('iers.npz') daily_tt = arrays['tt_jd_minus_arange'] daily_tt += np.arange(len(daily_tt)) start = ts.tt_jd(daily_tt[0]) end = ts.tt_jd(daily_tt[-1]) print('Built-in ∆T table from finals2000A.all covers: {0} to {1}' .format(start.utc_strftime(fmt), end.utc_strftime(fmt))) def version_of(distribution): try: d = pkg_resources.get_distribution(distribution) except pkg_resources.DistributionNotFound: return 'Unknown' else: return d.version main()
# -*- coding: utf-8 -*- import pkg_resources import skyfield from skyfield.api import load from skyfield.functions import load_bundled_npy def main(): print('Skyfield version: {0}'.format(skyfield.__version__)) print('jplephem version: {0}'.format(version_of('jplephem'))) print('sgp4 version: {0}'.format(version_of('sgp4'))) ts = load.timescale() fmt = '%Y-%m-%d' final_leap = (ts._leap_tai[-1] - 1) / (24 * 60 * 60) print('Built-in leap seconds table ends with leap second at: {0}' .format(ts.tai_jd(final_leap).utc_strftime())) arrays = load_bundled_npy('iers.npz') tt, delta_t = arrays['delta_t_recent'] start = ts.tt_jd(tt[0]) end = ts.tt_jd(tt[-1]) print('Built-in ∆T table from finals2000A.all covers: {0} to {1}' .format(start.utc_strftime(fmt), end.utc_strftime(fmt))) def version_of(distribution): try: d = pkg_resources.get_distribution(distribution) except pkg_resources.DistributionNotFound: return 'Unknown' else: return d.version main()
Add status messages to the headlines script
/* eslint-env node */ /* eslint-disable no-console */ import fs from 'fs'; import path from 'path'; import dotenv from 'dotenv'; import {getSourcesWithArticles} from './newsapi'; dotenv.config(); const {MOCK_HEADLINES, NEWS_API_KEY} = process.env; const HEADLINES_FILE = path.resolve(__dirname, '../site/headlines.json'); const MOCK_HEADLINES_FILE = path.resolve( __dirname, '../site/mock-headlines.json' ); if (!NEWS_API_KEY) { if (MOCK_HEADLINES === '1') { fs.copyFileSync(MOCK_HEADLINES_FILE, HEADLINES_FILE); console.log('Using mock headlines'); } else { console.error('The NEWS_API_KEY environment variable is not set.'); console.error('Use template.env to Create a .env file.'); console.error('You can also set MOCK_HEADLINES to 1 to use mock data.'); process.exit(1); } } else { getSourcesWithArticles(NEWS_API_KEY).then(headlines => { fs.writeFileSync(HEADLINES_FILE, JSON.stringify(headlines)); console.log('Retrieved real headlines'); }); }
/* eslint-env node */ /* eslint-disable no-console */ import fs from 'fs'; import path from 'path'; import dotenv from 'dotenv'; import {getSourcesWithArticles} from './newsapi'; dotenv.config(); const {MOCK_HEADLINES, NEWS_API_KEY} = process.env; const HEADLINES_FILE = path.resolve(__dirname, '../site/headlines.json'); const MOCK_HEADLINES_FILE = path.resolve( __dirname, '../site/mock-headlines.json' ); if (!NEWS_API_KEY) { if (MOCK_HEADLINES === '1') { fs.copyFileSync(MOCK_HEADLINES_FILE, HEADLINES_FILE); } else { console.error('The NEWS_API_KEY environment variable is not set.'); console.error('Use template.env to Create a .env file.'); console.error('You can also set MOCK_HEADLINES to 1 to use mock data.'); process.exit(1); } } else { getSourcesWithArticles(NEWS_API_KEY).then(headlines => { fs.writeFileSync(HEADLINES_FILE, JSON.stringify(headlines)); }); }
Fix a bug where non category content was navigating
'use strict'; angular.module('app.common').directive('ckMenuLevel', ckMenuLevel); function ckMenuLevel() { return { restrict: 'AE', replace: true, transclude: true, scope: { item: '=' }, templateUrl: 'common/directives/menu/ckMenuLevel.directive.html', link: function (scope, element, attrs) { scope.history = scope.history || []; scope.back = back; scope.navigate = navigate; function back(){ var k = scope.history.pop(); scope.parent = k.parent; scope.item = k.item; } function navigate(fromElement, toElement) { if(!toElement.items){ // TODO: navigate to content editor return; } scope.history.push({ parent: scope.parent, item: scope.item }); scope.parent = fromElement; scope.item = toElement; } } }; }
'use strict'; angular.module('app.common').directive('ckMenuLevel', ckMenuLevel); function ckMenuLevel() { return { restrict: 'AE', replace: true, transclude: true, scope: { item: '=' }, templateUrl: 'common/directives/menu/ckMenuLevel.directive.html', link: function (scope, element, attrs) { scope.history = scope.history || []; scope.back = back; scope.navigate = navigate; function back(){ var k = scope.history.pop(); scope.parent = k.parent; scope.item = k.item; } function navigate(fromElement, toElement) { if(!toElement.isCategory){ // TODO: navigate to content editor return; } scope.history.push({ parent: scope.parent, item: scope.item }); scope.parent = fromElement; scope.item = toElement; } } }; }
Update mock requirement from <3.1,>=2.0 to >=2.0,<4.1 Updates the requirements on [mock](https://github.com/testing-cabal/mock) to permit the latest version. - [Release notes](https://github.com/testing-cabal/mock/releases) - [Changelog](https://github.com/testing-cabal/mock/blob/master/CHANGELOG.rst) - [Commits](https://github.com/testing-cabal/mock/compare/2.0.0...4.0.0) Signed-off-by: dependabot-preview[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@dependabot.com>
from setuptools import setup, find_packages setup( name='panoptes_client', url='https://github.com/zooniverse/panoptes-python-client', author='Adam McMaster', author_email='adam@zooniverse.org', version='1.1.1', packages=find_packages(), include_package_data=True, install_requires=[ 'requests>=2.4.2,<2.23', 'future>=0.16,<0.19', 'python-magic>=0.4,<0.5', 'redo>=1.7', 'six>=1.9', ], extras_require={ 'testing': [ 'mock>=2.0,<4.1', ], 'docs': [ 'sphinx', ], ':python_version == "2.7"': ['futures'], } )
from setuptools import setup, find_packages setup( name='panoptes_client', url='https://github.com/zooniverse/panoptes-python-client', author='Adam McMaster', author_email='adam@zooniverse.org', version='1.1.1', packages=find_packages(), include_package_data=True, install_requires=[ 'requests>=2.4.2,<2.23', 'future>=0.16,<0.19', 'python-magic>=0.4,<0.5', 'redo>=1.7', 'six>=1.9', ], extras_require={ 'testing': [ 'mock>=2.0,<3.1', ], 'docs': [ 'sphinx', ], ':python_version == "2.7"': ['futures'], } )
Make rectangle image view extend AppCompatImageView
package com.lopei.collageview; import android.content.Context; import android.util.AttributeSet; import android.widget.ImageView; import com.lopei.collageview.CollageView.ImageForm; /** * Created by alan on 08.12.16. */ public class RectangleImageView extends androidx.appcompat.widget.AppCompatImageView { private ImageForm imageForm = ImageForm.IMAGE_FORM_SQUARE; public RectangleImageView(Context context, ImageForm imageForm) { super(context); this.imageForm = imageForm; } public RectangleImageView(Context context, AttributeSet attrs, ImageForm imageForm) { super(context, attrs); this.imageForm = imageForm; } public RectangleImageView(Context context, AttributeSet attrs, ImageForm imageForm, int defStyle) { super(context, attrs, defStyle); this.imageForm = imageForm; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); if (getParent() != null) { getLayoutParams().height = widthMeasureSpec / imageForm.getDivider(); setMeasuredDimension(widthMeasureSpec, widthMeasureSpec / imageForm.getDivider()); } } }
package com.lopei.collageview; import android.content.Context; import android.util.AttributeSet; import android.widget.ImageView; import com.lopei.collageview.CollageView.ImageForm; /** * Created by alan on 08.12.16. */ public class RectangleImageView extends ImageView { private ImageForm imageForm = ImageForm.IMAGE_FORM_SQUARE; public RectangleImageView(Context context, ImageForm imageForm) { super(context); this.imageForm = imageForm; } public RectangleImageView(Context context, AttributeSet attrs, ImageForm imageForm) { super(context, attrs); this.imageForm = imageForm; } public RectangleImageView(Context context, AttributeSet attrs, ImageForm imageForm, int defStyle) { super(context, attrs, defStyle); this.imageForm = imageForm; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); if (getParent() != null) { getLayoutParams().height = widthMeasureSpec / imageForm.getDivider(); setMeasuredDimension(widthMeasureSpec, widthMeasureSpec / imageForm.getDivider()); } } }
Remove unused filter parameters from data request. Change-Id: Ic4e9f38a63dd99aa28d5faf28d392fb8b132141d
package com.vaadin.components.grid.config; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.js.JsProperty; import com.google.gwt.core.client.js.JsType; import com.vaadin.components.common.js.JSArray; /** * This class is a JsInterop wrapper for the JS object editor handler request. */ @JsType public interface JSDataRequest { @JsProperty int getIndex(); @JsProperty void setIndex(int index); @JsProperty int getCount(); @JsProperty void setCount(int count); @JsProperty JSArray<JSSortOrder> getSortOrder(); @JsProperty void setSortOrder(JSArray<JSSortOrder> sortOrder); @JsProperty JavaScriptObject getSuccess(); @JsProperty void setSuccess(JavaScriptObject success); @JsProperty JavaScriptObject getFailure(); @JsProperty void setFailure(JavaScriptObject failure); }
package com.vaadin.components.grid.config; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.js.JsProperty; import com.google.gwt.core.client.js.JsType; import com.vaadin.components.common.js.JSArray; /** * This class is a JsInterop wrapper for the JS object editor handler request. */ @JsType public interface JSDataRequest { @JsProperty int getIndex(); @JsProperty void setIndex(int index); @JsProperty int getCount(); @JsProperty void setCount(int count); @JsProperty JSArray<JSSortOrder> getSortOrder(); @JsProperty void setSortOrder(JSArray<JSSortOrder> sortOrder); @JsProperty JSArray<?> getFilterData(); @JsProperty void setFilterData(JSArray<?> filterData); @JsProperty JavaScriptObject getSuccess(); @JsProperty void setSuccess(JavaScriptObject success); @JsProperty JavaScriptObject getFailure(); @JsProperty void setFailure(JavaScriptObject failure); }
Refactor of jquery ajax call to fetch call
import React from 'react'; import './App.css'; import Inventory from './Inventory' var App = React.createClass({ getInitialState: function() { return { data: [] } }, componentWillMount: function() { return fetch('/api/shoe') .then((response) => response.json()) .then((data) => { console.log(data) this.setState({ data: data }); }) .catch((error) => { console.log(error) }); }, render: function() { return( <div className="Top-Selling-Items"> <Inventory items={this.state.data} /> </div> ) } }) export default App;
import React from 'react'; import $ from 'jquery' import './App.css'; import Inventory from './Inventory' var App = React.createClass({ getInitialState: function() { return { data: [] } }, componentWillMount: function() { $.ajax({ url: `/api/shoe`, dataType: "json", success: function(data) { this.setState({data: data}) }.bind(this), error: function(xhr, status, err) { console.error(this, status, err.toString()) }.bind(this) }) }, render: function() { return( <div className="Top-Selling-Items"> // {console.log(this.state.data, 'this.state.data')} <Inventory items={this.state.data} /> </div> ) } }) export default App;
Fix protocol and version parsing
<?php namespace Inkwell\HTTP\Gateway { use Inkwell\HTTP; use Inkwell\Transport; use Dotink\Flourish\Collection; class Server implements Transport\GatewayInterface { /** * */ public function populate($request) { $request->headers = new Collection(getallheaders()); $request->params = new Collection(array_merge($_GET, $_POST)); $request->cookies = new HTTP\CookieCollection($_COOKIE); list($protocol, $version) = explode('/', $_SERVER['SERVER_PROTOCOL']); $request->setMethod($_SERVER['REQUEST_METHOD']); $request->setProtocol($protocol); $request->setVersion($version); } /** * */ public function transport($response) { $this->prepareCookies($response); $this->prepareHeaders($response); } /** * */ private function prepareCookies($response) { foreach ($response->cookies as $name => $params) { settype($params, 'array'); array_unshift($params, $name); call_user_func_array('setcookie', $params); } } /** * */ private function prepareHeaders($response) { foreach ($response->headers as $name => $value) { header(sprintf('%s: %s', $name, $value)); } } } }
<?php namespace Inkwell\HTTP\Gateway { use Inkwell\HTTP; use Inkwell\Transport; use Dotink\Flourish\Collection; class Server implements Transport\GatewayInterface { /** * */ public function populate($request) { $request->headers = new Collection(getallheaders()); $request->params = new Collection(array_merge($_GET, $_POST)); $request->cookies = new HTTP\CookieCollection($_COOKIE); $request->setMethod($_SERVER['REQUEST_METHOD']); $request->setProtocol(substr($_SERVER['SERVER_PROTOCOL'], 0, strpos('/'))); $request->setVersion(substr($_SERVER['SERVER_PROTOCOL'], strpos('/') + 1)); } /** * */ public function transport($response) { $this->prepareCookies($response); $this->prepareHeaders($response); } /** * */ private function prepareCookies($response) { foreach ($response->cookies as $name => $params) { settype($params, 'array'); array_unshift($params, $name); call_user_func_array('setcookie', $params); } } /** * */ private function prepareHeaders($response) { foreach ($response->headers as $name => $value) { header(sprintf('%s: %s', $name, $value)); } } } }
plugins/defaults: Set permalink to false for posts
'use strict'; // Dependencies const cssnext = require('cssnext') const path = require('path') // Aliases var basedir = __dirname module.exports = { paths: { destination: path.join(basedir, 'dist'), source: path.join(basedir, 'src'), templates: path.join(basedir, 'templates') }, plugins: { defaults: { '*.md': { kind: 'page', template: 'page' }, 'posts/**/*.md': { kind: 'post', permalink: false, template: 'post' } }, postcss: [ cssnext() ] }, globals: { site: { title: 'Steffen Bruchmann’s Website' } } }
'use strict'; // Dependencies const cssnext = require('cssnext') const path = require('path') // Aliases var basedir = __dirname module.exports = { paths: { destination: path.join(basedir, 'dist'), source: path.join(basedir, 'src'), templates: path.join(basedir, 'templates') }, plugins: { defaults: { '*.md': { kind: 'page', template: 'page' }, 'posts/**/*.md': { kind: 'post', template: 'post' } }, postcss: [ cssnext() ] }, globals: { site: { title: 'Steffen Bruchmann’s Website' } } }
Make it a bit lighter
const crypto = require('crypto'); /** * memHandler - In memory upload handler * @param {object} options * @param {string} fieldname * @param {string} filename */ module.exports = function(options, fieldname, filename) { let buffers = []; let fileSize = 0; // eslint-disable-line let hash = crypto.createHash('md5'); const getBuffer = () => Buffer.concat(buffers); const emptyFunc = () => ''; return { dataHandler: function(data) { buffers.push(data); hash.update(data); fileSize += data.length; if (options.debug) { return console.log('Uploading %s -> %s, bytes: %d', fieldname, filename, fileSize); // eslint-disable-line } }, getBuffer: getBuffer, getFilePath: emptyFunc, getFileSize: function(){ return fileSize; }, getHash: function(){ return hash.digest('hex'); }, complete: getBuffer, cleanup: emptyFunc }; };
const crypto = require('crypto'); /** * memHandler - In memory upload handler * @param {object} options * @param {string} fieldname * @param {string} filename */ module.exports = function(options, fieldname, filename) { let buffers = []; let fileSize = 0; // eslint-disable-line let hash = crypto.createHash('md5'); return { dataHandler: function(data) { buffers.push(data); hash.update(data); fileSize += data.length; if (options.debug) { return console.log('Uploading %s -> %s, bytes: %d', fieldname, filename, fileSize); // eslint-disable-line } }, getBuffer: function(){ return Buffer.concat(buffers); }, getFilePath: function(){ return ''; }, getFileSize: function(){ return fileSize; }, getHash: function(){ return hash.digest('hex'); }, complete: function(){ return Buffer.concat(buffers); }, cleanup: function(){ } }; };
Fix client IDs for Web/iOS clients. - Updated the IOS_CLIENT_ID with its new value. - Reverted change to WEB_CLIENT_ID (accidently wrote the iOS client ID here in commit 891b02f) Change-Id: Iac3f79c35386ddd93ce5989e0a9cde1b837f6d8c
/* * Copyright 2017 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.iosched.server.userdata; /** * API keys. */ public class Ids { public static final String ANDROID_CLIENT_ID = "237695054204-m87hbqe20bqpib715p3hiddpjjfih2l9" + ".apps.googleusercontent.com"; public static final String IOS_CLIENT_ID = "596109260910-n1vrfjs8d7105jh5j7qf42ph32sltjp0" + ".apps.googleusercontent.com"; public static final String WEB_CLIENT_ID = "755839215930-ctkg839m67rtqmgm55c6eg1j7cvu5mmf" + ".apps.googleusercontent.com"; public static final String ANDROID_AUDIENCE = ANDROID_CLIENT_ID; }
/* * Copyright 2017 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.iosched.server.userdata; /** * API keys. */ public class Ids { public static final String ANDROID_CLIENT_ID = "237695054204-m87hbqe20bqpib715p3hiddpjjfih2l9" + ".apps.googleusercontent.com"; public static final String IOS_CLIENT_ID = "237695054204-pjm3begvj1k28pg88ncnacdi6gl5nbcf" + ".apps.googleusercontent.com"; public static final String WEB_CLIENT_ID = "596109260910-n1vrfjs8d7105jh5j7qf42ph32sltjp0" + ".apps.googleusercontent.com"; public static final String ANDROID_AUDIENCE = ANDROID_CLIENT_ID; }
Kill multiple chains at once.
import subprocess import sys import getpass ### Kill a job and its chain of dependents (as created by sbatch_submit). ### Usage: python sbatch_cancel.py [Name of first running job in chain] [Name of first running job in chain for a second chain] ... USER = getpass.getuser() lines = subprocess.check_output(['squeue', '-u', USER, '-o', '"%.8A %.20E"']) lines = lines.split('\n') lines.sort() for current_job in sys.argv[1].split(): if len(target_job) < 5: continue to_kill = [current_job] for line in lines: s = line.split() if (len(s) > 0) and (to_kill[-1] in s[2]): to_kill.append(s[1]) subprocess.call(['scancel'] + to_kill)
import subprocess import sys import getpass ### Kill a job and its chain of dependents (as created by sbatch_submit). ### Usage: python sbatch_cancel.py [Name of first running job in chain] CURRENT_JOB = sys.argv[1] USER = getpass.getuser() lines = subprocess.check_output(['squeue', '-u', USER, '-o', '"%.8A %.20E"']) lines = lines.split('\n') lines.sort() to_kill = [CURRENT_JOB] for line in lines: s = line.split() if (len(s) > 0) and (to_kill[-1] in s[2]): to_kill.append(s[1]) subprocess.call(['scancel'] + to_kill)
Use values also as array keys in return array, so that the Sonata Forms work
<?php namespace Tg\OkoaBundle\Util; use Doctrine\Common\Annotations\AnnotationReader; use Symfony\Component\Validator\Constraints as Assert; use ReflectionProperty; use Exception; /** * Annotation utility functions. */ class AnnotationUtil { /** * Get the options that are available for a property of a class * Options are only available if the @Assert\Choice annotation is set * @param string $propertyName The name of the property * @return [] An array of available options */ public static function getOptionsForField($className, $propertyName) { if(is_object($className)) { $className = get_class($className); } $reflectionProperty = new ReflectionProperty($className, $propertyName); $reader = new AnnotationReader(); $annotation = $reader->getPropertyAnnotation($reflectionProperty, 'Symfony\Component\Validator\Constraints\Choice'); if(!$annotation) { throw new Exception(sprintf("Property '%s' does not have a Choice annotation.", $propertyName)); } return array_combine($annotation->choices, $annotation->choices); } }
<?php namespace Tg\OkoaBundle\Util; use Doctrine\Common\Annotations\AnnotationReader; use Symfony\Component\Validator\Constraints as Assert; use ReflectionProperty; use Exception; /** * Annotation utility functions. */ class AnnotationUtil { /** * Get the options that are available for a property of a class * Options are only available if the @Assert\Choice annotation is set * @param string $propertyName The name of the property * @return [] An array of available options */ public static function getOptionsForField($className, $propertyName) { if(is_object($className)) { $className = get_class($className); } $reflectionProperty = new ReflectionProperty($className, $propertyName); $reader = new AnnotationReader(); $annotation = $reader->getPropertyAnnotation($reflectionProperty, 'Symfony\Component\Validator\Constraints\Choice'); if(!$annotation) { throw new Exception(sprintf("Property '%s' does not have a Choice annotation.", $propertyName)); } return $annotation->choices; } }
Make options argument to ol.style.Stroke optional
goog.provide('ol.style.Stroke'); goog.require('ol.color'); /** * @constructor * @param {olx.style.StrokeOptions=} opt_options Options. */ ol.style.Stroke = function(opt_options) { var options = goog.isDef(opt_options) ? opt_options : {}; /** * @type {ol.Color|string} */ this.color = goog.isDef(options.color) ? options.color : null; /** * @type {string|undefined} */ this.lineCap = options.lineCap; /** * @type {Array.<number>} */ this.lineDash = goog.isDef(options.lineDash) ? options.lineDash : null; /** * @type {string|undefined} */ this.lineJoin = options.lineJoin; /** * @type {number|undefined} */ this.miterLimit = options.miterLimit; /** * @type {number|undefined} */ this.width = options.width; };
goog.provide('ol.style.Stroke'); goog.require('ol.color'); /** * @constructor * @param {olx.style.StrokeOptions} options Options. */ ol.style.Stroke = function(options) { /** * @type {ol.Color|string} */ this.color = goog.isDef(options.color) ? options.color : null; /** * @type {string|undefined} */ this.lineCap = options.lineCap; /** * @type {Array.<number>} */ this.lineDash = goog.isDef(options.lineDash) ? options.lineDash : null; /** * @type {string|undefined} */ this.lineJoin = options.lineJoin; /** * @type {number|undefined} */ this.miterLimit = options.miterLimit; /** * @type {number|undefined} */ this.width = options.width; };
Add missing dependencies, new release (0.1.1).
#!/usr/bin/env python """Django/PostgreSQL implementation of the Meteor DDP service.""" import os.path from setuptools import setup, find_packages setup( name='django-ddp', version='0.1.1', description=__doc__, long_description=open('README.rst').read(), author='Tyson Clugg', author_email='tyson@clugg.net', url='https://github.com/commoncode/django-ddp', packages=find_packages(), include_package_data=True, install_requires=[ 'Django>=1.7', 'psycopg2>=2.5.4', 'gevent>=1.0', 'gevent-websocket>=0.9', 'meteor-ejson>=1.0', 'psycogreen>=1.0', ], classifiers=[ "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Topic :: Internet :: WWW/HTTP", ], )
#!/usr/bin/env python """Django/PostgreSQL implementation of the Meteor DDP service.""" import os.path from setuptools import setup, find_packages setup( name='django-ddp', version='0.1.0', description=__doc__, long_description=open('README.rst').read(), author='Tyson Clugg', author_email='tyson@clugg.net', url='https://github.com/commoncode/django-ddp', packages=find_packages(), include_package_data=True, install_requires=[ 'Django>=1.7', 'psycopg2>=2.5.4', ], classifiers=[ "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Topic :: Internet :: WWW/HTTP", ], )
Allow later patch versions of argcomplete Using ~ should install 1.12.1 if available (which it is) Specifically, we want the changes here: https://github.com/kislyuk/argcomplete/issues/321 importlib-metadata 2.0 was released, and argcomplete defined that 2.0 should never be use that version, until the most recent current version. I believe that one of our test dependencies imported a higher version of argcomplete before the resolver realised this. There is potentially another piece of work to NOT install test dependencies for users of servicemanager, but that can be postponed for now.
from setuptools import setup setup( name="servicemanager", version="2.0.7", description="A python tool to manage developing and testing with lots of microservices", url="https://github.com/hmrc/service-manager", author="hmrc-web-operations", license="Apache Licence 2.0", packages=[ "servicemanager", "servicemanager.actions", "servicemanager.server", "servicemanager.service", "servicemanager.thirdparty", ], install_requires=[ "requests~=2.24.0", "pymongo==3.11.0", "bottle==0.12.18", "pytest==5.4.3", "pyhamcrest==2.0.2", "argcomplete~=1.12.0", "prettytable==0.7.2" ], scripts=["bin/sm", "bin/smserver"], zip_safe=False, )
from setuptools import setup setup( name="servicemanager", version="2.0.6", description="A python tool to manage developing and testing with lots of microservices", url="https://github.com/hmrc/service-manager", author="hmrc-web-operations", license="Apache Licence 2.0", packages=[ "servicemanager", "servicemanager.actions", "servicemanager.server", "servicemanager.service", "servicemanager.thirdparty", ], install_requires=[ "requests~=2.24.0", "pymongo==3.11.0", "bottle==0.12.18", "pytest==5.4.3", "pyhamcrest==2.0.2", "argcomplete==1.12.0", "prettytable==0.7.2" ], scripts=["bin/sm", "bin/smserver"], zip_safe=False, )
Fix bug with array and object data
/** * Message for errors when some method is not implemented * @type {String} * @private */ var NEED_IMPLEMENT_MESSAGE = "This method need to implement"; /** * BaseHash class * @constructor */ function BaseHash(options) { if (!options) { throw new Error('You must provide data'); } if (Object.prototype.toString.call(options) === '[object Object]') { this.setData(options.data); } else { this.setData(options); } } BaseHash.prototype = Object.create({ constructor: BaseHash, /** * Get data from current hashing instance * @returns {*} */ getData: function () { return this._data; }, /** * Set data that need to hash * @param {*} data * @returns {BaseHash} */ setData: function (data) { this._data = data; return this; }, /** * Hash data */ hash: function () { throw new Error(NEED_IMPLEMENT_MESSAGE); } }); module.exports = BaseHash;
/** * Message for errors when some method is not implemented * @type {String} * @private */ var NEED_IMPLEMENT_MESSAGE = "This method need to implement"; /** * BaseHash class * @constructor */ function BaseHash(options) { if (typeof options === 'string') { this.setData(options); } else if (typeof options === 'object' && options.data) { this.setData(options.data); } else { throw new Error('You need provide data'); } } BaseHash.prototype = Object.create({ constructor: BaseHash, /** * Get data from current hashing instance * @returns {*} */ getData: function () { return this._data; }, /** * Set data that need to hash * @param {*} data * @returns {BaseHash} */ setData: function (data) { this._data = data; return this; }, /** * Hash data */ hash: function () { throw new Error(NEED_IMPLEMENT_MESSAGE); } }); module.exports = BaseHash;
Add wait() to login test with wrong credentials to fix WebDriver test
<?php use tests\_pages\LoginPage; $I = new WebGuy($scenario); $I->wantTo('ensure that login works'); $loginPage = LoginPage::openBy($I); $I->see('Login', 'h1'); $I->amGoingTo('try to login with empty credentials'); $loginPage->login('', ''); $I->expectTo('see validations errors'); $I->see('Username cannot be blank.'); $I->see('Password cannot be blank.'); $I->amGoingTo('try to login with wrong credentials'); $loginPage->login('admin', 'wrong'); if (method_exists($I, 'wait')) { $I->wait(3); // only for selenium } $I->expectTo('see validations errors'); $I->see('Incorrect username or password.'); $I->amGoingTo('try to login with correct credentials'); $loginPage->login('admin', 'admin'); if (method_exists($I, 'wait')) { $I->wait(3); // only for selenium } $I->expectTo('see user info'); $I->see('Logout (admin)');
<?php use tests\_pages\LoginPage; $I = new WebGuy($scenario); $I->wantTo('ensure that login works'); $loginPage = LoginPage::openBy($I); $I->see('Login', 'h1'); $I->amGoingTo('try to login with empty credentials'); $loginPage->login('', ''); $I->expectTo('see validations errors'); $I->see('Username cannot be blank.'); $I->see('Password cannot be blank.'); $I->amGoingTo('try to login with wrong credentials'); $loginPage->login('admin', 'wrong'); $I->expectTo('see validations errors'); $I->see('Incorrect username or password.'); $I->amGoingTo('try to login with correct credentials'); $loginPage->login('admin', 'admin'); if (method_exists($I, 'wait')) { $I->wait(3); // only for selenium } $I->expectTo('see user info'); $I->see('Logout (admin)');
Add more tests to validator number
<?php /* * This file is a part of the Validator library. * * (c) 2013 Ebidtech * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace EBT\Validator\Tests; use EBT\Validator\ValidatorNumber; /** * ValidatorNumberTest */ class ValidatorNumberTest extends TestCase { /** * @param mixed $value * @param int|float $min * @param int|float $max * @param bool $expected * * @dataProvider providerRanges */ public function testInRange($value, $min, $max, $expected) { $this->assertEquals($expected, ValidatorNumber::inRange($value, $min, $max)); } /** * @return array */ public function providerRanges() { return array( // value, min, max, expected, array(10, 5, 30, true), array(10, 20, 30, false), array(40, 20, 30, false), array(7.5, 2.5, 8, true) ); } }
<?php /* * This file is a part of the Validator library. * * (c) 2013 Ebidtech * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace EBT\Validator\Tests; use EBT\Validator\ValidatorNumber; /** * ValidatorNumberTest */ class ValidatorNumberTest extends TestCase { /** * @param mixed $value * @param int|float $min * @param int|float $max * @param bool $expected * * @dataProvider providerRanges */ public function testInRange($value, $min, $max, $expected) { $this->assertEquals($expected, ValidatorNumber::inRange($value, $min, $max)); } /** * @return array */ public function providerRanges() { return array( // value, min, max, expected, array(10, 5, 30, true) ); } }
Use the partner's online resource document for the resource: Rhododendron Images from Curtis Botanical Magazine.
<?php namespace php_active_record; /* connector for Royal Botanic Garden Edinburgh: Rhododendron Images from Curtis Botanical Magazine estimated execution time: There is already a published data for this resource that is set to 'import once'. The connector modifies the 339.xml in Beast. */ include_once(dirname(__FILE__) . "/../../config/environment.php"); $timestart = time_elapsed(); $resource_id = 339; //-------------- /* set rating to 2 */ require_library('ResourceDataObjectElementsSetting'); $resource_path = "http://data.rbge.org.uk/service/static/Rhododendron_curtis_images_eol_transfer.xml"; $func = new ResourceDataObjectElementsSetting($resource_id, $resource_path, 'http://purl.org/dc/dcmitype/StillImage', 2); $xml = $func->set_data_object_rating_on_xml_document(); $func->save_resource_document($xml); //-------------- Functions::set_resource_status_to_force_harvest($resource_id); $elapsed_time_sec = time_elapsed() - $timestart; echo "\n"; echo "elapsed time = $elapsed_time_sec seconds \n"; echo "elapsed time = " . $elapsed_time_sec/60 . " minutes \n"; echo "elapsed time = " . $elapsed_time_sec/60/60 . " hours \n"; exit("\n\n Done processing."); ?>
<?php namespace php_active_record; /* connector for Royal Botanic Garden Edinburgh: Rhododendron Images from Curtis Botanical Magazine estimated execution time: There is already a published data for this resource that is set to 'import once'. The connector modifies the 339.xml in Beast. */ include_once(dirname(__FILE__) . "/../../config/environment.php"); $timestart = time_elapsed(); $resource_id = 339; //-------------- /* set rating to 2 */ require_library('ResourceDataObjectElementsSetting'); $resource_path = CONTENT_RESOURCE_LOCAL_PATH . $resource_id . ".xml"; $func = new ResourceDataObjectElementsSetting($resource_id, $resource_path, 'http://purl.org/dc/dcmitype/StillImage', 2); $xml = $func->set_data_object_rating_on_xml_document(); $func->save_resource_document($xml); //-------------- Functions::set_resource_status_to_force_harvest($resource_id); $elapsed_time_sec = time_elapsed() - $timestart; echo "\n"; echo "elapsed time = $elapsed_time_sec seconds \n"; echo "elapsed time = " . $elapsed_time_sec/60 . " minutes \n"; echo "elapsed time = " . $elapsed_time_sec/60/60 . " hours \n"; exit("\n\n Done processing."); ?>
Fix data availability when installed via pip
#! /usr/bin/env python """TODO: Maybe add a docstring containing a long description This would double as something we could put int the `long_description` parameter for `setup` and it would squelch some complaints pylint has on `setup.py`. """ from setuptools import setup import os setup(name='demandlib', version='0.1', author='oemof developing group', url='http://github.com/oemof/demandlib', license='GPL3', author_email='oemof@rl-institut.de', description='Demandlib of the open energy modelling framework', packages=['demandlib'], package_dir={'demandlib': 'demandlib'}, package_data = { 'demandlib': [ os.path.join('bdew_data', 'selp_series.csv'), os.path.join('bdew_data', 'shlp_hour_factors.csv'), os.path.join('bdew_data', 'shlp_sigmoid_factors.csv'), os.path.join('bdew_data', 'shlp_weekday_factors.csv')]}, install_requires=['numpy >= 1.7.0', 'pandas >= 0.18.0'] )
#! /usr/bin/env python """TODO: Maybe add a docstring containing a long description This would double as something we could put int the `long_description` parameter for `setup` and it would squelch some complaints pylint has on `setup.py`. """ from setuptools import setup setup(name='demandlib', version='0.1', author='oemof developing group', url='http://github.com/oemof/demandlib', license='GPL3', author_email='oemof@rl-institut.de', description='Demandlib of the open energy modelling framework', packages=['demandlib'], package_dir={'demandlib': 'demandlib'}, install_requires=['numpy >= 1.7.0', 'pandas >= 0.18.0'] )
[MNG-6977] Use hyphen when creating builder threads (names)
package org.apache.maven.lifecycle.internal; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; /** * Simple {@link ThreadFactory} implementation that ensures the corresponding threads have a meaningful name. */ public class BuildThreadFactory implements ThreadFactory { private final AtomicInteger id = new AtomicInteger(); private static final String PREFIX = "BuilderThread"; public Thread newThread( Runnable r ) { return new Thread( r, String.format( "%s-%d", PREFIX, id.getAndIncrement() ) ); } }
package org.apache.maven.lifecycle.internal; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; /** * Simple {@link ThreadFactory} implementation that ensures the corresponding threads have a meaningful name. */ public class BuildThreadFactory implements ThreadFactory { private final AtomicInteger id = new AtomicInteger(); private static final String PREFIX = "BuilderThread"; public Thread newThread( Runnable r ) { return new Thread( r, String.format( "%s %d", PREFIX, id.getAndIncrement() ) ); } }
Use notifyAll() to update the period in blocked waitPeriod
package ru.nsu.ccfit.bogush.factory.thing.periodical; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class SimplePeriodical implements Periodical { private long period; private static final String LOGGER_NAME = "SimplePeriodical"; private static final Logger logger = LogManager.getLogger(LOGGER_NAME); public SimplePeriodical(long period) { this.period = period; } private final Object lock = new Object(); @Override public void setPeriod(long period) { logger.trace("set period " + period + " milliseconds"); if (period < 0) { logger.error("period < 0"); throw new IllegalArgumentException("period must be greater than or equal to 0"); } this.period = period; lock.notifyAll(); } @Override public void waitPeriod() { long timeToWait = period; long time = System.currentTimeMillis(); try { synchronized (lock) { while (timeToWait > 0) { lock.wait(timeToWait); long newTime = System.currentTimeMillis(); timeToWait -= newTime - time; time = newTime; } } } catch (InterruptedException e) { e.printStackTrace(); logger.error(e); System.exit(1); } } @Override public long getPeriod() { return period; } }
package ru.nsu.ccfit.bogush.factory.thing.periodical; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class SimplePeriodical implements Periodical { private long period; private static final String LOGGER_NAME = "SimplePeriodical"; private static final Logger logger = LogManager.getLogger(LOGGER_NAME); public SimplePeriodical(long period) { this.period = period; } private final Object lock = new Object(); @Override public void setPeriod(long period) { logger.trace("set period " + period + " milliseconds"); if (period < 0) { logger.error("period < 0"); throw new IllegalArgumentException("period must be greater than or equal to 0"); } this.period = period; } @Override public void waitPeriod() { long timeToWait = period; long time = System.currentTimeMillis(); try { synchronized (lock) { while (timeToWait > 0) { lock.wait(timeToWait); long newTime = System.currentTimeMillis(); timeToWait -= newTime - time; time = newTime; } } } catch (InterruptedException e) { e.printStackTrace(); logger.error(e); System.exit(1); } } @Override public long getPeriod() { return period; } }
Use proper characters for command descriptions
package command import ( "fmt" "time" "github.com/igungor/tlbot" ) func init() { register(cmdToday) } var cmdToday = &Command{ Name: "bugun", ShortLine: "bugün günlerden ne?", Run: runToday, } type weekday time.Weekday var days = [...]string{ "pazar", "pazartesi", "sali", "carsamba", "persembe", "cuma", "cumartesi", } func (w weekday) String() string { return days[w] } func runToday(b *tlbot.Bot, msg *tlbot.Message) { txt := fmt.Sprintf("bugün %v", weekday(time.Now().Weekday()).String()) b.SendMessage(msg.Chat, txt, tlbot.ModeNone, false, nil) }
package command import ( "fmt" "time" "github.com/igungor/tlbot" ) func init() { register(cmdToday) } var cmdToday = &Command{ Name: "bugun", ShortLine: "bugun gunlerden ne?", Run: runToday, } type weekday time.Weekday var days = [...]string{ "pazar", "pazartesi", "sali", "carsamba", "persembe", "cuma", "cumartesi", } func (w weekday) String() string { return days[w] } func runToday(b *tlbot.Bot, msg *tlbot.Message) { txt := fmt.Sprintf("bugün %v", weekday(time.Now().Weekday()).String()) b.SendMessage(msg.Chat, txt, tlbot.ModeNone, false, nil) }
Add documentation for assigned person
<?php namespace Arctic\Model\Inquiry; use Arctic\Model; /** * Class Inquiry * @property int $businessgroupid * @property int $id * @property string $personid * @property string $mode * @property string $notes * @property int $assignedagentid * @property int $assignedpersonid * @property int $tripid * @property string|null $followupon * @property \DateTime $createdon * @property \DateTime $modifiedon * @property \DateTime|null $followedupon * @property bool $deleted * @property \Arctic\Model\Trip\Trip $trip * @property \Arctic\Model\BusinessGroup $businessgroup * @property \Arctic\Model\Person\Person $person */ class Inquiry extends Model { public static function getApiPath() { return 'inquiry'; } public function __construct() { parent::__construct(); $this->_addSingleReference( 'businessgroup' , 'Arctic\Model\BusinessGroup' , array( 'businessgroupid' => 'id' ) ); $this->_addSingleReference( 'person' , 'Arctic\Model\Person\Person' , array( 'personid' => 'id' ) ); $this->_addSingleReference( 'trip' , 'Arctic\Model\Trip\Trip' , array( 'tripid' => 'id' ) ); } }
<?php namespace Arctic\Model\Inquiry; use Arctic\Model; /** * Class Inquiry * @property int $businessgroupid * @property int $id * @property string $personid * @property string $mode * @property string $notes * @property int $assignedagentid * @property int $tripid * @property string|null $followupon * @property \DateTime $createdon * @property \DateTime $modifiedon * @property \DateTime|null $followedupon * @property bool $deleted * @property \Arctic\Model\Trip\Trip $trip * @property \Arctic\Model\BusinessGroup $businessgroup * @property \Arctic\Model\Person\Person $person */ class Inquiry extends Model { public static function getApiPath() { return 'inquiry'; } public function __construct() { parent::__construct(); $this->_addSingleReference( 'businessgroup' , 'Arctic\Model\BusinessGroup' , array( 'businessgroupid' => 'id' ) ); $this->_addSingleReference( 'person' , 'Arctic\Model\Person\Person' , array( 'personid' => 'id' ) ); $this->_addSingleReference( 'trip' , 'Arctic\Model\Trip\Trip' , array( 'tripid' => 'id' ) ); } }
Revert "[Form] Remove "value" attribute on empty_value option" This reverts commit 9e849eb78bcc668a2b8aad39cb47e2ad32c73a47. Reasons for the revert: * https://github.com/symfony/symfony/issues/8478 * https://github.com/symfony/symfony/issues/8526
<select <?php echo $view['form']->block($form, 'widget_attributes') ?> <?php if ($multiple): ?> multiple="multiple"<?php endif ?> > <?php if (null !== $empty_value): ?><option value=""<?php if ($required):?> disabled="disabled"<?php if (empty($value) && "0" !== $value): ?> selected="selected"<?php endif ?><?php endif?>><?php echo $view->escape($view['translator']->trans($empty_value, array(), $translation_domain)) ?></option><?php endif; ?> <?php if (count($preferred_choices) > 0): ?> <?php echo $view['form']->block($form, 'choice_widget_options', array('choices' => $preferred_choices)) ?> <?php if (count($choices) > 0 && null !== $separator): ?> <option disabled="disabled"><?php echo $separator ?></option> <?php endif ?> <?php endif ?> <?php echo $view['form']->block($form, 'choice_widget_options', array('choices' => $choices)) ?> </select>
<select <?php echo $view['form']->block($form, 'widget_attributes') ?> <?php if ($multiple): ?> multiple="multiple"<?php endif ?> > <?php if (null !== $empty_value): ?><option <?php if ($required):?> disabled="disabled"<?php if (empty($value) && "0" !== $value): ?> selected="selected"<?php endif ?><?php else: ?> value=""<?php endif?>><?php echo $view->escape($view['translator']->trans($empty_value, array(), $translation_domain)) ?></option><?php endif; ?> <?php if (count($preferred_choices) > 0): ?> <?php echo $view['form']->block($form, 'choice_widget_options', array('choices' => $preferred_choices)) ?> <?php if (count($choices) > 0 && null !== $separator): ?> <option disabled="disabled"><?php echo $separator ?></option> <?php endif ?> <?php endif ?> <?php echo $view['form']->block($form, 'choice_widget_options', array('choices' => $choices)) ?> </select>
Disable the "draw properties" benchmark We'd still like to be able to run this benchmark manually, but we don't need it to be run automatically. BUG=None CQ_EXTRA_TRYBOTS=tryserver.chromium.perf:linux_perf_bisect;tryserver.chromium.perf:mac_perf_bisect;tryserver.chromium.perf:win_perf_bisect;tryserver.chromium.perf:android_nexus5_perf_bisect Review URL: https://codereview.chromium.org/1202383004 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#336012}
# Copyright 2015 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. from core import perf_benchmark from measurements import draw_properties from telemetry import benchmark import page_sets # This benchmark depends on tracing categories available in M43 # This benchmark is still useful for manual testing, but need not be enabled # and run regularly. @benchmark.Disabled() class DrawPropertiesToughScrolling(perf_benchmark.PerfBenchmark): test = draw_properties.DrawProperties page_set = page_sets.ToughScrollingCasesPageSet @classmethod def Name(cls): return 'draw_properties.tough_scrolling' # This benchmark depends on tracing categories available in M43 # This benchmark is still useful for manual testing, but need not be enabled # and run regularly. @benchmark.Disabled() class DrawPropertiesTop25(perf_benchmark.PerfBenchmark): """Measures the performance of computing draw properties from property trees. http://www.chromium.org/developers/design-documents/rendering-benchmarks """ test = draw_properties.DrawProperties page_set = page_sets.Top25SmoothPageSet @classmethod def Name(cls): return 'draw_properties.top_25'
# Copyright 2015 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. from core import perf_benchmark from measurements import draw_properties from telemetry import benchmark import page_sets # This benchmark depends on tracing categories available in M43 @benchmark.Disabled('reference') class DrawPropertiesToughScrolling(perf_benchmark.PerfBenchmark): test = draw_properties.DrawProperties page_set = page_sets.ToughScrollingCasesPageSet @classmethod def Name(cls): return 'draw_properties.tough_scrolling' # This benchmark depends on tracing categories available in M43 @benchmark.Disabled('reference','win') # http://crbug.com/463111 class DrawPropertiesTop25(perf_benchmark.PerfBenchmark): """Measures the performance of computing draw properties from property trees. http://www.chromium.org/developers/design-documents/rendering-benchmarks """ test = draw_properties.DrawProperties page_set = page_sets.Top25SmoothPageSet @classmethod def Name(cls): return 'draw_properties.top_25'
Revert target dao key to non-local groupPermissionJunctionDAO
/** * @license * Copyright 2017 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ foam.RELATIONSHIP({ cardinality: '*:*', sourceModel: 'foam.nanos.auth.Group', targetModel: 'foam.nanos.auth.Permission', forwardName: 'permissions', inverseName: 'groups', junctionDAOKey: 'groupPermissionJunctionDAO' }); /* foam.RELATIONSHIP({ cardinality: '*:*', sourceModel: 'foam.nanos.auth.User', targetModel: 'foam.nanos.auth.Group', forwardName: 'groups', inverseName: 'users', sourceProperty: { hidden: true }, targetProperty: { hidden: true } }); */ foam.RELATIONSHIP({ sourceModel: 'foam.nanos.theme.Theme', targetModel: 'foam.nanos.auth.User', cardinality: '1:*', forwardName: 'users', inverseName: 'personalTheme', sourceProperty: { hidden: true, visibility: 'HIDDEN' } });
/** * @license * Copyright 2017 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ foam.RELATIONSHIP({ cardinality: '*:*', sourceModel: 'foam.nanos.auth.Group', targetModel: 'foam.nanos.auth.Permission', forwardName: 'permissions', inverseName: 'groups', junctionDAOKey: 'localGroupPermissionJunctionDAO' }); /* foam.RELATIONSHIP({ cardinality: '*:*', sourceModel: 'foam.nanos.auth.User', targetModel: 'foam.nanos.auth.Group', forwardName: 'groups', inverseName: 'users', sourceProperty: { hidden: true }, targetProperty: { hidden: true } }); */ foam.RELATIONSHIP({ sourceModel: 'foam.nanos.theme.Theme', targetModel: 'foam.nanos.auth.User', cardinality: '1:*', forwardName: 'users', inverseName: 'personalTheme', sourceProperty: { hidden: true, visibility: 'HIDDEN' } });
Fix a bug when Stop button does not behaves as expected in selected browsers (Firefox, Opera) Windows 7 64 bit Opera 12.11 Firefox 16.0.2
(function($) { $.extend(mejs.MepDefaults, { stopText: 'Stop' }); // STOP BUTTON $.extend(MediaElementPlayer.prototype, { buildstop: function(player, controls, layers, media) { var t = this, stop = $('<div class="mejs-button mejs-stop-button mejs-stop">' + '<button type="button" aria-controls="' + t.id + '" title="' + t.options.stopText + '"></button>' + '</div>') .appendTo(controls) .click(function() { if (!media.paused) { media.pause(); } if (media.currentTime > 0) { media.setCurrentTime(0); media.pause(); controls.find('.mejs-time-current').width('0px'); controls.find('.mejs-time-handle').css('left', '0px'); controls.find('.mejs-time-float-current').html( mejs.Utility.secondsToTimeCode(0) ); controls.find('.mejs-currenttime').html( mejs.Utility.secondsToTimeCode(0) ); layers.find('.mejs-poster').show(); } }); } }); })(mejs.$);
(function($) { $.extend(mejs.MepDefaults, { stopText: 'Stop' }); // STOP BUTTON $.extend(MediaElementPlayer.prototype, { buildstop: function(player, controls, layers, media) { var t = this, stop = $('<div class="mejs-button mejs-stop-button mejs-stop">' + '<button type="button" aria-controls="' + t.id + '" title="' + t.options.stopText + '"></button>' + '</div>') .appendTo(controls) .click(function() { if (!media.paused) { media.pause(); } if (media.currentTime > 0) { media.setCurrentTime(0); controls.find('.mejs-time-current').width('0px'); controls.find('.mejs-time-handle').css('left', '0px'); controls.find('.mejs-time-float-current').html( mejs.Utility.secondsToTimeCode(0) ); controls.find('.mejs-currenttime').html( mejs.Utility.secondsToTimeCode(0) ); layers.find('.mejs-poster').show(); } }); } }); })(mejs.$);
Add some test geometry which includes file node.
# -*- coding: utf-8 -*- #------------------------------------------------------------------------------- ## Description """ Define file for Cache Manager Tool. """ #------------------------------------------------------------------------------- ## Define Cache Nodes to deal with this script. CACHE_NODES = [ {"name":"file", "parmName":"file"}, {"name":"filecache", "parmName":"file"}, {"name":"alembic", "parmName":"fileName"}, {"name":"alembicarchive", "parmName":"fileName"}, {"name":"dopio", "parmName":"file"}, ] CHILDNODES_EXCEPTION = [ "filecache", "dopio", "df_alembic_import", ] DEBUG_MODE = False ## Define Houdini Environment Varialbes. This will also be used for displaying. ENV_TYPE = [ '-', 'HIP', 'JOB', ] ## Menu Items. MENU_HELP = "Help" MENU_RELOAD = "Reload" ## Listed CHACHE_NODES node has children which should be got rid of as default. NODES_EXCEPTION = [ "light", "hlight", "ambient", "indirectlight", "arnold_light", "cam", "testgeometry_pighead", "testgeometry_rubbertoy", "testgeometry_squab", "testgeometry_ragdoll", ] #------------------------------------------------------------------------------- # EOF #-------------------------------------------------------------------------------
# -*- coding: utf-8 -*- #------------------------------------------------------------------------------- ## Description """ Define file for Cache Manager Tool. """ #------------------------------------------------------------------------------- ## Define Cache Nodes to deal with this script. CACHE_NODES = [ {"name":"file", "parmName":"file"}, {"name":"filecache", "parmName":"file"}, {"name":"alembic", "parmName":"fileName"}, {"name":"alembicarchive", "parmName":"fileName"}, {"name":"dopio", "parmName":"file"}, ] CHILDNODES_EXCEPTION = [ "filecache", "dopio", "df_alembic_import", ] DEBUG_MODE = False ## Define Houdini Environment Varialbes. This will also be used for displaying. ENV_TYPE = [ '-', 'HIP', 'JOB', ] ## Menu Items. MENU_HELP = "Help" MENU_RELOAD = "Reload" ## Listed CHACHE_NODES node has children which should be got rid of as default. NODES_EXCEPTION = [ "light", "hlight", "ambient", "indirectlight", "arnold_light", "cam", ] #------------------------------------------------------------------------------- # EOF #-------------------------------------------------------------------------------
Add allow_timelog to task type model
from sqlalchemy_utils import UUIDType from zou.app import db from zou.app.models.serializer import SerializerMixin from zou.app.models.base import BaseMixin class TaskType(db.Model, BaseMixin, SerializerMixin): """ Categorize tasks in domain areas: modeling, animation, etc. """ name = db.Column(db.String(40), nullable=False) short_name = db.Column(db.String(20)) color = db.Column(db.String(7), default="#FFFFFF") priority = db.Column(db.Integer, default=1) for_shots = db.Column(db.Boolean, default=False) for_entity = db.Column(db.String(30), default="Asset") allow_timelog = db.Column(db.Boolean, default=True) shotgun_id = db.Column(db.Integer, index=True) department_id = db.Column( UUIDType(binary=False), db.ForeignKey("department.id") ) __table_args__ = ( db.UniqueConstraint( 'name', 'for_entity', 'department_id', name='task_type_uc' ), )
from sqlalchemy_utils import UUIDType from zou.app import db from zou.app.models.serializer import SerializerMixin from zou.app.models.base import BaseMixin class TaskType(db.Model, BaseMixin, SerializerMixin): """ Categorize tasks in domain areas: modeling, animation, etc. """ name = db.Column(db.String(40), nullable=False) short_name = db.Column(db.String(20)) color = db.Column(db.String(7), default="#FFFFFF") priority = db.Column(db.Integer, default=1) for_shots = db.Column(db.Boolean, default=False) for_entity = db.Column(db.String(30), default="Asset") shotgun_id = db.Column(db.Integer, index=True) department_id = db.Column( UUIDType(binary=False), db.ForeignKey("department.id") ) __table_args__ = ( db.UniqueConstraint( 'name', 'for_entity', 'department_id', name='task_type_uc' ), )
Implement boolean option flags and change TypeDoc path strategy
module.exports = function (grunt) { 'use strict'; grunt.registerMultiTask('typedoc', 'Generate TypeScript docs', function () { var options = this.options({}); var args = []; for (var key in options) { if (options.hasOwnProperty(key) && (typeof options[key] !== "boolean" || options[key])) { args.push('--' + key); if (typeof options[key] !== "boolean" && !!options[key]) { args.push(options[key]); } } } for (var i = 0; i < this.filesSrc.length; i++) { args.push(this.filesSrc[i]); } // lazy init var path = require('path'); var child_process = require('child_process'); var typedoc; try { typedoc = require.resolve('../../typedoc/package.json'); } catch(e) { typedoc = require.resolve('typedoc/package.json') } var winExt = /^win/.test(process.platform) ? '.cmd' : ''; var done = this.async(); var executable = path.resolve(typedoc, '..', '..', '.bin', 'typedoc' + winExt); var child = child_process.spawn(executable, args, { stdio: 'inherit', env: process.env }).on('exit', function (code) { if (code !== 0) { done(false); } if (child) { child.kill(); } done(); }); }); };
module.exports = function (grunt) { 'use strict'; grunt.registerMultiTask('typedoc', 'Generate TypeScript docs', function () { var options = this.options({}); var args = []; for (var key in options) { if (options.hasOwnProperty(key)) { args.push('--' + key); if (!!options[key]) { args.push(options[key]); } } } for (var i = 0; i < this.filesSrc.length; i++) { args.push(this.filesSrc[i]); } // lazy init var path = require('path'); var child_process = require('child_process'); var winExt = /^win/.test(process.platform) ? '.cmd' : ''; var done = this.async(); var executable = path.resolve(require.resolve('typedoc/package.json'), '..', '..', '.bin', 'typedoc' + winExt); var child = child_process.spawn(executable, args, { stdio: 'inherit', env: process.env }).on('exit', function (code) { if (code !== 0) { done(false); } if (child) { child.kill(); } done(); }); }); };
Fix "ReferenceError: Bob is not defined" for correct use of module.exports
var Bob = require('./bob'); describe("Bob", function() { var bob = new Bob(); it("stating something", function() { var result = bob.hey('Tom-ay-to, tom-aaaah-to.'); expect(result).toEqual('Whatever.'); }); xit("shouting", function() { var result = bob.hey('WATCH OUT!'); expect(result).toEqual('Woah, chill out!'); }); xit("asking a question", function() { var result = bob.hey('Does this cryogenic chamber make me look fat?'); expect(result).toEqual('Sure.'); }); xit("talking forcefully", function() { var result = bob.hey("Let's go make out behind the gym!"); expect(result).toEqual('Whatever.'); }); xit("shouting numbers", function() { var result = bob.hey('1, 2, 3 GO!'); expect(result).toEqual('Woah, chill out!'); }); xit("shouting with special characters", function() { var result = bob.hey('ZOMG THE %^*@#$(*^ ZOMBIES ARE COMING!!11!!1!'); expect(result).toEqual('Woah, chill out!'); }); xit("silence", function() { var result = bob.hey(''); expect(result).toEqual('Fine, be that way!'); }); });
require('./bob'); describe("Bob", function() { var bob = new Bob(); it("stating something", function() { var result = bob.hey('Tom-ay-to, tom-aaaah-to.'); expect(result).toEqual('Whatever.'); }); xit("shouting", function() { var result = bob.hey('WATCH OUT!'); expect(result).toEqual('Woah, chill out!'); }); xit("asking a question", function() { var result = bob.hey('Does this cryogenic chamber make me look fat?'); expect(result).toEqual('Sure.'); }); xit("talking forcefully", function() { var result = bob.hey("Let's go make out behind the gym!"); expect(result).toEqual('Whatever.'); }); xit("shouting numbers", function() { var result = bob.hey('1, 2, 3 GO!'); expect(result).toEqual('Woah, chill out!'); }); xit("shouting with special characters", function() { var result = bob.hey('ZOMG THE %^*@#$(*^ ZOMBIES ARE COMING!!11!!1!'); expect(result).toEqual('Woah, chill out!'); }); xit("silence", function() { var result = bob.hey(''); expect(result).toEqual('Fine, be that way!'); }); });
Update readme and check for no data
const path = require('path'); const url = require('url'); const jade = require('jade'); module.exports = function(route, root, data, options, err) { try { root = root || '.'; options = options || {}; var routed = path.normalize(url.parse(route).pathname); if (routed[routed.length - 1] === '/') { routed += "index"; } const filename = path.basename(routed); const template = jade.compileFile(root + routed + '.jade', options); if (data) { return template(data[filename].locals); } else { return template(); } } catch(e) { typeof err === 'function' && err(e); } };
const path = require('path'); const url = require('url'); const jade = require('jade'); module.exports = function(route, root, data, options, err) { try { root = root || '.'; options = options || {}; var routed = path.normalize(url.parse(route).pathname); if (routed[routed.length - 1] === '/') { routed += "index"; } const filename = path.basename(routed); const template = jade.compileFile(root + routed + '.jade', options); return template(data[filename].locals); } catch(e) { typeof err === 'function' && err(e); } };
Allow normal user create disk offering. picked from Yaoning Li.
package org.zstack.header.configuration; import org.zstack.header.identity.rbac.RBACDescription; public class RBACInfo implements RBACDescription { @Override public void permissions() { permissionBuilder() .name("configuration") .adminOnlyAPIs("org.zstack.header.configuration.**") .targetResources(InstanceOfferingVO.class, DiskOfferingVO.class) .normalAPIs(APIQueryDiskOfferingMsg.class, APIQueryInstanceOfferingMsg.class, APICreateDiskOfferingMsg.class) .build(); } @Override public void contributeToRoles() { } @Override public void roles() { roleBuilder() .name("configuration") .uuid("067c4dc358e847aba47903ca4fb1c41c") .permissionsByName("configuration") .build(); } @Override public void globalReadableResources() { } }
package org.zstack.header.configuration; import org.zstack.header.identity.rbac.RBACDescription; public class RBACInfo implements RBACDescription { @Override public void permissions() { permissionBuilder() .name("configuration") .adminOnlyAPIs("org.zstack.header.configuration.**") .targetResources(InstanceOfferingVO.class, DiskOfferingVO.class) .normalAPIs(APIQueryDiskOfferingMsg.class, APIQueryInstanceOfferingMsg.class) .build(); } @Override public void contributeToRoles() { } @Override public void roles() { roleBuilder() .name("configuration") .uuid("067c4dc358e847aba47903ca4fb1c41c") .permissionsByName("configuration") .build(); } @Override public void globalReadableResources() { } }
Fix return types to return correct number of values
package copy import ( "strings" ) // Use the object Meta from files (move to other file?) type LinkService struct { client *Client } var ( // Links paths linksTopLevelSuffix = "links" linksGetSuffix = strings.Join([]string{linksTopLevelSuffix, "%v"}, "/") // https://.../links/TOKEN ) func NewLinkService(client *Client) *LinkService { fs := new(LinkService) fs.client = client return fs } func (ls *LinkService) GetLink(token string) (*Meta, error) { return nil, nil } func (ls *LinkService) GetLinks() ([]Meta, error) { return nil, nil } func (ls *LinkService) CreateLink(name string, paths []string, public bool) error { return nil } func (ls *LinkService) AddPaths(token string, paths []string) error { return nil } func (ls *LinkService) AddRecipients(token string, recipients []Recipient) error { return nil } func (ls *LinkService) DeleteLink(token string) error { return nil } func (ls *LinkService) GetFilesMetaFromLink(token string) (*Meta, error) { return nil, nil }
package copy import ( "strings" ) // Use the object Meta from files (move to other file?) type LinkService struct { client *Client } var ( // Links paths linksTopLevelSuffix = "links" linksGetSuffix = strings.Join([]string{linksTopLevelSuffix, "%v"}, "/") // https://.../links/TOKEN ) func NewLinkService(client *Client) *LinkService { fs := new(LinkService) fs.client = client return fs } func (ls *LinkService) GetLink(token string) (*Meta, error) { return nil, nil } func (ls *LinkService) GetLinks() ([]Meta, error) { return nil, nil } func (ls *LinkService) CreateLink(name string, paths []string, public bool) error { return nil, nil } func (ls *LinkService) AddPaths(token string, paths []string) error { return nil, nil } func (ls *LinkService) AddRecipients(token string, recipients []Recipient) error { return nil, nil } func (ls *LinkService) DeleteLink(token string) error { return nil, nil } func (ls *LinkService) GetFilesMetaFromLink(token string) (*Meta, error) { return nil, nil }