text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix en generador de código de módulo ADC
goog.require('Blockly.JavaScript'); Blockly.JavaScript['adc_done'] = function(block) { var code = 'adc_done()'; return [code, Blockly.JavaScript.ORDER_NONE + '\n'] }; Blockly.JavaScript['adc_read'] = function(block) { var option = block.getFieldValue('ADCoptions'); var code = 'read_adc(' + option +')'; if (block.outputConnection) { if ( option === 'ADC_START_AND_READ') return ['read_adc()' , Blockly.JavaScript.ORDER_NONE + '\n']; return [code, Blockly.JavaScript.ORDER_NONE + '\n']; } else { return code + ';\n'; } }; Blockly.JavaScript['adc_channel'] = function(block) { var channel = block.getFieldValue('channel'); var code = 'set_adc_channel(' + channel +');\n'; return code; }; Blockly.JavaScript['adc_setup'] = function(block) { var option = block.getFieldValue('CLOCKoptions'); var code = 'setup_adc(' + option +');\n'; return code; };
goog.require('Blockly.JavaScript'); Blockly.JavaScript['adc_done'] = function(block) { var code = 'adc_done()'; return [code, Blockly.JavaScript.ORDER_NONE]; }; Blockly.JavaScript['adc_read'] = function(block) { // var option = block.getFieldValue('ADCoptions'); // var code = 'read_adc(' + option +');\n'; // if(option == 'ADC_START_AND_READ') { // code = 'read_adc();\n'; // } // if(block.outputConnection) { // return [code, Blockly.JavaScript.ORDER_NONE]; // } else { // return code; // } if(block.outputConnection) { return "I have an output"; } else { return "I don't have an output"; } }; Blockly.JavaScript['adc_channel'] = function(block) { var channel = block.getFieldValue('channel'); var code = 'set_adc_channel(' + channel +');\n'; return code; }; Blockly.JavaScript['adc_setup'] = function(block) { var option = block.getFieldValue('CLOCKoptions'); var code = 'setup_adc(' + option +');\n'; return code; };
Add missing method to no-op artifact
/* * Copyright 2017. nekocode (nekocode.cn@gmail.com) * * 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 cn.nekocode.resinspector; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RestrictTo; import android.view.View; /** * @author nekocode (nekocode.cn@gmail.com) */ public class ResourceInspector { @NonNull public static Context wrap(@NonNull Context base) { return base; } @RestrictTo(RestrictTo.Scope.LIBRARY) public static boolean isViewBeingInspected(@Nullable View view) { return false; } @RestrictTo(RestrictTo.Scope.LIBRARY) @Nullable public static String getViewLayoutResName(@Nullable View view) { return null; } public static void initialize(@NonNull final Context context) { } }
/* * Copyright 2017. nekocode (nekocode.cn@gmail.com) * * 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 cn.nekocode.resinspector; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RestrictTo; import android.view.View; /** * @author nekocode (nekocode.cn@gmail.com) */ public class ResourceInspector { @NonNull public static Context wrap(@NonNull Context base) { return base; } @RestrictTo(RestrictTo.Scope.LIBRARY) public static boolean isViewBeingInspected(@Nullable View view) { return false; } @RestrictTo(RestrictTo.Scope.LIBRARY) @Nullable public static String getViewLayoutResName(@Nullable View view) { return null; } }
Fix mistaken comment in test
'use strict'; var jf = require('../../'), expect = require('chai').expect, fs = require('fs'); const testFilePath = './' + Math.random() + '.json'; describe('newFile executer', function () { it('should create new file and if already exists, raise error.', function (done) { jf .newFile( testFilePath ) .io( function( obj ) { expect(obj).to.eql(jf.initialValue()); } ) .pass( () => { jf .newFile( testFilePath, function( err ){ expect( err ).to.be.an.instanceof( jf.JsonFiledError ); done(); } ) .exec(); }) .exec(); }); });
'use strict'; var jf = require('../../'), expect = require('chai').expect, fs = require('fs'); const testFilePath = './' + Math.random() + '.json'; describe('The initialValue', function () { it('should be equal to defined in json.filed.', function (done) { jf .newFile( testFilePath ) .io( function( obj ) { expect(obj).to.eql(jf.initialValue()); } ) .pass( () => { jf .newFile( testFilePath, function( err ){ expect( err ).to.be.an.instanceof( jf.JsonFiledError ); done(); } ) .exec(); }) .exec(); }); });
Add support for text based LongArrayTextReference
package net.openhft.chronicle.bytes; public interface ByteStringAppender<B extends ByteStringAppender<B>> extends StreamingDataOutput<B> { default B append(char ch) { BytesUtil.appendUTF(this, ch); return (B) this; } default B append(CharSequence cs) { return append(cs, 0, cs.length()); } default B append(long value) { BytesUtil.append(this, value); return (B) this; } default B append(float f) { BytesUtil.append(this, f); return (B) this; } default B append(double d) { BytesUtil.append(this, d); return (B) this; } default B append(CharSequence cs, int start, int end) { BytesUtil.appendUTF(this, cs, start, end - start); return (B) this; } default B append(long value, int digits) { BytesUtil.append((RandomDataOutput) this, position(), value, digits); this.skip(digits); return (B) this; } }
package net.openhft.chronicle.bytes; public interface ByteStringAppender<B extends ByteStringAppender<B>> extends StreamingDataOutput<B> { default B append(char ch) { BytesUtil.appendUTF(this, ch); return (B) this; } default B append(CharSequence cs) { return append(cs, 0, cs.length()); } default B append(long value) { BytesUtil.append(this, value); return (B) this; } default B append(float f) { BytesUtil.append(this, f); return (B) this; } default B append(double d) { BytesUtil.append(this, d); return (B) this; } default B append(CharSequence cs, int start, int end) { BytesUtil.appendUTF(this, cs, start, end - start); return (B) this; } }
USe git Python Social Auth to get Fedora nicknames
#!/usr/bin/env python from setuptools import setup setup( name='Dapi', version='1.0', description='DevAssistant Package Index', author='Miro Hroncok', author_email='mhroncok@redhat.com', url='https://github.com/hroncok/dapi', license='AGPLv3', install_requires=[ 'Django==1.6', 'psycopg2', 'South', 'daploader>=0.0.4', 'PyYAML', 'python-social-auth==c5dd3339', 'django-taggit', 'django-simple-captcha', 'django-haystack', 'whoosh', 'djangorestframework==03b4c60b', 'django-gravatar2', ], dependency_links = [ 'git+git://github.com/omab/python-social-auth.git@c5dd3339#egg=python-social-auth-c5dd3339', 'git+git://github.com/tomchristie/django-rest-framework.git@03b4c60b#egg=djangorestframework-03b4c60b', ] )
#!/usr/bin/env python from setuptools import setup setup( name='Dapi', version='1.0', description='DevAssistant Package Index', author='Miro Hroncok', author_email='mhroncok@redhat.com', url='https://github.com/hroncok/dapi', license='AGPLv3', install_requires=[ 'Django==1.6', 'psycopg2', 'South', 'daploader>=0.0.4', 'PyYAML', 'python-social-auth', 'django-taggit', 'django-simple-captcha', 'django-haystack', 'whoosh', 'djangorestframework==03b4c60b', 'django-gravatar2', ], dependency_links = [ 'git+git://github.com/tomchristie/django-rest-framework.git@03b4c60b#egg=djangorestframework-03b4c60b', ] )
Fix config syntax error when deploying
package g import ( "time" ) // changelog: // 3.1.3: code refactor // 3.1.4: bugfix ignore configuration // 5.0.0: 支持通过配置控制是否开启/run接口;收集udp流量数据;du某个目录的大小 // 5.1.0: 同步插件的时候不再使用checksum机制 // 5.1.3: Fix config syntax error when deploying const ( VERSION = "5.1.3" COLLECT_INTERVAL = time.Second URL_CHECK_HEALTH = "url.check.health" NET_PORT_LISTEN = "net.port.listen" DU_BS = "du.bs" PROC_NUM = "proc.num" )
package g import ( "time" ) // changelog: // 3.1.3: code refactor // 3.1.4: bugfix ignore configuration // 5.0.0: 支持通过配置控制是否开启/run接口;收集udp流量数据;du某个目录的大小 // 5.1.0: 同步插件的时候不再使用checksum机制 const ( VERSION = "5.1.2" COLLECT_INTERVAL = time.Second URL_CHECK_HEALTH = "url.check.health" NET_PORT_LISTEN = "net.port.listen" DU_BS = "du.bs" PROC_NUM = "proc.num" )
Use call_user_func_array so we can pass options to faker
<?php namespace League\FactoryMuffin\Kind; use InvalidArgumentException; use League\FactoryMuffin\Kind; /** * Class Generic. * * @package League\FactoryMuffin\Kind * @author Zizaco <zizaco@gmail.com> * @author Scott Robertson <scottymeuk@gmail.com> * @author Graham Campbell <graham@mineuk.com> * @license <https://github.com/thephpleague/factory-muffin/blob/master/LICENSE> MIT */ class Generic extends Kind { /** * Generate, and return the attribute. * * We attempt to use Faker for any string passed in. * If a Faker property does not exist, we'll return the original string. * * @return mixed */ public function generate() { // Only try and use Faker when there are no spaces in the string if (!is_string($this->getKind()) or strpos($this->getKind(), ' ') !== false) { return $this->getKind(); } // If it fails to call it, it must not be a real thing try { return call_user_func_array(array($this->faker, $this->getKind()), $this->getOptions()); } catch (InvalidArgumentException $e) { } // Just return the literal string return $this->getKind(); } }
<?php namespace League\FactoryMuffin\Kind; use InvalidArgumentException; use League\FactoryMuffin\Kind; /** * Class Generic. * * @package League\FactoryMuffin\Kind * @author Zizaco <zizaco@gmail.com> * @author Scott Robertson <scottymeuk@gmail.com> * @author Graham Campbell <graham@mineuk.com> * @license <https://github.com/thephpleague/factory-muffin/blob/master/LICENSE> MIT */ class Generic extends Kind { /** * Generate, and return the attribute. * * We attempt to use Faker for any string passed in. * If a Faker property does not exist, we'll return the original string. * * @return mixed */ public function generate() { // Only try and use Faker when there are no spaces in the string if (!is_string($this->getKind()) or strpos($this->getKind(), ' ') !== false) { return $this->getKind(); } // If it fails to call it, it must not be a real thing try { return call_user_func_array(array($this->faker, $this->kind), $this->getOptions()); } catch (InvalidArgumentException $e) { } // Just return the literal string return $this->getKind(); } }
Change dist folder to match after move
/** * Created by v0n000p on 2/19/17. */ const path = require('path'); const webpack = require('webpack'); const isProduction = (process.env.NODE_ENV === 'production'); console.log('isProduction', isProduction); const plugins = []; const loaders = [ { test: /\.tsx?$/, loader: 'ts-loader' } ]; if(isProduction){ plugins.push( new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }) ) }else { } module.exports = { entry: path.resolve(__dirname, './src/containers/index.ts'), output: { path: path.resolve(__dirname, './dist'), filename: '[name].js' }, resolve: { // Add `.ts` and `.tsx` as a resolvable extension. extensions: ['.ts', '.tsx', '.js'] // note if using webpack 1 you'd also need a '' in the array as well }, module:{ loaders:loaders }, plugins:plugins };
/** * Created by v0n000p on 2/19/17. */ const path = require('path'); const webpack = require('webpack'); const isProduction = (process.env.NODE_ENV === 'production'); console.log('isProduction', isProduction); const plugins = []; const loaders = [ { test: /\.tsx?$/, loader: 'ts-loader' } ]; if(isProduction){ plugins.push( new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }) ) }else { } module.exports = { entry: path.resolve(__dirname, '../src/containers/index.ts'), output: { path: path.resolve(__dirname, '../dist'), filename: '[name].js' }, resolve: { // Add `.ts` and `.tsx` as a resolvable extension. extensions: ['.ts', '.tsx', '.js'] // note if using webpack 1 you'd also need a '' in the array as well }, module:{ loaders:loaders }, plugins:plugins };
[skip ci] Fix rootURL in production 🔨
/* eslint-env node */ 'use strict'; module.exports = function(environment) { let ENV = { modulePrefix: 'dummy', environment, rootURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true }, EXTEND_PROTOTYPES: { // Prevent Ember Data from overriding Date.parse. Date: false } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { ENV.locationType = 'hash'; ENV.rootURL = '/ember-polymer/'; } return ENV; };
/* eslint-env node */ 'use strict'; module.exports = function(environment) { let ENV = { modulePrefix: 'dummy', environment, rootURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true }, EXTEND_PROTOTYPES: { // Prevent Ember Data from overriding Date.parse. Date: false } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { } return ENV; };
Update atom state before calling watches
class Atom { constructor(state) { this.state = state; this.watches = {}; } reset(state) { return this._change(state); } swap(f, ...args) { return this._change(f(this.state, ...args)); } deref() { return this.state; } addWatch(k, f) { // if (this.watches[key]) { // console.warn(`adding a watch with an already registered key: ${k}`); // } this.watches[k] = f; return this; } removeWatch(k) { // if (!this.watches[key]) { // console.warn(`removing a watch with an unknown key: ${k}`); // } delete this.watches[key]; return this; } _change(newState) { const { state, watches } = this; this.state = newState; Object.keys(watches).forEach(k => watches[k](k, state, newState)); return this.state; } } export default function atom(state) { return new Atom(state); }
class Atom { constructor(state) { this.state = state; this.watches = {}; } reset(state) { return this._change(state); } swap(f, ...args) { return this._change(f(this.state, ...args)); } deref() { return this.state; } addWatch(k, f) { // if (this.watches[key]) { // console.warn(`adding a watch with an already registered key: ${k}`); // } this.watches[k] = f; return this; } removeWatch(k) { // if (!this.watches[key]) { // console.warn(`removing a watch with an unknown key: ${k}`); // } delete this.watches[key]; return this; } _change(newState) { const { state, watches } = this; Object.keys(watches).forEach(k => watches[k](k, state, newState)); this.state = newState; return this.state; } } export default function atom(state) { return new Atom(state); }
Use the added_subchannel_activity template for this activity
window.GenericActivityView = Backbone.View.extend({ tagName: "div", className: "activity-block", initialize: function(options) { this.useTemplate("activities", "_generic_activity"); }, render: function() { $(this.el).html( Mustache.to_html(this.tmpl, this.model.toJSON()) ); $('#facts_for_channel').append($(this.el)); return this; }, clickHandler: function(e) { document.location.href = this.model.url(); } }); ActivityAddedEvidenceView = GenericActivityView.extend({}); ActivityAddedSubchannelView = GenericActivityView.extend({ initialize: function(options) { this.useTemplate("activities", "_added_subchannel_activity"); } }); ActivityWasFollowedView = GenericActivityView.extend({}); window.ActivityView = function(opts) { if (opts.model.get("action") === "added_evidence") { return new ActivityAddedEvidenceView(opts); } else if (opts.model.get("action") === "added_subchannel") { return new ActivityAddedSubchannelView(opts); } else if (opts.model.get("action") === "was_followed") { return new ActivityWasFollowedView(opts); } else { return new GenericActivityView(opts); } };
window.GenericActivityView = Backbone.View.extend({ tagName: "div", className: "activity-block", initialize: function(options) { this.useTemplate("activities", "_generic_activity"); }, render: function() { $(this.el).html( Mustache.to_html(this.tmpl, this.model.toJSON()) ); $('#facts_for_channel').append($(this.el)); return this; }, clickHandler: function(e) { document.location.href = this.model.url(); } }); ActivityAddedEvidenceView = GenericActivityView.extend({}); ActivityAddedSubchannelView = GenericActivityView.extend({}); ActivityWasFollowedView = GenericActivityView.extend({}); window.ActivityView = function(opts) { if (opts.model.get("action") === "added_evidence") { return new ActivityAddedEvidenceView(opts); } else if (opts.model.get("action") === "added_subchannel") { return new ActivityAddedSubchannelView(opts); } else if (opts.model.get("action") === "was_followed") { return new ActivityWasFollowedView(opts); } else { return new GenericActivityView(opts); } };
Use new TextureStimulus parameter definitions. git-svn-id: 033d166fe8e629f6cbcd3c0e2b9ad0cffc79b88b@238 3a63a0ee-37fe-0310-a504-e92b6e0a3ba7
#!/usr/bin/env python from VisionEgg.Core import * from VisionEgg.Textures import * from VisionEgg.AppHelper import * filename = "orig.bmp" if len(sys.argv) > 1: filename = sys.argv[1] try: texture = TextureFromFile(filename) except: print "Could not open image file '%s', generating texture."%filename texture = Texture(size=(256,256)) screen = get_default_screen() # Set the projection so that eye coordinates are window coordinates projection = OrthographicProjection(right=screen.size[0],top=screen.size[1]) # Create the instance of TextureStimulus stimulus = TextureStimulus(texture=texture,projection=projection) # Set the stimulus to have 1:1 scaling (requires projection as set above) # This may result in clipping if texture is bigger than screen stimulus.parameters.right = texture.orig.size[0] stimulus.parameters.top = texture.orig.size[1] stimulus.init_gl() # Because the stimulus has a projection, we don't care what the # default is that the viewport uses. lower_y = screen.size[1]/2 - texture.orig.size[1]/2 viewport = Viewport(screen,(0,lower_y),screen.size) viewport.add_stimulus(stimulus) p = Presentation(duration=(5.0,'seconds'),viewports=[viewport]) p.go()
#!/usr/bin/env python from VisionEgg.Core import * from VisionEgg.Textures import * from VisionEgg.AppHelper import * filename = "orig.bmp" if len(sys.argv) > 1: filename = sys.argv[1] try: texture = TextureFromFile(filename) except: print "Could not open image file '%s', generating texture."%filename texture = Texture(size=(256,256)) screen = get_default_screen() # Set the projection so that eye coordinates are window coordinates projection = OrthographicProjection(right=screen.size[0],top=screen.size[1]) # Create the instance of TextureStimulus stimulus = TextureStimulus(texture=texture,projection=projection) # Set the stimulus to have 1:1 scaling (requires projection as set above) # This may result in clipping if texture is bigger than screen stimulus.parameters.upper_right = ( texture.orig.size[0], texture.orig.size[1] ) stimulus.init_gl() # Because the stimulus has a projection, we don't care what default is that the viewport uses. lower_y = screen.size[1]/2 - texture.orig.size[1]/2 viewport = Viewport(screen,(0,lower_y),screen.size) viewport.add_stimulus(stimulus) p = Presentation(duration=(5.0,'seconds'),viewports=[viewport]) p.go()
Set more detail log on error
var sys = require('sys'); var fs = require('fs'); var cache = {} function now() { return (new Date).getTime(); } exports.put = function(key, value, time) { fs.writeFile('cache/' + key, value, function (err) { if (err) { console.log('Error on set:' err); } else { cache[key] = {expire: time + now()} } }); } exports.del = function(key) { fs.unlink('cache/' + key, function (err) { delete cache[key]; }); } exports.get = function(key) { var data = cache[key]; if (typeof data != "undefined") { if (isNaN(data.expire) || data.expire >= now()) { fs.readFile('cache/' + key, function (err, filedata) { if (err) { console.log('Error on get:' err); return null; } else { return filedata; } }); } else { exports.del(key); } } return null; }
var sys = require('sys'); var fs = require('fs'); var cache = {} function now() { return (new Date).getTime(); } exports.put = function(key, value, time) { fs.writeFile('cache/' + key, value, function (err) { if (err) { console.log(err); } else { cache[key] = {expire: time + now()} } }); } exports.del = function(key) { fs.unlink('cache/' + key, function (err) { delete cache[key]; }); } exports.get = function(key) { var data = cache[key]; if (typeof data != "undefined") { if (isNaN(data.expire) || data.expire >= now()) { fs.readFile('cache/' + key, function (err, filedata) { if (err) { console.log(err); return null; } else { return filedata; } }); } else { exports.del(key); } } return null; }
Make sure properties with dashes are handled correctly
<?php namespace spec\Scato\Serializer\ObjectAccess; use PhpSpec\ObjectBehavior; use Prophecy\Argument; use stdClass; class SimpleAccessorSpec extends ObjectBehavior { function it_should_be_an_object_accessor() { $this->shouldHaveType('Scato\Serializer\Navigation\ObjectAccessorInterface'); } function it_should_find_names() { $object = new stdClass(); $object->foo = 'bar'; $this->getNames($object)->shouldBe(array('foo')); } function it_should_read_values() { $object = new stdClass(); $object->foo = 'bar'; $this->getValue($object, 'foo')->shouldBe('bar'); } function it_should_find_properties_with_dashes() { $array = ['foo-bar' => 'foobar']; $object = (object) $array; $this->getNames($object)->shouldBe(array('foo-bar')); } function it_should_read_properties_with_dashes() { $array = ['foo-bar' => 'foobar']; $object = (object) $array; $this->getValue($object, 'foo-bar')->shouldBe('foobar'); } }
<?php namespace spec\Scato\Serializer\ObjectAccess; use PhpSpec\ObjectBehavior; use Prophecy\Argument; use stdClass; class SimpleAccessorSpec extends ObjectBehavior { function it_should_be_an_object_accessor() { $this->shouldHaveType('Scato\Serializer\Navigation\ObjectAccessorInterface'); } function it_should_find_names() { $object = new stdClass(); $object->foo = 'bar'; $this->getNames($object)->shouldBe(array('foo')); } function it_should_read_values() { $object = new stdClass(); $object->foo = 'bar'; $this->getValue($object, 'foo')->shouldBe('bar'); } }
Add default votes and topscores
import datetime from flask import url_for from Simpoll import db class Poll(db.Document): created_at = db.DateTimeField(default=datetime.datetime.now, required=True) question = db.StringField(max_length=255, required=True) option1 = db.StringField(max_length=255, required=True) option2 = db.StringField(max_length=255, required=True) option1votes = db.IntField(default=0, required=True) option2votes = db.IntField(default=0, required=True) topscore = db.IntField(default=0, required=True) def get_absolute_url(self): # it's okay to use the first 7 bytes for url # because first 4 bytes are time and next 3 are # a machine id return url_for('post', kwargs={"slug": self._id[0:6]}) def __unicode__(self): return self.question meta = { 'allow_inheritance': True, 'indexes': ['-created_at', 'slug'], 'ordering': ['-created_at'] }
import datetime from flask import url_for from Simpoll import db class Poll(db.Document): created_at = db.DateTimeField(default=datetime.datetime.now, required=True) question = db.StringField(max_length=255, required=True) option1 = db.StringField(max_length=255, required=True) option2 = db.StringField(max_length=255, required=True) option1votes = db.IntField(required=True) option2votes = db.IntField(required=True) topscore = db.IntField(required=True) def get_absolute_url(self): # it's okay to use the first 7 bytes for url # because first 4 bytes are time and next 3 are # a machine id return url_for('post', kwargs={"slug": self._id[0:6]}) def __unicode__(self): return self.question meta = { 'allow_inheritance': True, 'indexes': ['-created_at', 'slug'], 'ordering': ['-created_at'] }
Include next 15 minutes in 'next courses' block
<?php namespace Etu\Core\UserBundle\Entity\Repository; use Doctrine\ORM\EntityRepository; use Etu\Core\UserBundle\Entity\Course; use Etu\Core\UserBundle\Entity\User; class CourseRepository extends EntityRepository { /** * @param User $user * @return Course[] */ public function getUserNextCourses(User $user) { /** @var Course[] $todayCourses */ $todayCourses = $this->createQueryBuilder('c') ->where('c.user = :user') ->andWhere('c.day = :day') ->orderBy('c.start', 'ASC') ->setParameter('user', $user->getId()) ->setParameter('day', Course::getTodayConstant()) ->getQuery() ->getResult(); $nextCourses = []; foreach ($todayCourses as $course) { if ($course->getStartAsInt() >= (int) date('Hi') - 15) { $nextCourses[$course->getStart()][] = $course; } } return array_slice($nextCourses, 0, 5); } }
<?php namespace Etu\Core\UserBundle\Entity\Repository; use Doctrine\ORM\EntityRepository; use Etu\Core\UserBundle\Entity\Course; use Etu\Core\UserBundle\Entity\User; class CourseRepository extends EntityRepository { /** * @param User $user * @return Course[] */ public function getUserNextCourses(User $user) { /** @var Course[] $todayCourses */ $todayCourses = $this->createQueryBuilder('c') ->where('c.user = :user') ->andWhere('c.day = :day') ->orderBy('c.start', 'ASC') ->setParameter('user', $user->getId()) ->setParameter('day', Course::getTodayConstant()) ->getQuery() ->getResult(); $nextCourses = []; foreach ($todayCourses as $course) { if ($course->getStartAsInt() >= (int) date('Hi')) { $nextCourses[$course->getStart()][] = $course; } } return array_slice($nextCourses, 0, 5); } }
Add explicit example filtering based on the byte length of the content
from tempfile import TemporaryDirectory from expects import expect from hypothesis import given, assume, example from hypothesis.strategies import text, characters from mamba import description, it from pathlib import Path from crowd_anki.utils.filesystem.name_sanitizer import sanitize_anki_deck_name, \ invalid_filename_chars from test_utils.matchers import contain_any size_limit = 255 def byte_length_size(sample): return len(bytes(sample, "utf-8")) <= size_limit with description("AnkiDeckNameSanitizer"): with it("should remove all bad characters from the string"): expect(sanitize_anki_deck_name(invalid_filename_chars)) \ .not_to(contain_any(*invalid_filename_chars)) with it("should be possible to create a file name from a random sanitized string"): @given(text(characters(min_codepoint=1, max_codepoint=800), max_size=size_limit, min_size=1) .filter(byte_length_size)) @example("line\n another one") def can_create(potential_name): assume(potential_name not in ('.', '..')) with TemporaryDirectory() as dir_name: Path(dir_name).joinpath(sanitize_anki_deck_name(potential_name)).mkdir() can_create()
from tempfile import TemporaryDirectory from expects import expect from hypothesis import given, assume, example from hypothesis.strategies import text, characters from mamba import description, it from pathlib import Path from crowd_anki.utils.filesystem.name_sanitizer import sanitize_anki_deck_name, \ invalid_filename_chars from test_utils.matchers import contain_any with description("AnkiDeckNameSanitizer"): with it("should remove all bad characters from the string"): expect(sanitize_anki_deck_name(invalid_filename_chars)) \ .not_to(contain_any(*invalid_filename_chars)) with it("should be possible to create a file name from a random sanitized string"): @given(text(characters(min_codepoint=1, max_codepoint=800), max_size=254, min_size=1)) @example("line\n another one") def can_create(potential_name): assume(potential_name not in ('.', '..')) with TemporaryDirectory() as dir_name: Path(dir_name).joinpath(sanitize_anki_deck_name(potential_name)).mkdir() can_create()
Remove describe only test switch
/* jshint mocha: true */ 'use strict'; const assert = require('assert'); const sendgrid = require('../lib/sendgrid'); let nodes; let send = sendgrid.sendgrid.send; beforeEach(function() { sendgrid.sendgrid.send = function() {}; nodes = [ { name: 'foo', offline: true, },{ name: 'bar', offline: false, } ]; }); afterEach(function() { sendgrid.sendgrid.send = send; }); describe('sendgrid', function() { describe('notify', function() { it('sends an email', function(done) { sendgrid.sendgrid.send = function(email, cb) { assert.equal(email.from, process.env.SENDGRID_SENDER); assert.equal(email.subject, '[jenkins-monitor] Downtime Alert'); assert.equal(typeof email.text, 'object'); cb(null); }; sendgrid.notify(nodes, done); }); }); });
/* jshint mocha: true */ 'use strict'; const assert = require('assert'); const sendgrid = require('../lib/sendgrid'); let nodes; let send = sendgrid.sendgrid.send; beforeEach(function() { sendgrid.sendgrid.send = function() {}; nodes = [ { name: 'foo', offline: true, },{ name: 'bar', offline: false, } ]; }); afterEach(function() { sendgrid.sendgrid.send = send; }); describe.only('sendgrid', function() { describe('notify', function() { it('sends an email', function(done) { sendgrid.sendgrid.send = function(email, cb) { assert.equal(email.from, process.env.SENDGRID_SENDER); assert.equal(email.subject, '[jenkins-monitor] Downtime Alert'); assert.equal(typeof email.text, 'object'); cb(null); }; sendgrid.notify(nodes, done); }); }); });
Reduce events frequency: 1% -> 0.5%
import React, { PropTypes, Component } from 'react' import moment from 'moment' import eventActions from '../actions/eventActionCreators' const TIME_INIT = moment('2190-07-02').utc() const DELAY = 1000 class Time extends Component { componentWillMount () { this.setState({ time: TIME_INIT }) } componentDidMount () { this.timer = setInterval(this._interval.bind(this), DELAY) } componentWillUnmount () { clearInterval(this.timer) } render () { return <div>{this.state.time.format('MMM Do YYYY').valueOf()}</div> } _interval () { this._advanceTime() if (Math.random() < 0.005) this._triggerEvent() } _advanceTime () { const time = this.state.time.add(1, 'days') this.setState({ time }) } _triggerEvent () { const n = Math.random() const eventCategory = (n < 0.5) ? 'easy' : (n < 0.75 ? 'medium' : 'hard') this.props.dispatch(eventActions.triggerEvent(eventCategory)) } } Time.propTypes = { dispatch: PropTypes.func.isRequired, } export default Time
import React, { PropTypes, Component } from 'react' import moment from 'moment' import eventActions from '../actions/eventActionCreators' const TIME_INIT = moment('2190-07-02').utc() const DELAY = 1000 class Time extends Component { componentWillMount () { this.setState({ time: TIME_INIT }) } componentDidMount () { this.timer = setInterval(this._interval.bind(this), DELAY) } componentWillUnmount () { clearInterval(this.timer) } render () { return <div>{this.state.time.format('MMM Do YYYY').valueOf()}</div> } _interval () { this._advanceTime() if (Math.random() < 0.01) this._triggerEvent() } _advanceTime () { const time = this.state.time.add(1, 'days') this.setState({ time }) } _triggerEvent () { const n = Math.random() const eventCategory = (n < 0.5) ? 'easy' : (n < 0.75 ? 'medium' : 'hard') this.props.dispatch(eventActions.triggerEvent(eventCategory)) } } Time.propTypes = { dispatch: PropTypes.func.isRequired, } export default Time
Change parameters to match StressModel2 and so the results.
"""recharge_func module Author: R.A. Collenteur Contains the classes for the different models that are available to calculate the recharge from evaporation and precipitation data. Each Recharge class contains at least the following: Attributes ---------- nparam: int Number of parameters needed for this model. Functions --------- set_parameters(self, name) A function that returns a Pandas DataFrame of the parameters of the recharge function. Columns of the dataframe need to be ['value', 'pmin', 'pmax', 'vary']. Rows of the DataFrame have names of the parameters. Input name is used as a prefix. This function is called by a Tseries object. simulate(self, evap, prec, p=None) A function that returns an array of the simulated recharge series. """ import pandas as pd class Linear: """Linear recharge model The recharge to the groundwater is calculated as: R = P - f * E """ def __init__(self): self.nparam = 1 def set_parameters(self, name): parameters = pd.DataFrame( columns=['initial', 'pmin', 'pmax', 'vary', 'name']) parameters.loc[name + '_f'] = (-1.0, -2.0, 0.0, 1, name) return parameters def simulate(self, precip, evap, p=None): recharge = precip + p * evap return recharge
"""recharge_func module Author: R.A. Collenteur Contains the classes for the different models that are available to calculate the recharge from evaporation and precipitation data. Each Recharge class contains at least the following: Attributes ---------- nparam: int Number of parameters needed for this model. Functions --------- set_parameters(self, name) A function that returns a Pandas DataFrame of the parameters of the recharge function. Columns of the dataframe need to be ['value', 'pmin', 'pmax', 'vary']. Rows of the DataFrame have names of the parameters. Input name is used as a prefix. This function is called by a Tseries object. simulate(self, evap, prec, p=None) A function that returns an array of the simulated recharge series. """ import pandas as pd class Linear: """Linear recharge model The recharge to the groundwater is calculated as: R = P - f * E """ def __init__(self): self.nparam = 1 def set_parameters(self, name): parameters = pd.DataFrame( columns=['initial', 'pmin', 'pmax', 'vary', 'name']) parameters.loc[name + '_f'] = (-1.0, -5.0, 0.0, 1, name) return parameters def simulate(self, precip, evap, p=None): recharge = precip + p * evap return recharge
Fix no endline at end of file
#### #### Check that counts for basic searches is within 10% of given counts #### import re, os, time import ftplib from behave import * from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC @given('I want a screenshot of page "{page}"') def step_impl(context, page): context.browser.maximize_window() context.browser.get(context.target + page) @then('the screenshot is "{title}"') def step_impl(context, title): current_directory = os.getcwd() screenshot_directory = current_directory + "/screenshots" if not os.path.exists(screenshot_directory): os.mkdir(screenshot_directory) os.chdir(screenshot_directory) context.browser.save_screenshot(title + '.png') os.chdir(current_directory)
#### #### Check that counts for basic searches is within 10% of given counts #### import re, os, time import ftplib from behave import * from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC @given('I want a screenshot of page "{page}"') def step_impl(context, page): context.browser.maximize_window() context.browser.get(context.target + page) @then('the screenshot is "{title}"') def step_impl(context, title): current_directory = os.getcwd() screenshot_directory = current_directory + "/screenshots" if not os.path.exists(screenshot_directory): os.mkdir(screenshot_directory) os.chdir(screenshot_directory) context.browser.save_screenshot(title + '.png') os.chdir(current_directory)
Remove TODO about steps, coming soon!
<?php namespace CachetHQ\Cachet\Http\Controllers; use CachetHQ\Cachet\Models\Component; use Illuminate\Routing\Controller; use Illuminate\Support\Facades\View; class DashboardController extends Controller { /** * Shows the dashboard view. * * @return \Illuminate\View\View */ public function showDashboard() { $components = Component::all(); return View::make('dashboard.index')->with([ 'components' => $components, ]); } /** * Shows the metrics view. * * @return \Illuminate\View\View */ public function showMetrics() { return View::make('dashboard.metrics.index')->with([ 'pageTitle' => trans('dashboard.metrics.metrics').' - '.trans('dashboard.dashboard'), ]); } /** * Shows the notifications view. * * @return \Illuminate\View\View */ public function showNotifications() { return View::make('dashboard.notifications.index')->with([ 'pageTitle' => trans('dashboard.notifications.notifications').' - '.trans('dashboard.dashboard'), ]); } }
<?php namespace CachetHQ\Cachet\Http\Controllers; use CachetHQ\Cachet\Models\Component; use Illuminate\Routing\Controller; use Illuminate\Support\Facades\View; class DashboardController extends Controller { /** * Shows the dashboard view. * * @return \Illuminate\View\View */ public function showDashboard() { // TODO: Find steps needed to complete setup. $components = Component::all(); return View::make('dashboard.index')->with([ 'components' => $components, ]); } /** * Shows the metrics view. * * @return \Illuminate\View\View */ public function showMetrics() { return View::make('dashboard.metrics.index')->with([ 'pageTitle' => trans('dashboard.metrics.metrics').' - '.trans('dashboard.dashboard'), ]); } /** * Shows the notifications view. * * @return \Illuminate\View\View */ public function showNotifications() { return View::make('dashboard.notifications.index')->with([ 'pageTitle' => trans('dashboard.notifications.notifications').' - '.trans('dashboard.dashboard'), ]); } }
Fix the title of the main video
import window from 'global/window'; import document from 'global/document'; import $ from 'jquery'; import videojs from 'video.js'; const player = window.player = videojs('preview-player', { fluid: true, plugins: { mux: { data: { property_key: 'VJSISBEST', video_title: 'Disney\'s Oceans', video_id: 1 } } } }); player.on('ready', function() { player.removeClass('placeholder'); }); const overlay = $('.videojs-hero-overlay'); player.on(['play', 'playing'], function() { overlay.addClass('transparent'); }); player.on(['pause'], function() { overlay.removeClass('transparent'); }); // Poor man's lazy loading the iframe content to speed up homeage loading setTimeout(function(){ Array.prototype.forEach.call(document.querySelectorAll('iframe'), function(ifrm){ const src = ifrm.getAttribute('temp-src'); if (src) { ifrm.setAttribute('src', src); } }); }, 1000);
import window from 'global/window'; import document from 'global/document'; import $ from 'jquery'; import videojs from 'video.js'; const player = window.player = videojs('preview-player', { fluid: true, plugins: { mux: { data: { property_key: 'VJSISBEST', video_title: 'The Boids!', video_id: 1 } } } }); player.on('ready', function() { player.removeClass('placeholder'); }); const overlay = $('.videojs-hero-overlay'); player.on(['play', 'playing'], function() { overlay.addClass('transparent'); }); player.on(['pause'], function() { overlay.removeClass('transparent'); }); // Poor man's lazy loading the iframe content to speed up homeage loading setTimeout(function(){ Array.prototype.forEach.call(document.querySelectorAll('iframe'), function(ifrm){ const src = ifrm.getAttribute('temp-src'); if (src) { ifrm.setAttribute('src', src); } }); }, 1000);
Fix for my nefarious `warn` replacement
import sys import warnings from warnings import warn as orig_warn def my_warn(message, category=None, stacklevel=1): # taken from warnings module # Get context information try: caller = sys._getframe(stacklevel) except ValueError: globals = sys.__dict__ lineno = 1 else: globals = caller.f_globals lineno = caller.f_lineno module = globals['__name__'] filename = globals.get('__file__') m = { 'argspec': 'inspect.getargspec() is deprecated' } if module == 'scipy._lib.decorator' and m['argspec'] in message: return if module == 'mdtraj.formats.hdf5' and m['argspec'] in message: return if module == 'statsmodels.base.wrapper' and m['argspec'] in message: return if module == 'nose.util' and m['argspec'] in message: return print("Warning: module: ", module) print("Warning: message: ", message) # This explicit check is necessary for python < 3.5 maybe?? if category is None: category = UserWarning return orig_warn(message=message, category=category, stacklevel=stacklevel + 1) warnings.warn = my_warn
import sys import warnings from warnings import warn as orig_warn def my_warn(message, category=None, stacklevel=1): # taken from warnings module # Get context information try: caller = sys._getframe(stacklevel) except ValueError: globals = sys.__dict__ lineno = 1 else: globals = caller.f_globals lineno = caller.f_lineno module = globals['__name__'] filename = globals.get('__file__') m = { 'argspec': 'inspect.getargspec() is deprecated' } if module == 'scipy._lib.decorator' and m['argspec'] in message: return if module == 'mdtraj.formats.hdf5' and m['argspec'] in message: return if module == 'statsmodels.base.wrapper' and m['argspec'] in message: return if module == 'nose.util' and m['argspec'] in message: return print("Warning: module: ", module) print("Warning: message: ", message) return orig_warn(message=message, category=category, stacklevel=stacklevel + 1) warnings.warn = my_warn
Add value() to jug namespace The jug namespace might need some attention.
# -*- coding: utf-8 -*- # vim: set ts=4 sts=4 sw=4 expandtab smartindent: # Copyright (C) 2008-2010, Luis Pedro Coelho <lpc@cmu.edu> # # 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. from __future__ import division from .task import TaskGenerator, Task, value from .jug import init from .backends import file_store, dict_store, redis_store __version__ = '0.5.9-git'
# -*- coding: utf-8 -*- # vim: set ts=4 sts=4 sw=4 expandtab smartindent: # Copyright (C) 2008-2010, Luis Pedro Coelho <lpc@cmu.edu> # # 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. from __future__ import division from .task import TaskGenerator, Task from .jug import init from .backends import file_store, dict_store, redis_store __version__ = '0.5.0'
Fix test for eq and test eq with other classes
from pytwitcherapi import chat def test_eq_str(servers): assert servers[0] == '192.16.64.11:80',\ "Server should be equal to the same address." def test_noteq_str(servers): assert servers[0] != '192.16.64.50:89',\ """Server should not be equal to a different address""" def test_eq(servers): s1 = chat.ChatServerStatus('192.16.64.11:80') assert servers[0] == s1,\ """Servers with same address should be equal""" assert not (s1 == 123),\ """Servers should not be eqaul to other classes with different id""" def test_noteq(servers): assert not (servers[0] == servers[1]),\ """Servers with different address should not be equal""" def test_lt(servers): sortedservers = sorted(servers) expected = [servers[2], servers[3], servers[0], servers[1]] assert sortedservers == expected,\ """Server should be sorted like this: online, then offline, little errors, then more errors, little lag, then more lag."""
from pytwitcherapi import chat def test_eq_str(servers): assert servers[0] == '192.16.64.11:80',\ "Server should be equal to the same address." def test_noteq_str(servers): assert servers[0] != '192.16.64.50:89',\ """Server should not be equal to a different address""" def test_eq(servers): s1 = chat.ChatServerStatus('192.16.64.11:80') assert servers[0] == s1,\ """Servers with same address should be equal""" def test_noteq(servers): assert servers[0] != servers[1],\ """Servers with different address should not be equal""" def test_lt(servers): sortedservers = sorted(servers) expected = [servers[2], servers[3], servers[0], servers[1]] assert sortedservers == expected,\ """Server should be sorted like this: online, then offline, little errors, then more errors, little lag, then more lag."""
Use '"' for string delimeter
import logging.config from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_mail import Mail from flask_user import UserManager, SQLAlchemyAdapter from flask_bootstrap import Bootstrap import iis.jobs def create_app(config: object) -> Flask: """Create the flask app. Can be called from testing contexts""" app = Flask(__name__) app.config.from_envvar("IIS_FLASK_SETTINGS") app.config.from_object(config) # Register blueprints app.register_blueprint(iis.jobs.jobs, url_prefix="/jobs") # Call app.logger to prevent it from clobbering configuration app.logger logging.config.dictConfig(app.config["LOGGING"]) app.logger.info("App configured.") return app app = create_app(None) # Set up SQLAlchemy and Migrate db = SQLAlchemy(app) # type: SQLAlchemy migrate = Migrate(app, db) # Load Flask-Mail mail = Mail(app) # Set up bootstrap Bootstrap(app) # Configure user model for Flask-User from iis.models import User # noqa: E402 db_adapter = SQLAlchemyAdapter(db, User) user_manager = UserManager(db_adapter, app) from iis import views, models # noqa: E402, F401
import logging.config from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_mail import Mail from flask_user import UserManager, SQLAlchemyAdapter from flask_bootstrap import Bootstrap def create_app(config: object) -> Flask: """Create the flask app. Can be called from testing contexts""" app = Flask(__name__) app.config.from_envvar('IIS_FLASK_SETTINGS') app.config.from_object(config) # Call app.logger to prevent it from clobbering configuration app.logger logging.config.dictConfig(app.config['LOGGING']) app.logger.info("App configured.") return app app = create_app(None) # Set up SQLAlchemy and Migrate db = SQLAlchemy(app) # type: SQLAlchemy migrate = Migrate(app, db) # Load Flask-Mail mail = Mail(app) # Set up bootstrap Bootstrap(app) # Configure user model for Flask-User from iis.models import User # noqa: E402 db_adapter = SQLAlchemyAdapter(db, User) user_manager = UserManager(db_adapter, app) from iis import views, models # noqa: E402, F401
Add search index for the taxonomy collection
'use strict'; /** * @module providers */ var util = require('util'); var EntityProvider = process.requireAPI('lib/providers/EntityProvider.js'); /** * Defines a TaxonomyProvider class to get and save taxonomies. * * @class TaxonomyProvider * @constructor * @extends EntityProvider * @param {Database} database The database to interact with */ function TaxonomyProvider(database) { EntityProvider.call(this, database, 'taxonomy'); } module.exports = TaxonomyProvider; util.inherits(TaxonomyProvider, EntityProvider); /** * Creates taxonomies indexes. * * @method createIndexes * @async * @param {Function} callback Function to call when it's done with : * - **Error** An error if something went wrong, null otherwise */ TaxonomyProvider.prototype.createIndexes = function(callback) { this.database.createIndexes(this.collection, [ {key: {name: 1}, name: 'byName'}, {key: {name: 'text'}, weights: {name: 1}, name: 'querySearch'} ], function(error, result) { if (result && result.note) process.logger.debug('Create taxonomies indexes : ' + result.note); callback(error); }); };
'use strict'; /** * @module providers */ var util = require('util'); var EntityProvider = process.requireAPI('lib/providers/EntityProvider.js'); /** * Defines a TaxonomyProvider class to get and save taxonomies. * * @class TaxonomyProvider * @constructor * @extends EntityProvider * @param {Database} database The database to interact with */ function TaxonomyProvider(database) { EntityProvider.call(this, database, 'taxonomy'); } module.exports = TaxonomyProvider; util.inherits(TaxonomyProvider, EntityProvider); /** * Creates taxonomies indexes. * * @method createIndexes * @async * @param {Function} callback Function to call when it's done with : * - **Error** An error if something went wrong, null otherwise */ TaxonomyProvider.prototype.createIndexes = function(callback) { this.database.createIndexes(this.collection, [ {key: {name: 1}, name: 'byName'} ], function(error, result) { if (result && result.note) process.logger.debug('Create taxonomies indexes : ' + result.note); callback(error); }); };
Add jasmineHtmlReporter included with angular-cli 11.0.2 but missing on update
// Karma configuration file, see link for more information // https://karma-runner.github.io/1.0/config/configuration-file.html module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', '@angular-devkit/build-angular'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage'), require('@angular-devkit/build-angular/plugins/karma') ], client: { clearContext: false // leave Jasmine Spec Runner output visible in browser }, jasmineHtmlReporter: { suppressAll: true // removes the duplicated traces }, coverageReporter: { dir: require('path').join(__dirname, './coverage/run-and-fun'), subdir: '.', reporters: [ { type: 'html' }, { type: 'text-summary' } ] }, reporters: ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false, restartOnFileChange: true }); };
// Karma configuration file, see link for more information // https://karma-runner.github.io/1.0/config/configuration-file.html module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', '@angular-devkit/build-angular'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage'), require('@angular-devkit/build-angular/plugins/karma') ], client: { clearContext: false // leave Jasmine Spec Runner output visible in browser }, coverageReporter: { dir: require('path').join(__dirname, './coverage/run-and-fun'), subdir: '.', reporters: [ { type: 'html' }, { type: 'text-summary' } ] }, reporters: ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false, restartOnFileChange: true }); };
Implement bitbucket OAuth support (implemented in composer 1.2) In composer 1.2 support for OAuth authentication for bitbucket.org has been expanded. This fix brings the same support to the composer asset plugin. It's completely backwards compatible with composer versions before 1.2.
<?php /* * This file is part of the Fxp Composer Asset Plugin package. * * (c) François Pluchino <francois.pluchino@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Fxp\Composer\AssetPlugin\Repository\Vcs; use Composer\Cache; use Composer\Repository\Vcs\GitBitbucketDriver as BaseGitBitbucketDriver; /** * Git Bitbucket vcs driver. * * @author François Pluchino <francois.pluchino@gmail.com> */ class GitBitbucketDriver extends BaseGitBitbucketDriver { /** * @var Cache */ protected $cache; /** * {@inheritdoc} */ public function initialize() { parent::initialize(); $this->cache = new Cache($this->io, $this->config->get('cache-repo-dir').'/'.$this->originUrl.'/'.$this->owner.'/'.$this->repository); } /** * {@inheritdoc} */ public function getComposerInformation($identifier) { $method = method_exists($this, 'getContentsWithOAuthCredentials') ? 'getContentsWithOAuthCredentials' : 'getContents'; return BitbucketUtil::getComposerInformation($this->cache, $this->infoCache, $this->getScheme(), $this->repoConfig, $identifier, $this->owner, $this->repository, $this, $method); } }
<?php /* * This file is part of the Fxp Composer Asset Plugin package. * * (c) François Pluchino <francois.pluchino@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Fxp\Composer\AssetPlugin\Repository\Vcs; use Composer\Cache; use Composer\Repository\Vcs\GitBitbucketDriver as BaseGitBitbucketDriver; /** * Git Bitbucket vcs driver. * * @author François Pluchino <francois.pluchino@gmail.com> */ class GitBitbucketDriver extends BaseGitBitbucketDriver { /** * @var Cache */ protected $cache; /** * {@inheritdoc} */ public function initialize() { parent::initialize(); $this->cache = new Cache($this->io, $this->config->get('cache-repo-dir').'/'.$this->originUrl.'/'.$this->owner.'/'.$this->repository); } /** * {@inheritdoc} */ public function getComposerInformation($identifier) { return BitbucketUtil::getComposerInformation($this->cache, $this->infoCache, $this->getScheme(), $this->repoConfig, $identifier, $this->owner, $this->repository, $this, 'getContents'); } }
Adjust jasmine task to generate coverage report
var gulp = require('gulp'); var apigen = require('gulp-apigen'); var phpunit = require('gulp-phpunit'); var spawn = require('child_process').spawn; var jasmine = require('gulp-jasmine'); var cover = require('gulp-coverage'); gulp.task('apigen', function() { gulp.src('apigen.neon').pipe(apigen('./vendor/bin/apigen')); }); gulp.task('phpunit', function() { gulp.src('phpunit.xml').pipe(phpunit('./vendor/bin/phpunit')); }); gulp.task('phpcs', function () { spawn('vendor/bin/phpcs', [], {stdio: 'inherit'}); }); gulp.task('php', ['phpcs','apigen','phpunit'], function () { }); gulp.task('jasmine', function() { gulp.src('test/js/*Spec.js') .pipe(cover.instrument({ pattern: ['src/webroot/js/*.js']//, // debugDirectory: 'debug' })) .pipe(jasmine()) .pipe(cover.gather()) .pipe(cover.format()) .pipe(gulp.dest('test/js/cover'));; }); gulp.task('default', function() { // place code for your default task here });
var gulp = require('gulp'); var apigen = require('gulp-apigen'); var phpunit = require('gulp-phpunit'); var spawn = require('child_process').spawn; var jasmine = require('gulp-jasmine'); gulp.task('apigen', function() { gulp.src('apigen.neon').pipe(apigen('./vendor/bin/apigen')); }); gulp.task('phpunit', function() { gulp.src('phpunit.xml').pipe(phpunit('./vendor/bin/phpunit')); }); gulp.task('phpcs', function () { spawn('vendor/bin/phpcs', [], {stdio: 'inherit'}); }); gulp.task('php', ['phpcs','apigen','phpunit'], function () { }); gulp.task('jasmine', function() { gulp.src('test/js/*Spec.js') .pipe(jasmine()); }); gulp.task('default', function() { // place code for your default task here });
Raise exception when script called with wrong args (instead of just printing)
import sys, os args = sys.argv if (len(args) <= 1): raise ValueError('Please provide source url when calling scraper.py. Example : python scraper.py url output.csv') else: url = args[1] if (len(args) == 2): filename = url.split('/')[-1].split('.')[0] output = filename + ".csv" print("No output file specified : using " + output) else: output = sys.argv[2] if not output.endswith(".csv"): output = output + ".csv" if os.path.isfile(output): os.remove(output) os.system("scrapy crawl realclearpoliticsSpider -a url="+url+" -o "+output)
import sys, os args = sys.argv if (len(args) <= 1): print("ERROR: Please provide source url") print("Example : python scraper.py url output.csv") else: url = args[1] if (len(args) == 2): filename = url.split('/')[-1].split('.')[0] output = filename + ".csv" print("No output file specified : using " + output) else: output = sys.argv[2] if not output.endswith(".csv"): output = output + ".csv" if os.path.isfile(output): os.remove(output) os.system("scrapy crawl realclearpoliticsSpider -a url="+url+" -o "+output)
Add user ID to member
from __future__ import absolute_import from sentry.api.serializers import Serializer, register from sentry.models import OrganizationMember @register(OrganizationMember) class OrganizationMemberSerializer(Serializer): def serialize(self, obj, attrs, user): if obj.user: user_data = {'id': obj.user.id} else: user_data = None d = { 'id': str(obj.id), 'email': obj.get_email(), 'name': obj.user.get_display_name() if obj.user else obj.get_email(), 'user': user_data, 'role': obj.role, 'roleName': obj.get_role_display(), 'pending': obj.is_pending, 'flags': { 'sso:linked': bool(getattr(obj.flags, 'sso:linked')), 'sso:invalid': bool(getattr(obj.flags, 'sso:invalid')), }, 'dateCreated': obj.date_added, } return d
from __future__ import absolute_import from sentry.api.serializers import Serializer, register from sentry.models import OrganizationMember @register(OrganizationMember) class OrganizationMemberSerializer(Serializer): def serialize(self, obj, attrs, user): d = { 'id': str(obj.id), 'email': obj.get_email(), 'name': obj.user.get_display_name() if obj.user else obj.get_email(), 'role': obj.role, 'roleName': obj.get_role_display(), 'pending': obj.is_pending, 'flags': { 'sso:linked': bool(getattr(obj.flags, 'sso:linked')), 'sso:invalid': bool(getattr(obj.flags, 'sso:invalid')), }, 'dateCreated': obj.date_added, } return d
Remove wrong directory and let it build
from setuptools import setup setup( name='ploodood', version='0.1', description='Generates words that "sound like real words"', author = 'Matteo Giordano', author_email = 'ilmalteo@gmail.com', url = 'https://github.com/malteo/ploodood', download_url = 'https://github.com/malteo/ploodood/tarball/0.1', keywords = ['password', 'generator', 'cli', 'command line'], py_modules=['ploodood'], classifiers = [], install_requires=[ 'Click', 'Requests', 'untangle' ], entry_points=''' [console_scripts] ploodood=ploodood:ploodood ''', )
from setuptools import setup setup( name='ploodood', version='0.1', description='Generates words that "sound like real words"', author = 'Matteo Giordano', author_email = 'ilmalteo@gmail.com', url = 'https://github.com/malteo/ploodood', download_url = 'https://github.com/malteo/ploodood/tarball/0.1', keywords = ['password', 'generator', 'cli', 'command line'], packages=['ploodood'], py_modules=['ploodood'], classifiers = [], install_requires=[ 'Click', 'Requests', 'untangle' ], entry_points=''' [console_scripts] ploodood=ploodood:ploodood ''', )
Create a custom exception type: Change service method signature for own exception class
package com.logicify.d2g.services; import com.logicify.d2g.domain.User; import com.logicify.d2g.dtos.domain.exceptions.ControllerException; import com.logicify.d2g.dtos.incomingdtos.UserCreateIncomingDto; import com.logicify.d2g.dtos.incomingdtos.UserUpdateIncomingDto; import com.logicify.d2g.dtos.incomingdtos.UserUpdateStatusIncomingDto; import com.logicify.d2g.dtos.outgoingdtos.UserOutgoingDto; import com.logicify.d2g.dtos.outgoingdtos.UsersListOutgoingDto; import java.util.UUID; /** * @author knorr */ public interface UserService { String createPasswordHash(String password) throws ControllerException; void createUser(UserCreateIncomingDto userCreateIncomingDto) throws ControllerException; UsersListOutgoingDto findAll(); UserOutgoingDto findOne(UUID id) throws ControllerException; void delete(UUID id) throws ControllerException; void updateUser(UUID id, UserUpdateIncomingDto userUpdateIncomingDto) throws ControllerException; void updateStatus(UUID id, UserUpdateStatusIncomingDto userUpdateStatusIncomingDto); /** * Returns user by it's UUID * * @param id user uuif * @return requested {@link User} */ //TODO: Implement finding user by its uuid }
package com.logicify.d2g.services; import com.logicify.d2g.domain.User; import com.logicify.d2g.dtos.incomingdtos.UserCreateIncomingDto; import com.logicify.d2g.dtos.incomingdtos.UserUpdateIncomingDto; import com.logicify.d2g.dtos.incomingdtos.UserUpdateStatusIncomingDto; import com.logicify.d2g.dtos.outgoingdtos.UserOutgoingDto; import com.logicify.d2g.dtos.outgoingdtos.UsersListOutgoingDto; import com.logicify.d2g.utils.PasswordStorage; import java.util.UUID; /** * @author knorr */ public interface UserService { String createPasswordHash(String password) throws PasswordStorage.CannotPerformOperationException; void createUser(UserCreateIncomingDto userCreateIncomingDto) throws PasswordStorage.CannotPerformOperationException; UsersListOutgoingDto findAll(); UserOutgoingDto findOne(UUID id); void delete(UUID id); void updateUser(UUID id, UserUpdateIncomingDto userUpdateIncomingDto) throws PasswordStorage.CannotPerformOperationException; void updateStatus(UUID id, UserUpdateStatusIncomingDto userUpdateStatusIncomingDto); /** * Returns user by it's UUID * * @param id user uuif * @return requested {@link User} */ //TODO: Implement finding user by its uuid }
Send navigation object as prop to RepoList React Navigator adds a navigation object as a prop to each screen. This isn't shared by the screen's components so it has to be passed down manually for the child components to be able to navigate.
import React, { Component } from 'react'; import { View } from 'react-native'; import RepoSearchBar from './components/RepoSearchBar'; import RepoSearchButton from './components/RepoSearchButton'; import RepoList from './components/RepoList'; export default class SearchScreen extends Component { constructor(props) { super(props); this.state = { username: '', repos: [] }; this.changeUsername = this.changeUsername.bind(this); this.updateRepos = this.updateRepos.bind(this); } render() { let buttonDisabled = this.state.username.length === 0; return ( <View style={{ flex: 1, flexDirection: 'column', }}> <RepoSearchBar onChangeText={this.changeUsername}/> <RepoSearchButton disabled={buttonDisabled} username={this.state.username} onPress={this.updateRepos} /> <RepoList list={this.state.repos} navigation={this.props.navigation} /> </View> ); } changeUsername(newUsername) { this.setState({ username: newUsername }); } updateRepos(newRepos) { this.setState({ repos: newRepos }); } }
import React, { Component } from 'react'; import { View } from 'react-native'; import RepoSearchBar from './components/RepoSearchBar'; import RepoSearchButton from './components/RepoSearchButton'; import RepoList from './components/RepoList'; export default class SearchScreen extends Component { constructor(props) { super(props); this.state = { username: '', repos: [] }; this.changeUsername = this.changeUsername.bind(this); this.updateRepos = this.updateRepos.bind(this); } render() { let buttonDisabled = this.state.username.length === 0; return ( <View style={{ flex: 1, flexDirection: 'column', }}> <RepoSearchBar onChangeText={this.changeUsername}/> <RepoSearchButton disabled={buttonDisabled} username={this.state.username} onPress={this.updateRepos} /> <RepoList list={this.state.repos}/> </View> ); } changeUsername(newUsername) { this.setState({ username: newUsername }); } updateRepos(newRepos) { this.setState({ repos: newRepos }); } }
Print usage when incorrect parameters passed If the incorrect number of parameters are passed the print the usage string.
package main import ( "fmt" "os" "os/user" "path" "strconv" "strings" "syscall" ) var usage string = "setuidgid: usage: setuidgid username program [arg...]" func checkError(err error) { if err != nil { fmt.Println(err) os.Exit(111) } } func main() { if len(os.Args) <= 2 { fmt.Print(usage) os.Exit(100) } username := os.Args[1] program := os.Args[2] pargv := os.Args[2:] user, err := user.Lookup(username) checkError(err) uid, err := strconv.Atoi(user.Uid) checkError(err) gid, err := strconv.Atoi(user.Gid) checkError(err) err = syscall.Setgid(gid) checkError(err) err = syscall.Setuid(uid) checkError(err) if path.IsAbs(program) { err := syscall.Exec(program, pargv, os.Environ()) checkError(err) } for _, p := range strings.Split(os.Getenv("PATH"), ":") { absPath := path.Join(p, program) err = syscall.Exec(absPath, pargv, os.Environ()) } checkError(err) }
package main import ( "fmt" "os" "os/user" "path" "strconv" "strings" "syscall" ) func checkError(err error) { if err != nil { fmt.Println(err) os.Exit(111) } } func main() { username := os.Args[1] program := os.Args[2] pargv := os.Args[2:] user, err := user.Lookup(username) checkError(err) uid, err := strconv.Atoi(user.Uid) checkError(err) gid, err := strconv.Atoi(user.Gid) checkError(err) err = syscall.Setgid(gid) checkError(err) err = syscall.Setuid(uid) checkError(err) if path.IsAbs(program) { err := syscall.Exec(program, pargv, os.Environ()) checkError(err) } for _, p := range strings.Split(os.Getenv("PATH"), ":") { absPath := path.Join(p, program) err = syscall.Exec(absPath, pargv, os.Environ()) } checkError(err) }
Fix parameter values for load function
# -*- coding: utf-8 -*- import unittest import os from mathdeck import loadproblem class TestMathdeckLoadProblem(unittest.TestCase): def test_loadproblem_has_answers_attribute(self): file_name = 'has_answers_attribute.py' file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'fixtures','loadproblem', file_name) problem = loadproblem.load_file_as_module(file) self.assertTrue(hasattr(problem,'answers')) def test_loadproblem_has_no_answers_attribute(self): file_name = 'has_no_answers_attribute.py' file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'fixtures','loadproblem', file_name) self.assertRaises(Exception, loadproblem.load_file_as_module(file)) if __name__ == '__main__': unittest.main()
# -*- coding: utf-8 -*- import unittest import os from mathdeck import loadproblem class TestMathdeckLoadProblem(unittest.TestCase): def test_loadproblem_has_answers_attribute(self): file_name = 'has_answers_attribute.py' problem_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'fixtures','loadproblem') problem = loadproblem.load_file_as_module(problem_dir,file_name) self.assertTrue(hasattr(problem,'answers')) def test_loadproblem_has_no_answers_attribute(self): file_name = 'has_no_answers_attribute.py' problem_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'fixtures','loadproblem') self.assertRaises(Exception, loadproblem. \ load_file_as_module(problem_dir,file_name)) if __name__ == '__main__': unittest.main()
Use sys.executable to run Python, as suggested by Neal Norwitz.
# Test the atexit module. from test_support import TESTFN, vereq import atexit import os import sys input = """\ import atexit def handler1(): print "handler1" def handler2(*args, **kargs): print "handler2", args, kargs atexit.register(handler1) atexit.register(handler2) atexit.register(handler2, 7, kw="abc") """ fname = TESTFN + ".py" f = file(fname, "w") f.write(input) f.close() p = os.popen("%s %s" % (sys.executable, fname)) output = p.read() p.close() vereq(output, """\ handler2 (7,) {'kw': 'abc'} handler2 () {} handler1 """) input = """\ def direct(): print "direct exit" import sys sys.exitfunc = direct # Make sure atexit doesn't drop def indirect(): print "indirect exit" import atexit atexit.register(indirect) """ f = file(fname, "w") f.write(input) f.close() p = os.popen("%s %s" % (sys.executable, fname)) output = p.read() p.close() vereq(output, """\ indirect exit direct exit """) os.unlink(fname)
# Test the atexit module. from test_support import TESTFN, vereq import atexit import os input = """\ import atexit def handler1(): print "handler1" def handler2(*args, **kargs): print "handler2", args, kargs atexit.register(handler1) atexit.register(handler2) atexit.register(handler2, 7, kw="abc") """ fname = TESTFN + ".py" f = file(fname, "w") f.write(input) f.close() p = os.popen("python " + fname) output = p.read() p.close() vereq(output, """\ handler2 (7,) {'kw': 'abc'} handler2 () {} handler1 """) input = """\ def direct(): print "direct exit" import sys sys.exitfunc = direct # Make sure atexit doesn't drop def indirect(): print "indirect exit" import atexit atexit.register(indirect) """ f = file(fname, "w") f.write(input) f.close() p = os.popen("python " + fname) output = p.read() p.close() vereq(output, """\ indirect exit direct exit """) os.unlink(fname)
Update dsub version to 0.4.3.dev0 PiperOrigin-RevId: 337359189
# 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. """Single source of truth for dsub's version. This must remain small and dependency-free so that any dsub module may import it without creating circular dependencies. Note that this module is parsed as a text file by setup.py and changes to the format of this file could break setup.py. The version should follow formatting requirements specified in PEP-440. - https://www.python.org/dev/peps/pep-0440 A typical release sequence will be versioned as: 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ DSUB_VERSION = '0.4.3.dev0'
# 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. """Single source of truth for dsub's version. This must remain small and dependency-free so that any dsub module may import it without creating circular dependencies. Note that this module is parsed as a text file by setup.py and changes to the format of this file could break setup.py. The version should follow formatting requirements specified in PEP-440. - https://www.python.org/dev/peps/pep-0440 A typical release sequence will be versioned as: 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ DSUB_VERSION = '0.4.2'
Reduce logging noise when metric fetching fails
// Copyright 2020 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package ai.vespa.metricsproxy.service; import ai.vespa.metricsproxy.metric.Metrics; import java.io.IOException; /** * Fetch metrics for a given vespa service * * @author Jo Kristian Bergum */ public class RemoteMetricsFetcher extends HttpMetricFetcher { final static String METRICS_PATH = STATE_PATH + "metrics"; RemoteMetricsFetcher(VespaService service, int port) { super(service, port, METRICS_PATH); } /** * Connect to remote service over http and fetch metrics */ public Metrics getMetrics(int fetchCount) { try { return createMetrics(getJson(), fetchCount); } catch (IOException e) { return new Metrics(); } } Metrics createMetrics(String data, int fetchCount) { Metrics remoteMetrics = new Metrics(); try { remoteMetrics = MetricsParser.parse(data); } catch (Exception e) { handleException(e, data, fetchCount); } return remoteMetrics; } }
// Copyright 2020 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package ai.vespa.metricsproxy.service; import ai.vespa.metricsproxy.metric.Metrics; import java.io.IOException; /** * Fetch metrics for a given vespa service * * @author Jo Kristian Bergum */ public class RemoteMetricsFetcher extends HttpMetricFetcher { final static String METRICS_PATH = STATE_PATH + "metrics"; RemoteMetricsFetcher(VespaService service, int port) { super(service, port, METRICS_PATH); } /** * Connect to remote service over http and fetch metrics */ public Metrics getMetrics(int fetchCount) { String data = "{}"; try { data = getJson(); } catch (IOException e) { logMessageNoResponse(errMsgNoResponse(e), fetchCount); } return createMetrics(data, fetchCount); } Metrics createMetrics(String data, int fetchCount) { Metrics remoteMetrics = new Metrics(); try { remoteMetrics = MetricsParser.parse(data); } catch (Exception e) { handleException(e, data, fetchCount); } return remoteMetrics; } }
Fix typo in sourcemap option
module.exports = { options: { require: ['sass-css-importer'], loadPath: ['<%%= bowerOpts.directory || "bower_components" %>'], bundleExec: true }, debug: { src: '<%%= dirs.tmp %>/prepare/assets/styles/main.scss', dest: '<%%= dirs.tmp %>/public/assets/styles/main.css', options: { style: 'expanded', sourcemap: 'true' } }, "public": { src: '<%%= dirs.tmp %>/prepare/assets/styles/main.scss', dest: '<%%= dirs.tmp %>/public/assets/styles/main.css', options: { style: 'compressed' } } };
module.exports = { options: { require: ['sass-css-importer'], loadPath: ['<%%= bowerOpts.directory || "bower_components" %>'], bundleExec: true }, debug: { src: '<%%= dirs.tmp %>/prepare/assets/styles/main.scss', dest: '<%%= dirs.tmp %>/public/assets/styles/main.css', options: { style: 'expanded', sourcemaps: 'true' } }, "public": { src: '<%%= dirs.tmp %>/prepare/assets/styles/main.scss', dest: '<%%= dirs.tmp %>/public/assets/styles/main.css', options: { style: 'compressed' } } };
Change siteuser string for clarity
from django.db import models from django.contrib.auth.models import User class SiteUser(models.Model): def __str__(self): return self.company + " | " + self.user.username # Using a OneToOneField so we can add the extra 'company' parameter to the user # without extending or replacing Django's User model user = models.OneToOneField(User) company = models.CharField(default='', max_length=100) class LoginSession(models.Model): def __str__(self): return self.token token = models.CharField(default='', max_length=64) user = models.CharField(default='', max_length=100) class Testimonial(models.Model): def __str__(self): return self.postedby text = models.TextField(default='', max_length=1000) postedby = models.CharField(default='', max_length=1000) email = models.CharField(default='', max_length=100)
from django.db import models from django.contrib.auth.models import User class SiteUser(models.Model): def __str__(self): return self.user.username # Using a OneToOneField so we can add the extra 'company' parameter to the user # without extending or replacing Django's User model user = models.OneToOneField(User) company = models.CharField(default='', max_length=100) class LoginSession(models.Model): def __str__(self): return self.token token = models.CharField(default='', max_length=64) user = models.CharField(default='', max_length=100) class Testimonial(models.Model): def __str__(self): return self.postedby text = models.TextField(default='', max_length=1000) postedby = models.CharField(default='', max_length=1000) email = models.CharField(default='', max_length=100)
[GitHub] Use API v3 URL for accessing user data
<?php /* * This file is part of the KnpOAuthBundle package. * * (c) KnpLabs <hello@knplabs.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Knp\Bundle\OAuthBundle\Security\Http\OAuth; use Knp\Bundle\OAuthBundle\Security\Http\OAuth\OAuthProvider; /** * GithubProvider * * @author Geoffrey Bachelet <geoffrey.bachelet@gmail.com> */ class GithubProvider extends OAuthProvider { /** * {@inheritDoc} */ protected $options = array( 'authorization_url' => 'https://github.com/login/oauth/authorize', 'access_token_url' => 'https://github.com/login/oauth/access_token', 'infos_url' => 'https://api.github.com/user', 'username_path' => 'user.login', ); /** * Github unfortunately breaks the spec by using commas instead of spaces * to separate scopes */ public function configure() { $this->options['scope'] = str_replace(',', ' ', $this->options['scope']); } }
<?php /* * This file is part of the KnpOAuthBundle package. * * (c) KnpLabs <hello@knplabs.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Knp\Bundle\OAuthBundle\Security\Http\OAuth; use Knp\Bundle\OAuthBundle\Security\Http\OAuth\OAuthProvider; /** * GithubProvider * * @author Geoffrey Bachelet <geoffrey.bachelet@gmail.com> */ class GithubProvider extends OAuthProvider { /** * {@inheritDoc} */ protected $options = array( 'authorization_url' => 'https://github.com/login/oauth/authorize', 'access_token_url' => 'https://github.com/login/oauth/access_token', 'infos_url' => 'https://github.com/api/v2/json/user/show', 'username_path' => 'user.login', ); /** * Github unfortunately breaks the spec by using commas instead of spaces * to separate scopes */ public function configure() { $this->options['scope'] = str_replace(',', ' ', $this->options['scope']); } }
Add precision to currency json
/* * This file is part of Bitsquare. * * Bitsquare is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * Bitsquare is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Bitsquare. If not, see <http://www.gnu.org/licenses/>. */ package io.bitsquare.locale; import java.io.Serializable; public class CurrencyTuple implements Serializable { // That object is used for serializing to a Json file. public final String code; public final String name; public final int precision; // precision 4 is 1/10000 -> 0.0001 is smallest unit public CurrencyTuple(String code, String name) { // We use Fiat class and there precision is 4 // In future we might add custom precision per currency this(code, name, 4); } public CurrencyTuple(String code, String name, int precision) { this.code = code; this.name = name; this.precision = precision; } }
/* * This file is part of Bitsquare. * * Bitsquare is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * Bitsquare is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Bitsquare. If not, see <http://www.gnu.org/licenses/>. */ package io.bitsquare.locale; import java.io.Serializable; public class CurrencyTuple implements Serializable { // That object is used for serializing to a Json file. public final String code; public final String name; public CurrencyTuple(String code, String name) { this.code = code; this.name = name; } }
Add configurable start location to config.xml and template Still possible to hardcode, there's a comment in the template showing how that can be done.
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package __ID__; import android.os.Bundle; import org.apache.cordova.*; public class __ACTIVITY__ extends DroidGap { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Config.init(this); super.loadUrl(Config.getStartUrl()); //super.loadUrl("file:///android_asset/www/index.html") } }
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package __ID__; import android.os.Bundle; import org.apache.cordova.*; public class __ACTIVITY__ extends DroidGap { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Config.init(this); super.loadUrl("file:///android_asset/www/index.html"); } }
Add Javadoc for 'error' package.
/* * Copyright 2015, TeamDev Ltd. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * This package contains exceptions thrown for errors of domain model definitions in Protobuf, * or for errors in Java classes handling the domain. */ @ParametersAreNonnullByDefault package org.spine3.error; import javax.annotation.ParametersAreNonnullByDefault;
/* * Copyright 2015, TeamDev Ltd. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ @ParametersAreNonnullByDefault package org.spine3.error; import javax.annotation.ParametersAreNonnullByDefault;
Use almostEqual for comparing geo coordinates An upgrade in one of the underlying libraries has shifted the numbers very slightly.
from django.core.management import call_command from django.test import TestCase from frontend.models import PCT def setUpModule(): call_command('loaddata', 'frontend/tests/fixtures/ccgs.json', verbosity=0) def tearDownModule(): call_command('flush', verbosity=0, interactive=False) class CommandsTestCase(TestCase): def test_import_ccg_boundaries(self): args = [] opts = { 'filename': ('frontend/tests/fixtures/commands/' 'CCG_BSC_Apr2015.TAB') } call_command('import_ccg_boundaries', *args, **opts) pct = PCT.objects.get(code='03Q') self.assertAlmostEqual(pct.boundary.centroid.x, -1.0307530606980588)
from django.core.management import call_command from django.test import TestCase from frontend.models import PCT def setUpModule(): call_command('loaddata', 'frontend/tests/fixtures/ccgs.json', verbosity=0) def tearDownModule(): call_command('flush', verbosity=0, interactive=False) class CommandsTestCase(TestCase): def test_import_ccg_boundaries(self): args = [] opts = { 'filename': ('frontend/tests/fixtures/commands/' 'CCG_BSC_Apr2015.TAB') } call_command('import_ccg_boundaries', *args, **opts) pct = PCT.objects.get(code='03Q') self.assertEqual(pct.boundary.centroid.x, -1.0307530606980588)
Use + operator to add lengths
'use strict'; // MODULES // var merge = require( '@stdlib/utils/merge' ); var unique = require( './unique.js' ); // MAIN // /** * Combines two lunr indices into a single one. * * @private * @param {Object} a - first lunr index * @param {Object} b - second lunr index * @returns {Object} combined lunr object */ function combine( a, b ) { var documentStore; var corpusTokens; var tokenStore; corpusTokens = unique( a.corpusTokens.concat( b.corpusTokens ) ); documentStore = { 'store': merge( a.documentStore.store, b.documentStore.store ), 'length': a.documentStore.length + b.documentStore.length }; tokenStore = { 'root': merge( a.tokenStore.root, b.tokenStore.root ), 'length': a.tokenStore.length + b.tokenStore.length }; return { 'version': a.version, 'fields': a.fields.slice(), 'corpusTokens': corpusTokens, 'documentStore': documentStore, 'tokenStore': tokenStore, 'pipeline': a.pipeline.slice() }; } // end FUNCTION combine() // EXPORTS // module.exports = combine;
'use strict'; // MODULES // var merge = require( '@stdlib/utils/merge' ); var unique = require( './unique.js' ); // MAIN // /** * Combines two lunr indices into a single one. * * @private * @param {Object} a - first lunr index * @param {Object} b - second lunr index * @returns {Object} combined lunr object */ function combine( a, b ) { var documentStore; var corpusTokens; var tokenStore; corpusTokens = unique( a.corpusTokens.concat( b.corpusTokens ) ); documentStore = { 'store': merge( a.documentStore.store, b.documentStore.store ), 'length': a.documentStore.length = b.documentStore.length }; tokenStore = { 'root': merge( a.tokenStore.root, b.tokenStore.root ), 'length': a.tokenStore.length + b.tokenStore.length }; return { 'version': a.version, 'fields': a.fields.slice(), 'corpusTokens': corpusTokens, 'documentStore': documentStore, 'tokenStore': tokenStore, 'pipeline': a.pipeline.slice() }; } // end FUNCTION combine() // EXPORTS // module.exports = combine;
Select top most note after deleting a note
import Em from 'ember'; import { task, timeout } from 'ember-concurrency'; var applicationController = Em.Controller.extend({ activeNote: null, hideSidePanel: false, // data sortedNotes: function() { return this.get('model').sortBy('updatedAt', 'createdAt').reverseObjects(); }.property('model.[]', 'model.@each.updatedAt'), deleteNoteTask: task(function *(note) { yield timeout(150); this.get('model').removeObject(note); if (Em.isEmpty(this.get('model'))) { this.send('createNote'); } else { this.send('showNote', this.get('sortedNotes.firstObject')); } yield note.destroyRecord(); }).drop(), actions: { createNote: function() { this.transitionToRoute('new'); }, deleteNote: function(note) { this.get('deleteNoteTask').perform(note); // this.get('model').removeObject(note); // if (Em.isEmpty(this.get('model'))) { // this.send('createNote'); // } else { // this.send('showNote', this.get('model.lastObject')); // } // note.destroyRecord(); }, // deleteAll: function() { // this.get('notes').forEach(function(note) { // note.destroyRecord(); // }); // }, toggleSidePanelHidden: function() { this.toggleProperty('hideSidePanel'); } } }); export default applicationController;
import Em from 'ember'; import { task, timeout } from 'ember-concurrency'; var applicationController = Em.Controller.extend({ activeNote: null, hideSidePanel: false, // data sortedNotes: function() { return this.get('model').sortBy('updatedAt', 'createdAt').reverseObjects(); }.property('model.[]', 'model.@each.updatedAt'), deleteNoteTask: task(function *(note) { yield timeout(150); this.get('model').removeObject(note); if (Em.isEmpty(this.get('model'))) { this.send('createNote'); } else { this.send('showNote', this.get('model.firstObject')); } yield note.destroyRecord(); }).drop(), actions: { createNote: function() { this.transitionToRoute('new'); }, deleteNote: function(note) { this.get('deleteNoteTask').perform(note); // this.get('model').removeObject(note); // if (Em.isEmpty(this.get('model'))) { // this.send('createNote'); // } else { // this.send('showNote', this.get('model.lastObject')); // } // note.destroyRecord(); }, // deleteAll: function() { // this.get('notes').forEach(function(note) { // note.destroyRecord(); // }); // }, toggleSidePanelHidden: function() { this.toggleProperty('hideSidePanel'); } } }); export default applicationController;
Add optional params to refund
<?php class Stripe_Charge extends Stripe_ApiResource { public static function constructFrom($values, $apiKey=null) { $class = get_class(); return self::_scopedConstructFrom($class, $values, $apiKey); } public static function retrieve($id, $apiKey=null) { $class = get_class(); return self::_scopedRetrieve($class, $id, $apiKey); } public static function all($params=null, $apiKey=null) { $class = get_class(); return self::_scopedAll($class, $params, $apiKey); } public static function create($params=null, $apiKey=null) { $class = get_class(); return self::_scopedCreate($class, $params, $apiKey); } public function refund($params=null) { $requestor = new Stripe_ApiRequestor($this->_apiKey); $url = $this->instanceUrl() . '/refund'; list($response, $apiKey) = $requestor->request('post', $url, $params); $this->refreshFrom($response, $apiKey); return $this; } }
<?php class Stripe_Charge extends Stripe_ApiResource { public static function constructFrom($values, $apiKey=null) { $class = get_class(); return self::_scopedConstructFrom($class, $values, $apiKey); } public static function retrieve($id, $apiKey=null) { $class = get_class(); return self::_scopedRetrieve($class, $id, $apiKey); } public static function all($params=null, $apiKey=null) { $class = get_class(); return self::_scopedAll($class, $params, $apiKey); } public static function create($params=null, $apiKey=null) { $class = get_class(); return self::_scopedCreate($class, $params, $apiKey); } public function refund() { $requestor = new Stripe_ApiRequestor($this->_apiKey); $url = $this->instanceUrl() . '/refund'; list($response, $apiKey) = $requestor->request('post', $url); $this->refreshFrom($response, $apiKey); return $this; } }
Move the main items into a function
#!/usr/bin/env python import requests import calendar from datetime import datetime, timedelta from settings import _token, _domain, _user, _time, _pretty def delete_my_files(): while 1: files_list_url = 'https://slack.com/api/files.list' date = str(calendar.timegm((datetime.now() + timedelta(-_time)).utctimetuple())) data = {"token": _token, "ts_to": date, "user": _user} response = requests.post(files_list_url, data=data) if len(response.json()["files"]) == 0: break for f in response.json()["files"]: print("Deleting file " + f["name"] + "...") timestamp = str(calendar.timegm(datetime.now().utctimetuple())) delete_url = "https://" + _domain + ".slack.com/api/files.delete?t=" + timestamp requests.post(delete_url, data={ "token": _token, "file": f["id"], "set_active": "true", "_attempts": "1"}) print("DONE!") if __name__ == '__main__': delete_my_files()
#!/usr/bin/env python import requests import calendar from datetime import datetime, timedelta from settings import _token, _domain, _user, _time, _pretty if __name__ == '__main__': while 1: files_list_url = 'https://slack.com/api/files.list' date = str(calendar.timegm((datetime.now() + timedelta(-_time)).utctimetuple())) data = {"token": _token, "ts_to": date, "user": _user} response = requests.post(files_list_url, data=data) if len(response.json()["files"]) == 0: break for f in response.json()["files"]: print("Deleting file " + f["name"] + "...") timestamp = str(calendar.timegm(datetime.now().utctimetuple())) delete_url = "https://" + _domain + ".slack.com/api/files.delete?t=" + timestamp requests.post(delete_url, data={ "token": _token, "file": f["id"], "set_active": "true", "_attempts": "1"}) print("DONE!")
MODIFY academic cohort method and schema to include acad year
import { Mongo } from 'meteor/mongo'; import { SimpleSchema } from 'meteor/aldeed:simple-schema'; class AcadCohortCollection extends Mongo.Collection{ insert(acadCohortData, callBack){ const cohortDocument = acadCohortData; let result; //validate document return super.insert( cohortDocument, callBack); }; update(selector, modifier){ const result = super.update(selector, modifier); return result; }; remove(selector){ const result = super.remove(selector); return result; }; } const acadCohortSchema ={ cohortName:{ type: String, regEx: /AY\s\d\d\d\d\/\d\d\d\d/ }, cohortFocusAreaID:{ type: [String], optional: true }, cohortGradRequirementID: { type: [String], optional: true } } export const AcademicCohort = new AcadCohortCollection("AcademicCohort"); AcademicCohort.attachSchema(acadCohortSchema);
import { Mongo } from 'meteor/mongo'; import { SimpleSchema } from 'meteor/aldeed:simple-schema'; class AcadCohortCollection extends Mongo.Collection{ insert(acadCohortData, callBack){ const cohortDocument = acadCohortData; let result; //validate document return super.insert( cohortDocument, callBack); }; update(selector, modifier){ const result = super.update(selector, modifier); return result; }; remove(selector){ const result = super.remove(selector); return result; }; } const acadCohortSchema ={ cohortName:{ type: String, regEx: /AY\s\d\d\d\d\/\d\d\d\d/ }, cohortFocusAreaID:{ type: [String], optional: true } } export const AcademicCohort = new AcadCohortCollection("AcademicCohort"); AcademicCohort.attachSchema(acadCohortSchema);
Add timestamp to touch positions
'use strict'; var Feature = require('./Feature'); /** * @constructor * @extends Feature */ var TouchScrolling = Feature.extend('TouchScrolling', { handleTouchStart: function(grid, event) { this.lastTouch = this.getTouchedCell(grid, event); }, handleTouchMove: function(grid, event) { var currentTouch = this.getTouchedCell(grid, event); var lastTouch = this.lastTouch; var xOffset = (lastTouch.x - currentTouch.x) / lastTouch.width; var yOffset = (lastTouch.y - currentTouch.y) / lastTouch.height; grid.sbHScroller.index += xOffset; grid.sbVScroller.index += yOffset; this.lastTouch = currentTouch; }, getTouchedCell: function(grid, event) { var point = event.detail.touches[0]; var cell = grid.getGridCellFromMousePoint(point).cellEvent.bounds; cell.timestamp = Date.now(); return cell; } }); module.exports = TouchScrolling;
'use strict'; var Feature = require('./Feature'); /** * @constructor * @extends Feature */ var TouchScrolling = Feature.extend('TouchScrolling', { handleTouchStart: function(grid, event) { this.lastTouch = this.getTouchedCell(grid, event); }, handleTouchMove: function(grid, event) { var currentTouch = this.getTouchedCell(grid, event); var lastTouch = this.lastTouch; var xOffset = (lastTouch.x - currentTouch.x) / lastTouch.width; var yOffset = (lastTouch.y - currentTouch.y) / lastTouch.height; grid.sbHScroller.index = grid.sbHScroller.index + xOffset; grid.sbVScroller.index = grid.sbVScroller.index + yOffset; this.lastTouch = currentTouch; }, getTouchedCell: function(grid, event) { var point = event.detail.touches[0]; return grid.getGridCellFromMousePoint(point).cellEvent.bounds; } }); module.exports = TouchScrolling;
Update capability attach event to non-deprecated call
package gr8pefish.openglider.common.event; import gr8pefish.openglider.common.capabilities.OpenGliderCapabilities; import gr8pefish.openglider.common.capabilities.PlayerGlidingCapability; import gr8pefish.openglider.common.lib.ModInfo; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.ResourceLocation; import net.minecraftforge.event.AttachCapabilitiesEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; public class ServerEventHandler { @SubscribeEvent public void onAttachCapability(AttachCapabilitiesEvent<Entity> event) { if (event.getObject() instanceof EntityPlayer) { if (!event.getObject().hasCapability(OpenGliderCapabilities.GLIDING_CAPABILITY, null)) { event.addCapability(new ResourceLocation(ModInfo.MODID + "." + ModInfo.GLIDING_CAPABILITY_STRING), new PlayerGlidingCapability()); } } } }
package gr8pefish.openglider.common.event; import gr8pefish.openglider.common.capabilities.OpenGliderCapabilities; import gr8pefish.openglider.common.capabilities.PlayerGlidingCapability; import gr8pefish.openglider.common.lib.ModInfo; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.ResourceLocation; import net.minecraftforge.event.AttachCapabilitiesEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; public class ServerEventHandler { @SubscribeEvent public void onAttachCapability(AttachCapabilitiesEvent.Entity event) { if (event.getEntity() instanceof EntityPlayer) { if (!event.getEntity().hasCapability(OpenGliderCapabilities.GLIDING_CAPABILITY, null)) { event.addCapability(new ResourceLocation(ModInfo.MODID + "." + ModInfo.GLIDING_CAPABILITY_STRING), new PlayerGlidingCapability()); } } } }
Update theater view to use get_object_or_404 shortcut
from django.http import Http404 from django.http import HttpResponse from django.shortcuts import get_object_or_404, render from django.template import RequestContext, loader from .models import Theater # Default first page. Should be the search page. def index(request): return HttpResponse("Hello, world. You're at the ITDB_Main index. This is where you will be able to search.") # page for Theaters & theater details. Will show the details about a theater, and a list of Productions. def theaters(request): all_theaters_by_alpha = Theater.objects.order_by('name') context = RequestContext(request, {'all_theaters_by_alpha': all_theaters_by_alpha}) return render(request, 'ITDB_Main/theaters.html',context) def theater_detail(request, theater_id): theater = get_object_or_404(Theater, pk=theater_id) return render(request, 'ITDB_Main/theater_detail.html', {'theater' : theater}) # page for People def person(request): return HttpResponse("Page showing a single person - e.g. actor, director, writer, followed by a list of Productions") # page for Plays def play(request): return HttpResponse("Page showing a single play, followed by a list of Productions") # page for Productions def production(request): return HttpResponse("Page showing a single production, with details about theater and play, followed by a list of People")
from django.http import Http404 from django.http import HttpResponse from django.shortcuts import render from django.template import RequestContext, loader from .models import Theater # Default first page. Should be the search page. def index(request): return HttpResponse("Hello, world. You're at the ITDB_Main index. This is where you will be able to search.") # page for Theaters & theater details. Will show the details about a theater, and a list of Productions. def theaters(request): all_theaters_by_alpha = Theater.objects.order_by('name') context = RequestContext(request, {'all_theaters_by_alpha': all_theaters_by_alpha}) return render(request, 'ITDB_Main/theaters.html',context) def theater_detail(request, theater_id): try: theater = Theater.objects.get(pk=theater_id) except Theater.DoesNotExist: raise Http404("Theater does not exist") return render(request, 'ITDB_Main/theater_detail.html', {'theater' : theater}) # page for People def person(request): return HttpResponse("Page showing a single person - e.g. actor, director, writer, followed by a list of Productions") # page for Plays def play(request): return HttpResponse("Page showing a single play, followed by a list of Productions") # page for Productions def production(request): return HttpResponse("Page showing a single production, with details about theater and play, followed by a list of People")
Fix comment relating HTTP to be more generic.
package net.morimekta.providence.util; import net.morimekta.providence.PServiceCall; import javax.annotation.Nullable; import java.util.concurrent.TimeUnit; /** * Interface handling the instrumentation of service calls. */ @FunctionalInterface public interface ServiceCallInstrumentation { /** * After each service call this method is called with the duration, call and * response objects. Exceptions from the call is ignored, and will not affect * the response in any way. * <p> * Note that the timing may not include the whole stack time since receiving * the first packet, that is dependent on the specific implementation and the * limitations there. E.g. it does not include the time receiving the first * HTTP packet with the headers, or waiting for free worker threads when using * <code>ProvidenceServlet</code>. * * @param duration The duration of handling the service call in milliseconds, * including receiving and sending it. * @param call The call triggered. * @param reply The reply returned. */ void afterCall(double duration, @Nullable PServiceCall call, @Nullable PServiceCall reply); /** * Handy constant for calculating MS duration. */ long NS_IN_MILLIS = TimeUnit.MILLISECONDS.toNanos(1); }
package net.morimekta.providence.util; import net.morimekta.providence.PServiceCall; import javax.annotation.Nullable; import java.util.concurrent.TimeUnit; /** * Interface handling the instrumentation of service calls. */ @FunctionalInterface public interface ServiceCallInstrumentation { /** * After each service call this method is called with the duration, call and * response objects. Exceptions from the call is ignored, and will not affect * the response in any way. * * @param duration The duration of handling the service call in milliseconds, * including receiving and sending it. It does not include the * time receiving the first HTTP packet with the headers, or * waiting for free worker threads. * @param call The call triggered. * @param response The response returned. */ void afterCall(double duration, @Nullable PServiceCall call, @Nullable PServiceCall response); /** * Handy constant for calculating MS duration. */ long NS_IN_MILLIS = TimeUnit.MILLISECONDS.toNanos(1); }
Include context properties in track() calls [#131391691]
'use strict'; const _ = require('underscore'); const app = require('express')(); const Analytics = require('analytics-node'); const { secrets } = require('app/config/config'); const { guid } = require('./users'); const segmentKey = process.env.SEGMENT_WRITE_KEY || secrets.segmentKey; const env = app.get('env'); let analytics; // Flush events immediately if on dev environment if (env !== 'production') { analytics = new Analytics(segmentKey, { flushAt: 1 }); } else { analytics = new Analytics(segmentKey); } function generateOpts() { return { // Log the environment to differentiate events from production vs dev context: { environment: env } }; } module.exports = { // https://segment.com/docs/sources/server/node/#identify identify(user) { let opts = generateOpts(); if (!user) { opts.anonymousId = guid(); } else { const { id: userId, email, name, username } = user; opts = { userId, traits: { name, email, username } }; } analytics.identify(opts); }, // https://segment.com/docs/sources/server/node/#track track(user, event, properties) { const { id: userId } = user; let opts = _.extend(generateOpts(), { userId, event, properties }); analytics.track(opts); } };
'use strict'; const app = require('express')(); const Analytics = require('analytics-node'); const { secrets } = require('app/config/config'); const { guid } = require('./users'); const segmentKey = process.env.SEGMENT_WRITE_KEY || secrets.segmentKey; const env = app.get('env'); let analytics; // Flush events immediately if on dev environment if (env !== 'production') { analytics = new Analytics(segmentKey, { flushAt: 1 }); } else { analytics = new Analytics(segmentKey); } module.exports = { // https://segment.com/docs/sources/server/node/#identify identify(user) { let opts = {}; if (!user) { opts.anonymousId = guid(); } else { const { id: userId, email, name, username } = user; opts = { userId, traits: { name, email, username } }; } // Log the environment to differentiate events from production vs dev opts.context = { environment: env }; analytics.identify(opts); }, // https://segment.com/docs/sources/server/node/#track track(user, event, properties) { const { id: userId } = user; let opts = { userId, event, properties }; analytics.track(opts); } };
Remove js extension from log labels
var winston = require('winston'), path = require('path'); var logLevel = 'warn'; var sharedLogger = function(filename) { return new winston.Logger({ transports: [ new winston.transports.Console({ prettyPrint: true, timestamp: true, level: logLevel, label: path.basename(filename, '.js') }) ] }); }; sharedLogger.setLevel = function (val) { logLevel = val; } function failedPromiseHandler(logger) { logger = logger || sharedLogger; return function(err) { logger.error(err.stack); }; } function uuid() { return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); return v.toString(16); }); } module.exports = { logger: sharedLogger, failedPromiseHandler: failedPromiseHandler, uuid: uuid }
var winston = require('winston'), path = require('path'); var logLevel = 'warn'; var sharedLogger = function(filename) { return new winston.Logger({ transports: [ new winston.transports.Console({ prettyPrint: true, timestamp: true, level: logLevel, label: path.basename(filename) }) ] }); }; sharedLogger.setLevel = function (val) { logLevel = val; } function failedPromiseHandler(logger) { logger = logger || sharedLogger; return function(err) { logger.error(err.stack); }; } function uuid() { return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); return v.toString(16); }); } module.exports = { logger: sharedLogger, failedPromiseHandler: failedPromiseHandler, uuid: uuid }
Add open api generation template
const Server = require('dominion'); const Config = use('config'); Server.addComponent(require('./components/sessions')); Server.addComponent(require('./components/permissions')); Server.addComponent(require('./components/accounts')); Server.addComponent(require('./components/tracking')); Server.addComponent(require('./components/logging')); Server.addComponent(require('./components/authorize')); Server.addComponent(require('./components/notifications')); Server.addComponent(require('./components/media')); Server.addComponent(require('./components/favorites')); Server.start(Config); /* *** OpenAPI documentation *** if (Config.env.development) { const fs = require("fs"); const openAPIJSON = Server.openApiJSON({ "title": "Awesome APIs", "description": "Awesome APIs", "version": "1.0.0", "contact": { "email": "yura.chaikovsky@gmail.com" } }); fs.writeFileSync("<filePath>", JSON.stringify(openAPIJSON, null, 4)); } */
const Server = require('dominion'); const Config = use('config'); Server.addComponent(require('./components/sessions')); Server.addComponent(require('./components/permissions')); Server.addComponent(require('./components/accounts')); Server.addComponent(require('./components/tracking')); Server.addComponent(require('./components/logging')); Server.addComponent(require('./components/authorize')); Server.addComponent(require('./components/notifications')); Server.addComponent(require('./components/media')); Server.addComponent(require('./components/favorites')); Server.start(Config); /* *** OpenAPI documentation *** const fs = require("fs"); const openAPIJSON = Server.openApiJSON({ "title": "Awesome APIs", "description": "Awesome APIs", "version": "1.0.0", "contact": { "email": "yura.chaikovsky@gmail.com" } }); fs.writeFileSync("<filePath>", JSON.stringify(openAPIJSON, null, 4)); */
Add tests for curried merge
import toolz import toolz.curried from toolz.curried import (take, first, second, sorted, merge_with, reduce, merge) from collections import defaultdict from operator import add def test_take(): assert list(take(2)([1, 2, 3])) == [1, 2] def test_first(): assert first is toolz.itertoolz.first def test_merge(): assert merge(factory=lambda: defaultdict(int))({1: 1}) == {1: 1} assert merge({1: 1}) == {1: 1} assert merge({1: 1}, factory=lambda: defaultdict(int)) == {1: 1} def test_merge_with(): assert merge_with(sum)({1: 1}, {1: 2}) == {1: 3} def test_merge_with_list(): assert merge_with(sum, [{'a': 1}, {'a': 2}]) == {'a': 3} def test_sorted(): assert sorted(key=second)([(1, 2), (2, 1)]) == [(2, 1), (1, 2)] def test_reduce(): assert reduce(add)((1, 2, 3)) == 6 def test_module_name(): assert toolz.curried.__name__ == 'toolz.curried'
import toolz import toolz.curried from toolz.curried import take, first, second, sorted, merge_with, reduce from operator import add def test_take(): assert list(take(2)([1, 2, 3])) == [1, 2] def test_first(): assert first is toolz.itertoolz.first def test_merge_with(): assert merge_with(sum)({1: 1}, {1: 2}) == {1: 3} def test_merge_with_list(): assert merge_with(sum, [{'a': 1}, {'a': 2}]) == {'a': 3} def test_sorted(): assert sorted(key=second)([(1, 2), (2, 1)]) == [(2, 1), (1, 2)] def test_reduce(): assert reduce(add)((1, 2, 3)) == 6 def test_module_name(): assert toolz.curried.__name__ == 'toolz.curried'
Add Types\Datetime test for empty value
<?php use Mdd\QueryBuilder\Types; use Mdd\QueryBuilder\Tests\Escapers\SimpleEscaper; class DatetimeTest extends PHPUnit_Framework_TestCase { protected $escaper; protected function setUp() { $this->escaper = new SimpleEscaper(); } /** * @dataProvider providerTestFormatDatetime */ public function testFormatDatetime($expected, $value) { $type = new Types\Datetime($value); $this->assertSame($expected, $type->getValue()); } public function providerTestFormatDatetime() { return array( 'string' => array('2014-12-10 13:37:42', '2014-12-10 13:37:42'), 'empty value' => array('', ''), 'datetime #1' => array('2014-12-10 13:37:42', \DateTime::createFromFormat('Y-m-d H:i:s', '2014-12-10 13:37:42')), ); } }
<?php use Mdd\QueryBuilder\Types; use Mdd\QueryBuilder\Tests\Escapers\SimpleEscaper; class DatetimeTest extends PHPUnit_Framework_TestCase { protected $escaper; protected function setUp() { $this->escaper = new SimpleEscaper(); } /** * @dataProvider providerTestFormatDatetime */ public function testFormatDatetime($expected, $value) { $type = new Types\Datetime($value); $this->assertSame($expected, $type->getValue()); } public function providerTestFormatDatetime() { return array( 'string' => array('2014-12-10 13:37:42', '2014-12-10 13:37:42'), 'datetime #1' => array('2014-12-10 13:37:42', \DateTime::createFromFormat('Y-m-d H:i:s', '2014-12-10 13:37:42')), ); } }
Send platform name to defaul template context
import os from datetime import datetime import attr from jinja2 import Environment, FileSystemLoader, select_autoescape @attr.s class Message: id = attr.ib() platform = attr.ib() user = attr.ib() text = attr.ib() timestamp = attr.ib() raw = attr.ib() @property def datetime(self): return datetime.utcfromtimestamp(self.timestamp) def render(message, template_name, context={}): base_dir = os.path.join(os.getcwd(), 'templates') paths = [base_dir] # Include paths on settings # paths.extend(settings.TEMPLATES) env = Environment( loader=FileSystemLoader(paths), autoescape=select_autoescape(['html'])) template = env.get_template(template_name) default_context = { 'user': message.user, 'platform': message.platform, } default_context.update(context) return template.render(**default_context)
import os from datetime import datetime import attr from jinja2 import Environment, FileSystemLoader, select_autoescape @attr.s class Message: id = attr.ib() platform = attr.ib() user = attr.ib() text = attr.ib() timestamp = attr.ib() raw = attr.ib() @property def datetime(self): return datetime.utcfromtimestamp(self.timestamp) def render(message, template_name, context={}): base_dir = os.path.join(os.getcwd(), 'templates') paths = [base_dir] # Include paths on settings # paths.extend(settings.TEMPLATES) env = Environment( loader=FileSystemLoader(paths), autoescape=select_autoescape(['html'])) template = env.get_template(template_name) default_context = { 'user': message.user } default_context.update(context) return template.render(**default_context)
Use String() instead of toString()
import JsSha from 'jssha'; import {query, rfc3986} from '../util'; export default function buildHeaderString( {consumerKey, consumerSecret, oauthToken = '', oauthTokenSecret = ''}, url, method, params = {}, extraParams = {}, {nonce = String(Math.random()).slice(2), timestamp = Math.floor(Date.now() / 1000)} = {}, ) { const oauthParams = { oauth_consumer_key: consumerKey, oauth_nonce: nonce, oauth_signature_method: 'HMAC-SHA1', oauth_timestamp: timestamp, // ...oauthToken && {oauth_token: oauthToken}, ...oauthToken ? {oauth_token: oauthToken} : {}, oauth_version: '1.0', ...extraParams, }; const shaObj = new JsSha('SHA-1', 'TEXT'); shaObj.setHMACKey(`${rfc3986(consumerSecret)}&${rfc3986(oauthTokenSecret)}`, 'TEXT'); shaObj.update( `${rfc3986(method)}&${rfc3986(url)}&${rfc3986(query({...params, ...oauthParams}, true))}`, ); return `OAuth ${ Object.entries({ ...oauthParams, oauth_signature: shaObj.getHMAC('B64'), }) .map(([k, v]) => `${rfc3986(k)}="${rfc3986(v)}"`) .join(', ') }`; }
import JsSha from 'jssha'; import {query, rfc3986} from '../util'; export default function buildHeaderString( {consumerKey, consumerSecret, oauthToken = '', oauthTokenSecret = ''}, url, method, params = {}, extraParams = {}, {nonce = Math.random().toString().slice(2), timestamp = Math.floor(Date.now() / 1000)} = {}, ) { const oauthParams = { oauth_consumer_key: consumerKey, oauth_nonce: nonce, oauth_signature_method: 'HMAC-SHA1', oauth_timestamp: timestamp, // ...oauthToken && {oauth_token: oauthToken}, ...oauthToken ? {oauth_token: oauthToken} : {}, oauth_version: '1.0', ...extraParams, }; const shaObj = new JsSha('SHA-1', 'TEXT'); shaObj.setHMACKey(`${rfc3986(consumerSecret)}&${rfc3986(oauthTokenSecret)}`, 'TEXT'); shaObj.update( `${rfc3986(method)}&${rfc3986(url)}&${rfc3986(query({...params, ...oauthParams}, true))}`, ); return `OAuth ${ Object.entries({ ...oauthParams, oauth_signature: shaObj.getHMAC('B64'), }) .map(([k, v]) => `${rfc3986(k)}="${rfc3986(v)}"`) .join(', ') }`; }
Set a default if the browser doesn't send the DNT header
# This file is part of Workout Manager. # # Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Workout Manager is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Workout Manager. If not, see <http://www.gnu.org/licenses/>. from workout_manager import get_version def processor(request): return { # Application version 'version' : get_version(), # Do not track header 'DNT': request.META.get('HTTP_DNT', False) }
# This file is part of Workout Manager. # # Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Workout Manager is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Workout Manager. If not, see <http://www.gnu.org/licenses/>. from workout_manager import get_version def processor(request): return { # Application version 'version' : get_version(), # Do not track header 'DNT': request.META['HTTP_DNT'] }
Modify test to reflect new data being passed in.
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent('search-facet-worktype', 'Integration | Component | search facet worktype', { integration: true }); test('it renders', function(assert) { this.set('key', 'type'); this.set('title', 'Type'); this.set('state', ['Publication']); this.set('filter', ''); this.set('onChange', () => {}); this.set('processedTypes', {'presentation': {} }); this.render(hbs`{{search-facet-worktype key=key state=state filter=filter onChange=(action onChange) selected=selected processedTypes=processedTypes }}`); assert.equal(this.$('.type-filter-option')[0].innerText.trim(), 'Presentation'); });
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent('search-facet-worktype', 'Integration | Component | search facet worktype', { integration: true }); test('it renders', function(assert) { this.set('key', 'type'); this.set('title', 'Type'); this.set('state', ['Publication']); this.set('filter', ''); this.set('onChange', () => {}); this.set('data', {'presentation': {} }); this.render(hbs`{{search-facet-worktype key=key state=state filter=filter onChange=(action onChange) selected=selected data=data }}`); assert.equal(this.$('.type-filter-option')[0].innerText.trim(), 'Presentation'); });
Add condition to avoid notices
<?php namespace Algolia\AlgoliaSearchBundle\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader; /** * This is the class that loads and manages your bundle configuration * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ class AlgoliaAlgoliaSearchExtension extends Extension { /** * {@inheritdoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); if (isset($config['application_id'])) $container->setParameter('algolia.application_id', $config['application_id']); if (isset($config['api_key'])) $container->setParameter('algolia.api_key', $config['api_key']); $container->setParameter('algolia.catch_log_exceptions', $config['catch_log_exceptions']); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.yml'); } public function getAlias() { return 'algolia'; } }
<?php namespace Algolia\AlgoliaSearchBundle\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader; /** * This is the class that loads and manages your bundle configuration * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ class AlgoliaAlgoliaSearchExtension extends Extension { /** * {@inheritdoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $container->setParameter('algolia.application_id', $config['application_id']); $container->setParameter('algolia.api_key', $config['api_key']); $container->setParameter('algolia.catch_log_exceptions', $config['catch_log_exceptions']); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.yml'); } public function getAlias() { return 'algolia'; } }
Fix some minor formatting issues
import smbus import time ADDRESS = 4 CMD_READ_ANALOG = 1 VOLT12 = 650 VOLT18 = 978 def map_range(x, in_min, in_max, out_min, out_max): out_delta = out_max - out_min in_delta = in_max - in_min return (x - in_min) * out_delta / in_delta + out_min class Voltage: def __init__(self): self.bus = smbus.SMBus(1) def get_data(self): voltage_time = time.time() voltage_raw = self.bus.read_word_data(ADDRESS, CMD_READ_ANALOG) voltage = map_range(voltage_raw, VOLT12, VOLT18, 12, 18) return [ (voltage_time, "voltage_raw", voltage_raw), (voltage_time, "voltage", voltage) ]
import smbus import time ADDRESS = 4 CMD_READ_ANALOG = 1 VOLT12 = 650 VOLT18 = 978 def map_range(x, in_min, in_max, out_min, out_max): out_delta = out_max - out_min in_delta = in_max - in_min return (x - in_min) * out_delta / in_delta + out_min class Voltage: def __init__(self): self.bus = smbus.SMBus(1) def get_data(self): voltage_time = time.time(); voltage_raw = self.bus.read_word_data(ADDRESS, CMD_READ_ANALOG) voltage = map_range(voltage_raw, VOLT12, VOLT18, 12, 18) return [ (voltage_time, "voltage_raw", voltage_raw), (voltage_time, "voltage", voltage) ]
Test closing github issue automatically for default branch Fixes #5
(function() { 'use strict'; let path = require('path'); let express = require('express'); let http = require('http'); let _ = require('lodash'); let bodyParser = require('body-parser'); let sseExpress = require('sse-express'); let app = express(); let globalId = 1; let connections = []; app.use(bodyParser.urlencoded({ // to support URL-encoded bodies extended: true })); app.use((req, res, next) => { // setup cors headers res.setHeader('Access-Control-Allow-Origin', '*'); next(); }); app.post('/sendMessage', (req, res) => { res.writeHead(200, { 'Access-Control-Allow-Origin': '*' }); connections.forEach(function(connection) { connection.sse('message', { text: req.body.message, userId: req.body.userId }); }); res.end(); }); app.get('/updates', sseExpress, function(req, res) { connections.push(res); // send id to user res.sse('connected', { id: globalId }); globalId++; req.on("close", function() { _.remove(connections, res); console.log('clients: ' + connections.length); }); console.log(`Hello, ${globalId}!`); }); app.listen(99, function () { console.log('Example app listening on port 99!'); }); })();
(function() { 'use strict'; let path = require('path'); let express = require('express'); let http = require('http'); let _ = require('lodash'); let bodyParser = require('body-parser'); let sseExpress = require('sse-express'); let app = express(); let globalId = 1; let connections = []; app.use(bodyParser.urlencoded({ // to support URL-encoded bodies extended: true })); app.use((req, res, next) => { // setup cors res.setHeader('Access-Control-Allow-Origin', '*'); next(); }); app.post('/sendMessage', (req, res) => { res.writeHead(200, { 'Access-Control-Allow-Origin': '*' }); connections.forEach(function(connection) { connection.sse('message', { text: req.body.message, userId: req.body.userId }); }); res.end(); }); app.get('/updates', sseExpress, function(req, res) { connections.push(res); // send id to user res.sse('connected', { id: globalId }); globalId++; req.on("close", function() { _.remove(connections, res); console.log('clients: ' + connections.length); }); console.log(`Hello, ${globalId}!`); }); app.listen(99, function () { console.log('Example app listening on port 99!'); }); })();
Replace magic strings with constants
from os.path import join from os import mkdir, getcwd from bank import split_bank from errors import BotError FEATURE_BANK_FILENAME = "features.bank" FEATURES_DIRECTORY = "features" OUTPUT_FEATURES_FILENAME = join(FEATURES_DIRECTORY, "all.feature") class Dealer(object): def __init__(self): self.__feature = "" self.__scenarios = [] def assign(self): try: with open(FEATURE_BANK_FILENAME, "rb") as bank_input: (header, self.__feature, self.__scenarios) = split_bank(bank_input.read()) except IOError: raise BotError("No features bank in {:s}".format(getcwd())) if not self.__feature: print("No more scenarios to deal") mkdir(FEATURES_DIRECTORY) with open(OUTPUT_FEATURES_FILENAME, "wb") as features: features.write(header) features.write(self.__feature) if self.__scenarios: features.write(self.__scenarios[0])
from os import mkdir, getcwd from bank import split_bank from errors import BotError class Dealer(object): def __init__(self): self.__feature = "" self.__scenarios = [] def assign(self): try: with open("features.bank", "rb") as bank_input: (header, self.__feature, self.__scenarios) = split_bank(bank_input.read()) except IOError: raise BotError("No features bank in {:s}".format(getcwd())) if not self.__feature: print("No more scenarios to deal") mkdir("features") with open("features/all.feature", "wb") as features: features.write(header) features.write(self.__feature) if self.__scenarios: features.write(self.__scenarios[0])
Fix bug in copy_glob when destination directory already has files
import glob import shutil import os if os.name == "nt": from .ntcommonpath import commonpath else: from .posixcommonpath import commonpath def move_glob(src,dst): """Moves files from src to dest. src may be any glob to recognize files. dst must be a folder.""" for obj in glob.iglob(src): shutil.move(obj,dst) def copy_glob(src,dst): """Copies files from src to dest. src may be any glob to recognize files. dst must be a folder.""" for obj in glob.iglob(src): if os.path.isdir(obj): start_part=commonpath([src,obj]) end_part=os.path.relpath(obj,start_part) ctree_dst=os.path.join(dst,end_part) if not os.path.isdir(ctree_dst): shutil.copytree(obj,ctree_dst) else: copy_glob(os.path.join(obj,"*"),ctree_dst) else: shutil.copy2(obj,dst)
import glob import shutil import os if os.name == "nt": from .ntcommonpath import commonpath else: from .posixcommonpath import commonpath def move_glob(src,dst): """Moves files from src to dest. src may be any glob to recognize files. dst must be a folder.""" for obj in glob.iglob(src): shutil.move(obj,dst) def copy_glob(src,dst): """Copies files from src to dest. src may be any glob to recognize files. dst must be a folder.""" for obj in glob.iglob(src): if os.path.isdir(obj): start_part=commonpath([src,obj]) end_part=os.path.relpath(obj,start_part) shutil.copytree(obj,os.path.join(dst,end_part)) else: shutil.copy2(obj,dst)
Add 2.7 to PyPI trove classifiers
# encoding: utf-8 from distutils.core import setup setup( name='json-store', version='1.1', packages=['json_store'], scripts=['bin/shelve2json.py'], description="A shelve-like store using JSON serialization.", long_description="JSON store is a simple replacement for shelve. It writes" " JSON serialized files and can accept unicode keys.", author='jeremy avnet', author_email='brainsik-code@theory.org', license='MIT License', url='https://github.com/brainsik/json-store', download_url='http://pypi.python.org/packages/source/j/json-store/json-store-1.1.tar.gz', classifiers=['Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7'] )
# encoding: utf-8 from distutils.core import setup setup( name='json-store', version='1.1', packages=['json_store',], scripts=['bin/shelve2json.py',], description="A shelve-like store using JSON serialization.", long_description="JSON store is a simple replacement for shelve. It writes" " JSON serialized files and can accept unicode keys.", author='jeremy avnet', author_email='brainsik-code@theory.org', license='MIT License', url='https://github.com/brainsik/json-store', download_url='http://pypi.python.org/packages/source/j/json-store/json-store-1.1.tar.gz', classifiers=['Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.6',] )
Switch to web integration test
package integration; import hello.Application; import org.fluentlenium.adapter.FluentTest; import org.junit.Test; import org.junit.runner.RunWith; import org.openqa.selenium.WebDriver; import org.openqa.selenium.phantomjs.PhantomJSDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.*; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @WebIntegrationTest("server.port:0") public class GreetingTest extends FluentTest { @Value("${local.server.port}") private int port; private DesiredCapabilities capabilities = DesiredCapabilities.phantomjs(); private WebDriver driver = new PhantomJSDriver(capabilities); @Override public WebDriver getDefaultDriver() { return driver; } @Test public void testGetIndex() { goTo("http://127.0.0.1:" + port + "/greeting?name=Sam"); assertThat(pageSource()).contains("Hello, Sam!"); goTo("http://127.0.0.1:" + port + "/greeting?name=Bob"); assertThat(pageSource()).contains("Hello, Bob!"); } }
package integration; import hello.Application; import org.fluentlenium.adapter.FluentTest; import org.junit.Test; import org.junit.runner.RunWith; import org.openqa.selenium.WebDriver; import org.openqa.selenium.phantomjs.PhantomJSDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.*; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @WebAppConfiguration @IntegrationTest("server.port:0") public class GreetingTest extends FluentTest { @Value("${local.server.port}") private int port; private DesiredCapabilities capabilities = DesiredCapabilities.phantomjs(); private WebDriver driver = new PhantomJSDriver(capabilities); @Override public WebDriver getDefaultDriver() { return driver; } @Test public void testGetIndex() { goTo("http://127.0.0.1:" + port + "/greeting?name=Sam"); assertThat(pageSource()).contains("Hello, Sam!"); goTo("http://127.0.0.1:" + port + "/greeting?name=Bob"); assertThat(pageSource()).contains("Hello, Bob!"); } }
FIX - beat.sh is now called by bash and not python
""" Author: Ashish Gaikwad <ash.gkwd@gmail.com> Copyright (c) 2015 Ashish Gaikwad Description: This daemon will execute command once Internet is connected. Then it will exit. """ import socket from subprocess import call import time commands = [["bash", "/usr/bin/beat.sh"]] def internet(host='8.8.8.8', port=53): try: socket.setdefaulttimeout(1) socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port)) return True except Exception as ex: pass return False def main(): print "[once-internet-is-on-d started]" while not internet(): pass time.sleep(40) for x in commands: print "[once-internet-is-on-d calling] : ", x call(x) print "[once-internet-is-on-d finished]" if __name__ == '__main__': main()
""" Author: Ashish Gaikwad <ash.gkwd@gmail.com> Copyright (c) 2015 Ashish Gaikwad Description: This daemon will execute command once Internet is connected. Then it will exit. """ import socket from subprocess import call import time commands = [["python", "/usr/bin/beat.sh"]] def internet(host='8.8.8.8', port=53): try: socket.setdefaulttimeout(1) socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port)) return True except Exception as ex: pass return False def main(): print "[once-internet-is-on-d started]" while not internet(): pass time.sleep(40) for x in commands: print "[once-internet-is-on-d calling] : ", x call(x) print "[once-internet-is-on-d finished]" if __name__ == '__main__': main()
Fix global storage directory name.
"use strict"; const Storage = require("node-storage"); const os = require('os'); const GLOBAL_STORE_ROOT = os.homedir() + "/.drup/"; const GLOBAL_STORE = { config : { path: "config.json" }, projects : { path: "projects.json" }, }; let openStorages = {}; class DrupStorage { constructor(file) { this.driver = new Storage(file); } set(key, value) { this.driver.put(key, value); } get(key) { return this.driver.get(key); } remove(key) { this.driver.remove(key); } } module.exports = { get config() { return this.get(GLOBAL_STORE_ROOT + GLOBAL_STORE.config.path); }, get projects() { return this.get(GLOBAL_STORE_ROOT + GLOBAL_STORE.projects.path); }, get(file) { if (!openStorages[file]) { openStorages[file] = new DrupStorage(file); } return openStorages[file]; } };
"use strict"; const Storage = require("node-storage"); const os = require('os'); const GLOBAL_STORE_ROOT = os.homedir() + "/.src/"; const GLOBAL_STORE = { config : { path: "config.json" }, projects : { path: "projects.json" }, }; let openStorages = {}; class DrupStorage { constructor(file) { this.driver = new Storage(file); } set(key, value) { this.driver.put(key, value); } get(key) { return this.driver.get(key); } remove(key) { this.driver.remove(key); } } module.exports = { get config() { return this.get(GLOBAL_STORE_ROOT + GLOBAL_STORE.config.path); }, get projects() { return this.get(GLOBAL_STORE_ROOT + GLOBAL_STORE.projects.path); }, get(file) { if (!openStorages[file]) { openStorages[file] = new DrupStorage(file); } return openStorages[file]; } };
Fix global name of vtk module It is exposed as "vtk", not "vtkjs".
// The lean build does not include any of the third-party runtime dependencies, rather // it assumes they are in the global namespace at runtime. var config = require('./webpack.base.config'); var merge = require('webpack-merge'); module.exports = merge(config, { entry: { 'geo.lean': './index.js', 'geo.lean.min': './index.js' }, externals: { d3: 'd3', hammerjs: { root: 'Hammer', commonjs: 'hammerjs', commonjs2: 'hammerjs', amd: 'hammerjs', // Since GeoJS's libraryTarget is "umd", defining this (undocumented) external library type // will allow Webpack to create a better error message if a "hammerjs" import fails umd: 'hammerjs' }, 'vtk.js': 'vtk' } });
// The lean build does not include any of the third-party runtime dependencies, rather // it assumes they are in the global namespace at runtime. var config = require('./webpack.base.config'); var merge = require('webpack-merge'); module.exports = merge(config, { entry: { 'geo.lean': './index.js', 'geo.lean.min': './index.js' }, externals: { d3: 'd3', hammerjs: { root: 'Hammer', commonjs: 'hammerjs', commonjs2: 'hammerjs', amd: 'hammerjs', // Since GeoJS's libraryTarget is "umd", defining this (undocumented) external library type // will allow Webpack to create a better error message if a "hammerjs" import fails umd: 'hammerjs' }, 'vtk.js': 'vtkjs' } });
Correct documentation for path to load test runner
from __future__ import absolute_import from django.conf import settings from django.test.simple import DjangoTestSuiteRunner USAGE = """\ Custom test runner to allow testing of celery delayed tasks. """ class CeleryTestSuiteRunner(DjangoTestSuiteRunner): """Django test runner allowing testing of celery delayed tasks. All tasks are run locally, not in a worker. To use this runner set ``settings.TEST_RUNNER``:: TEST_RUNNER = "djcelery.contrib.test_runner.CeleryTestSuiteRunner" """ def setup_test_environment(self, **kwargs): super(CeleryTestSuiteRunner, self).setup_test_environment(**kwargs) settings.CELERY_ALWAYS_EAGER = True settings.CELERY_EAGER_PROPAGATES_EXCEPTIONS = True # Issue #75
from __future__ import absolute_import from django.conf import settings from django.test.simple import DjangoTestSuiteRunner USAGE = """\ Custom test runner to allow testing of celery delayed tasks. """ class CeleryTestSuiteRunner(DjangoTestSuiteRunner): """Django test runner allowing testing of celery delayed tasks. All tasks are run locally, not in a worker. To use this runner set ``settings.TEST_RUNNER``:: TEST_RUNNER = "celery.contrib.test_runner.CeleryTestSuiteRunner" """ def setup_test_environment(self, **kwargs): super(CeleryTestSuiteRunner, self).setup_test_environment(**kwargs) settings.CELERY_ALWAYS_EAGER = True settings.CELERY_EAGER_PROPAGATES_EXCEPTIONS = True # Issue #75
Fix create example jobs reqire paths
const config = require('../config/config'); const Mongoose = require('mongoose'); const Job = require('../src/models/job'); //Mongoose connection var mongoose = Mongoose.connect(config.mongoDBPath, { useMongoClient: true }) .then(() => { console.log('Connected to MongoDB at ', config.mongoDBPath); return Mongoose.connection; }) .catch(err => console.log(`Database connection error: ${err.message}`)); mongoose.Promise = global.Promise; var job = new Job({ name: '5 minutes', pair: 'BTC-EUR', amount: '1', gdax: { secret: ``, key: ``, passphrase: ``, URI: `` } }); job.save(function(err) { if (err) throw err; console.log('User saved successfully!'); });
const config = require('./config/config'); const Mongoose = require('mongoose'); const Job = require('./src/models/job'); //Mongoose connection var mongoose = Mongoose.connect(config.mongoDBPath, { useMongoClient: true }) .then(() => { console.log('Connected to MongoDB at ', config.mongoDBPath); return Mongoose.connection; }) .catch(err => console.log(`Database connection error: ${err.message}`)); mongoose.Promise = global.Promise; var job = new Job({ name: '5 minutes', pair: 'BTC-EUR', amount: '1', gdax: { secret: ``, key: ``, passphrase: ``, URI: `` } }); job.save(function(err) { if (err) throw err; console.log('User saved successfully!'); });
Fix validation of news creation form
""" byceps.blueprints.news_admin.forms ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2017 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ import re from wtforms import StringField, TextAreaField from wtforms.validators import InputRequired, Length, Optional, Regexp from ...util.l10n import LocalizedForm SLUG_REGEX = re.compile('^[a-z0-9-]+$') class ItemCreateForm(LocalizedForm): slug = StringField('Slug', [InputRequired(), Length(max=80), Regexp(SLUG_REGEX, message='Nur Kleinbuchstaben, Ziffern und Bindestrich sind erlaubt.')]) title = StringField('Titel', [InputRequired(), Length(max=80)]) body = TextAreaField('Text', [InputRequired()]) image_url_path = StringField('Bild-URL-Pfad', [Optional(), Length(max=80)]) class ItemUpdateForm(ItemCreateForm): pass
""" byceps.blueprints.news_admin.forms ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2017 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ import re from wtforms import StringField, TextAreaField from wtforms.validators import InputRequired, Length, Optional, Regexp from ...util.l10n import LocalizedForm SLUG_REGEX = re.compile('^[a-z0-9-]+$') class ItemCreateForm(LocalizedForm): slug = StringField('Slug', [InputRequired(), Length(max=80), Regexp(SLUG_REGEX, message='Nur Kleinbuchstaben, Ziffern und Bindestrich sind erlaubt.')]) title = StringField('Titel', [InputRequired(), Length(max=80)]) body = TextAreaField('Text', [InputRequired(), Length(max=80)]) image_url_path = StringField('Bild-URL-Pfad', [Optional(), Length(max=80)]) class ItemUpdateForm(ItemCreateForm): pass
Fix YUI arg passing, had CSS/JS flipped
import subprocess from compress.conf import settings from compress.filter_base import FilterBase, FilterError class YUICompressorFilter(FilterBase): def filter_common(self, content, type_, arguments): command = '%s --type=%s %s' % (settings.COMPRESS_YUI_BINARY, type_, arguments) if self.verbose: command += ' --verbose' p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, \ stdin=subprocess.PIPE, stderr=subprocess.PIPE) p.stdin.write(content) p.stdin.close() filtered_css = p.stdout.read() p.stdout.close() err = p.stderr.read() p.stderr.close() if p.wait() != 0: if not err: err = 'Unable to apply YUI Compressor filter' raise FilterError(err) if self.verbose: print err return filtered_css def filter_js(self, js): return self.filter_common(js, 'js', settings.COMPRESS_YUI_JS_ARGUMENTS) def filter_css(self, css): return self.filter_common(css, 'css', settings.COMPRESS_YUI_CSS_ARGUMENTS)
import subprocess from compress.conf import settings from compress.filter_base import FilterBase, FilterError class YUICompressorFilter(FilterBase): def filter_common(self, content, type_, arguments): command = '%s --type=%s %s' % (settings.COMPRESS_YUI_BINARY, type_, arguments) if self.verbose: command += ' --verbose' p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, \ stdin=subprocess.PIPE, stderr=subprocess.PIPE) p.stdin.write(content) p.stdin.close() filtered_css = p.stdout.read() p.stdout.close() err = p.stderr.read() p.stderr.close() if p.wait() != 0: if not err: err = 'Unable to apply YUI Compressor filter' raise FilterError(err) if self.verbose: print err return filtered_css def filter_js(self, js): return self.filter_common(js, 'js', settings.COMPRESS_YUI_CSS_ARGUMENTS) def filter_css(self, css): return self.filter_common(css, 'css', settings.COMPRESS_YUI_JS_ARGUMENTS)
Set ready to true whether we have a function or not.
/** * WithRegistrySetup component. * * Site Kit by Google, Copyright 2021 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. */ /** * WordPress dependencies */ import { useEffect, useState } from '@wordpress/element'; /** * Internal dependencies */ import Data from 'googlesitekit-data'; const { useRegistry } = Data; const WithRegistrySetup = ( { func, children } ) => { const registry = useRegistry(); const [ ready, setReady ] = useState( false ); useEffect( () => { if ( func && typeof func === 'function' ) { func( registry ); } setReady( true ); } ); if ( ready ) { return children; } return null; }; export default WithRegistrySetup;
/** * WithRegistrySetup component. * * Site Kit by Google, Copyright 2021 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. */ /** * WordPress dependencies */ import { useEffect, useState } from '@wordpress/element'; /** * Internal dependencies */ import Data from 'googlesitekit-data'; const { useRegistry } = Data; const WithRegistrySetup = ( { func, children } ) => { const registry = useRegistry(); const [ ready, setReady ] = useState( false ); useEffect( () => { if ( func && typeof func === 'function' ) { func( registry ); setReady( true ); } } ); if ( ready ) { return children; } return null; }; export default WithRegistrySetup;
Add unicode representations for tags/positions
from django.db import models from django.contrib.auth.models import User class Tag(models.Model): description = models.TextField() def __unicode__(self): return self.description class Position(models.Model): company = models.TextField() job_title = models.TextField() description = models.TextField() tags = models.ManyToManyField(Tag) def __unicode__(self): return u'%s at %s' % (self.job_title, self.company) class Application(models.Model): user = models.ForeignKey(User) position = models.ForeignKey(Position) APPLIED = 'APP' REJECTED = 'REJ' INTERVIEWING = 'INT' NEGOTIATING = 'NEG' STATUS_CHOICES = ( (APPLIED, 'Applied'), (REJECTED, 'Rejected'), (INTERVIEWING, 'Interviewing'), (NEGOTIATING, 'Negotiating'), ) status = models.CharField(max_length=3, choices=STATUS_CHOICES, default=APPLIED) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True)
from django.db import models from django.contrib.auth.models import User class Tag(models.Model): description = models.TextField() class Position(models.Model): company = models.TextField() job_title = models.TextField() description = models.TextField() tags = models.ManyToManyField(Tag) class Application(models.Model): user = models.ForeignKey(User) position = models.ForeignKey(Position) APPLIED = 'APP' REJECTED = 'REJ' INTERVIEWING = 'INT' NEGOTIATING = 'NEG' STATUS_CHOICES = ( (APPLIED, 'Applied'), (REJECTED, 'Rejected'), (INTERVIEWING, 'Interviewing'), (NEGOTIATING, 'Negotiating'), ) status = models.CharField(max_length=3, choices=STATUS_CHOICES, default=APPLIED) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True)
Add GExit: the obj to pass around that can only be waited on, not .Exit()ed
package cog import "sync" // Exit is useful for terminating a group of goroutines that run in a // for{select{}}. Be sure to `Exit.Add(n)` before starting goroutines, and // `defer Exit.Done()` in the goroutine. type Exit struct { *GExit c chan struct{} once sync.Once } // GExit (short for "goroutine exit") is what should be passed to things that // need to know when to exit but that should not be able to trigger an exit. type GExit struct { sync.WaitGroup C <-chan struct{} } // Exiter is anything that can cleanup after itself at any arbitrary point in // time. type Exiter interface { Exit() } // NewExit creates a new Exit, useful for ensuring termination of goroutines on // exit. func NewExit() *Exit { e := &Exit{ GExit: &GExit{}, c: make(chan struct{}), } e.GExit.C = e.c return e } // Exit closes C and waits for all goroutines to exit. func (e *Exit) Exit() { e.once.Do(func() { close(e.c) e.Wait() }) }
package cog import "sync" // Exit is useful for terminating a group of goroutines that run in a // for{select{}}. Be sure to `Exit.Add(n)` before starting goroutines, and // `defer Exit.Done()` in the goroutine. type Exit struct { sync.WaitGroup C <-chan struct{} c chan struct{} once sync.Once } // Exiter is anything that can cleanup after itself at any arbitrary point in // time. type Exiter interface { Exit() } // NewExit creates a new Exit, useful for ensuring termination of goroutines on // exit. func NewExit() *Exit { e := &Exit{ c: make(chan struct{}), } e.C = e.c return e } // Exit closes C and waits for all goroutines to exit. func (e *Exit) Exit() { e.once.Do(func() { close(e.c) e.Wait() }) }
Add XPath query to extract dataset name
from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import Selector from dataset import DatasetItem class DatasetSpider(CrawlSpider): name = 'dataset' allowed_domains = ['data.gc.ca/data/en'] start_urls = ['http://data.gc.ca/data/en/dataset?page=1'] rules = [Rule(SgmlLinkExtractor(allow=['/dataset/[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}']), 'parse_dataset')] def parse_dataset(self, response): sel = Selector(response) dataset = DatasetItem() dataset['url'] = response.url dataset['name'] = sel.xpath("//div[@class='span-6']/article/div[@class='module'][1]/section[@class='module-content indent-large'][1]/h1").extract() dataset['frequency'] = sel.xpath("//div[@class='span-2']/aside[@class='secondary']/div[@class='module-related'][2]/ul[1]/li[@class='margin-bottom-medium']").extract() return dataset
from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import Selector from dataset import DatasetItem class DatasetSpider(CrawlSpider): name = 'dataset' allowed_domains = ['data.gc.ca/data/en'] start_urls = ['http://data.gc.ca/data/en/dataset?page=1'] rules = [Rule(SgmlLinkExtractor(allow=['/dataset/[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}']), 'parse_dataset')] def parse_dataset(self, response): sel = Selector(response) dataset = DatasetItem() dataset['url'] = response.url dataset['frequency'] = sel.xpath("//div[@class='span-2']/aside[@class='secondary']/div[@class='module-related'][2]/ul[1]/li[@class='margin-bottom-medium']").extract()
Change className proptype from mandatory.
/* @flow */ import React, { PropTypes } from 'react'; export class BotWinPercent extends React.Component { // props: Props; static propTypes = { gamesPlayed: PropTypes.number.isRequired, gamesWon: PropTypes.number.isRequired, className: PropTypes.string, }; render () { const gamesPlayed = this.props.gamesPlayed; const gamesWon = this.props.gamesWon; let pct = (gamesWon / gamesPlayed) * 100; let pctStr; if (isNaN(pct)) { pctStr = '-'; } else { let roundedPct = Math.round(pct * 100) / 100; pctStr = `${roundedPct}%`; } if (this.props.className) { return ( <span className={this.props.className}>{pctStr}</span> ); } else { return ( <span>{pctStr}</span> ); } } } export default BotWinPercent;
/* @flow */ import React, { PropTypes } from 'react'; export class BotWinPercent extends React.Component { // props: Props; static propTypes = { gamesPlayed: PropTypes.number.isRequired, gamesWon: PropTypes.number.isRequired, className: PropTypes.string.isRequired, }; render () { const gamesPlayed = this.props.gamesPlayed; const gamesWon = this.props.gamesWon; let pct = (gamesWon / gamesPlayed) * 100; let pctStr; if (isNaN(pct)) { pctStr = '-'; } else { let roundedPct = Math.round(pct * 100) / 100; pctStr = `${roundedPct}%`; } if (this.props.className) { return ( <span className={this.props.className}>{pctStr}</span> ); } else { return ( <span>{pctStr}</span> ); } } } export default BotWinPercent;
Make artist page acceptance test more tolerant
/* eslint-disable jest/expect-expect */ describe("/artist/:id", () => { before(() => { cy.visit("/artist/pablo-picasso") }) it("renders metadata", () => { cy.title().should("contain", "Pablo Picasso") cy.title().should("contain", "Artworks, Bio & Shows on Artsy") cy.get("meta[name='description']") .should("have.attr", "content") .and( "contain", "Find the latest shows, biography, and artworks for sale by Pablo Picasso." ) }) it("renders page content", () => { cy.get("h1").should("contain", "Pablo Picasso") cy.get("h2").should("contain", "Spanish, 1881–1973") cy.get("h2").should("contain", "Notable works") }) }) //
/* eslint-disable jest/expect-expect */ describe("/artist/:id", () => { before(() => { cy.visit("/artist/pablo-picasso") }) it("renders metadata", () => { cy.title().should("contain", "Pablo Picasso") cy.title().should("contain", "Artworks, Bio & Shows on Artsy") cy.get("meta[name='description']") .should("have.attr", "content") .and( "eq", "Find the latest shows, biography, and artworks for sale by Pablo Picasso. Perhaps the most influential artist of the 20th century, Pablo Picasso may be best …" ) }) it("renders page content", () => { cy.get("h1").should("contain", "Pablo Picasso") cy.get("h2").should("contain", "Spanish, 1881–1973") cy.get("h2").should("contain", "Notable works") }) }) //
Drop Python 2.5 support, add support for Python 3.2
import os from setuptools import setup, find_packages def read(filename): return open(os.path.join(os.path.dirname(__file__), filename)).read() setup( name='gears-stylus', version='0.1.1', url='https://github.com/gears/gears-stylus', license='ISC', author='Mike Yumatov', author_email='mike@yumatov.org', description='Stylus compiler for Gears', long_description=read('README.rst'), packages=find_packages(), include_package_data=True, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: ISC License (ISCL)', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', ], )
import os from setuptools import setup, find_packages def read(filename): return open(os.path.join(os.path.dirname(__file__), filename)).read() setup( name='gears-stylus', version='0.1.1', url='https://github.com/gears/gears-stylus', license='ISC', author='Mike Yumatov', author_email='mike@yumatov.org', description='Stylus compiler for Gears', long_description=read('README.rst'), packages=find_packages(), include_package_data=True, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: ISC License (ISCL)', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ], )
Set conchtestdata directory creation perms to 0775.
package main import ( "flag" "fmt" "os" "path/filepath" ) type options struct { qty int dir string } func newOptionsDefault() *options { return &options{ qty: 1024, dir: "./testfiles", } } func main() { opts := newOptionsDefault() { flag.IntVar(&opts.qty, "qty", opts.qty, `quantity of test files`) flag.StringVar(&opts.dir, "dir", opts.dir, `location of test files`) } flag.Parse() if opts.qty < 1 { opts.qty = 1 } opts.dir = filepath.Clean(opts.dir) if _, err := os.Stat(opts.dir); !os.IsNotExist(err) { if err := os.RemoveAll(opts.dir); err != nil { fmt.Fprint(os.Stderr, err) os.Exit(1) } } if err := os.Mkdir(opts.dir, 0775); err != nil { fmt.Fprint(os.Stderr, err) os.Exit(1) } for i := 0; i < opts.qty; i++ { if err := createGZFile(opts.dir, opts.qty, i); err != nil { fmt.Fprint(os.Stderr, err) os.Exit(1) } } }
package main import ( "flag" "fmt" "os" "path/filepath" ) type options struct { qty int dir string } func newOptionsDefault() *options { return &options{ qty: 1024, dir: "./testfiles", } } func main() { opts := newOptionsDefault() { flag.IntVar(&opts.qty, "qty", opts.qty, `quantity of test files`) flag.StringVar(&opts.dir, "dir", opts.dir, `location of test files`) } flag.Parse() if opts.qty < 1 { opts.qty = 1 } opts.dir = filepath.Clean(opts.dir) if _, err := os.Stat(opts.dir); !os.IsNotExist(err) { if err := os.RemoveAll(opts.dir); err != nil { fmt.Fprint(os.Stderr, err) os.Exit(1) } } if err := os.Mkdir(opts.dir, 0700); err != nil { fmt.Fprint(os.Stderr, err) os.Exit(1) } for i := 0; i < opts.qty; i++ { if err := createGZFile(opts.dir, opts.qty, i); err != nil { fmt.Fprint(os.Stderr, err) os.Exit(1) } } }
Replace `unshift()` with `push()` plus `reverse()` As predicted, this is faster. Not sure if as fast as what I had before. Will do actual profiling and revert to prior state if it ends up being better.
/** * Copyright 2003-present Greg Hurrell. All rights reserved. * Licensed under the terms of the MIT license. * * @flow */ export default function addDigits( aDigits: Array<number>, bDigits: Array<number>, base: number ): Array<number> { let result = []; let carry = 0; const aLength = aDigits.length; const bLength = bDigits.length; for (let i = 0; i < aLength || i < bLength || carry; i++) { const aDigit = i < aLength ? aDigits[aLength - i - 1] : 0; const bDigit = i < bLength ? bDigits[bLength - i - 1] : 0; const sum = aDigit + bDigit + carry; result.push(sum % base); // ~~ here is the equivalent of Math.floor; used to avoid V8 de-opt, // "Reference to a variable which requires dynamic lookup". carry = ~~(sum / base); } return result.length ? result.reverse() : [0]; }
/** * Copyright 2003-present Greg Hurrell. All rights reserved. * Licensed under the terms of the MIT license. * * @flow */ export default function addDigits( aDigits: Array<number>, bDigits: Array<number>, base: number ): Array<number> { let result = []; let carry = 0; const aLength = aDigits.length; const bLength = bDigits.length; for (let i = 0; i < aLength || i < bLength || carry; i++) { const aDigit = i < aLength ? aDigits[aLength - i - 1] : 0; const bDigit = i < bLength ? bDigits[bLength - i - 1] : 0; const sum = aDigit + bDigit + carry; result.unshift(sum % base); // ~~ here is the equivalent of Math.floor; used to avoid V8 de-opt, // "Reference to a variable which requires dynamic lookup". carry = ~~(sum / base); } return result.length ? result : [0]; }
Validate response in loadListSuccess action and throw error if invalid
import { REGISTER_LIST, DESTROY_LIST, LOAD_LIST, LOAD_LIST_SUCCESS, LOAD_LIST_ERROR, } from './actionsTypes' export function registerList(listId, params) { return { type: REGISTER_LIST, payload: { listId, params, }, } } export function destroyList(listId) { return { type: DESTROY_LIST, payload: { listId, }, } } export function loadList(listId) { return { type: LOAD_LIST, payload: { listId, }, } } export function loadListSuccess(listId, response) { if (!response) { throw new Error('Response is required') } if (!response.items) { throw new Error('Response items is required') } if (!(response.items instanceof Array)) { throw new Error('Response items should be array') } return { type: LOAD_LIST_SUCCESS, payload: { listId, response, }, } } export function loadListError(listId, response) { return { type: LOAD_LIST_ERROR, payload: { listId, response, }, } }
import { REGISTER_LIST, DESTROY_LIST, LOAD_LIST, LOAD_LIST_SUCCESS, LOAD_LIST_ERROR, } from './actionsTypes' export function registerList(listId, params) { return { type: REGISTER_LIST, payload: { listId, params, }, } } export function destroyList(listId) { return { type: DESTROY_LIST, payload: { listId, }, } } export function loadList(listId) { return { type: LOAD_LIST, payload: { listId, }, } } export function loadListSuccess(listId, response) { return { type: LOAD_LIST_SUCCESS, payload: { listId, response, }, } } export function loadListError(listId, response) { return { type: LOAD_LIST_ERROR, payload: { listId, response, }, } }
Fix access error when detection fails
var browsers = [ [ 'chrome', /Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/ ], [ 'firefox', /Firefox\/([0-9\.]+)(?:\s|$)/ ], [ 'opera', /Opera\/([0-9\.]+)(?:\s|$)/ ], [ 'ie', /Trident\/7\.0.*rv\:([0-9\.]+)\).*Gecko$/ ], [ 'ie', /MSIE\s([0-9\.]+);.*Trident\/[4-6].0/ ], [ 'bb10', /BB10;\sTouch.*Version\/([0-9\.]+)/ ] ]; var match = browsers.map(match).filter(isMatch)[0]; var parts = match && match[3].split('.').slice(0,3); while (parts && parts.length < 3) { parts.push('0'); } // set the name and version exports.name = match && match[0]; exports.version = parts && parts.join('.'); function match(pair) { return pair.concat(pair[1].exec(navigator.userAgent)); } function isMatch(pair) { return !!pair[2]; }
var browsers = [ [ 'chrome', /Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/ ], [ 'firefox', /Firefox\/([0-9\.]+)(?:\s|$)/ ], [ 'opera', /Opera\/([0-9\.]+)(?:\s|$)/ ], [ 'ie', /Trident\/7\.0.*rv\:([0-9\.]+)\).*Gecko$/ ], [ 'ie', /MSIE\s([0-9\.]+);.*Trident\/[4-6].0/ ], [ 'bb10', /BB10;\sTouch.*Version\/([0-9\.]+)/ ] ]; var match = browsers.map(match).filter(isMatch)[0]; var parts = match && match[3].split('.').slice(0,3); while (parts.length < 3) { parts.push('0'); } // set the name and version exports.name = match && match[0]; exports.version = parts.join('.'); function match(pair) { return pair.concat(pair[1].exec(navigator.userAgent)); } function isMatch(pair) { return !!pair[2]; }
Add missing option for percentPosition
/* global imagesLoaded */ import Ember from 'ember'; var getOptions = function (keys) { var properties = this.getProperties(keys); Object.keys(properties).forEach(function (key) { if (properties[key] === "null") { properties[key] = null; } if (properties[key] === undefined) { delete properties[key]; } }); return properties; }; export default Ember.Component.extend({ classNames: ['masonry-grid'], options: null, items: null, masonryInitialized: false, initializeMasonry: Ember.on('didInsertElement', function () { this.set('options', getOptions.call(this, [ 'containerStyle', 'columnWidth', 'gutter', 'hiddenStyle', 'isFitWidth', 'isInitLayout', 'isOriginLeft', 'isOriginTop', 'isResizeBound', 'itemSelector', 'percentPosition', 'stamp', 'transitionDuration', 'visibleStyle' ])); this.layoutMasonry(); }), layoutMasonry: Ember.observer('items.@each', function () { var _this = this; imagesLoaded(this.$(), function () { if (_this.get('masonryInitialized')) { _this.$().masonry('destroy'); } _this.$().masonry(_this.get('options')); _this.set('masonryInitialized', true); }); }) });
/* global imagesLoaded */ import Ember from 'ember'; var getOptions = function (keys) { var properties = this.getProperties(keys); Object.keys(properties).forEach(function (key) { if (properties[key] === "null") { properties[key] = null; } if (properties[key] === undefined) { delete properties[key]; } }); return properties; }; export default Ember.Component.extend({ classNames: ['masonry-grid'], options: null, items: null, masonryInitialized: false, initializeMasonry: Ember.on('didInsertElement', function () { this.set('options', getOptions.call(this, [ 'containerStyle', 'columnWidth', 'gutter', 'hiddenStyle', 'isFitWidth', 'isInitLayout', 'isOriginLeft', 'isOriginTop', 'isResizeBound', 'itemSelector', 'stamp', 'transitionDuration', 'visibleStyle' ])); this.layoutMasonry(); }), layoutMasonry: Ember.observer('items.@each', function () { var _this = this; imagesLoaded(this.$(), function () { if (_this.get('masonryInitialized')) { _this.$().masonry('destroy'); } _this.$().masonry(_this.get('options')); _this.set('masonryInitialized', true); }); }) });
Remove debug of ui router state changes.
(function (module) { module.controller('projectListProcess', projectListProcess); projectListProcess.$inject = ["processes", "project", "$state", "mcmodal", "$filter"]; function projectListProcess(processes, project, $state, mcmodal, $filter) { var ctrl = this; ctrl.viewProcess = viewProcess; ctrl.chooseTemplate = chooseTemplate; ctrl.processes = processes; ctrl.project = project; if (ctrl.processes.length !== 0) { ctrl.processes = $filter('orderBy')(ctrl.processes, 'name'); ctrl.current = ctrl.processes[0]; $state.go('projects.project.processes.list.view', {process_id: ctrl.current.id}); } /////////////////////////////////// function viewProcess(process) { ctrl.current = process; $state.go('projects.project.processes.list.view', {process_id: ctrl.current.id}); } function chooseTemplate() { mcmodal.chooseTemplate(ctrl.project); } } }(angular.module('materialscommons')));
(function (module) { module.controller('projectListProcess', projectListProcess); projectListProcess.$inject = ["processes", "project", "$state", "mcmodal", "$filter"]; function projectListProcess(processes, project, $state, mcmodal, $filter) { console.log('projectListProcess'); var ctrl = this; ctrl.viewProcess = viewProcess; ctrl.chooseTemplate = chooseTemplate; ctrl.processes = processes; ctrl.project = project; if (ctrl.processes.length !== 0) { console.log(' ctrl.processes.length !== 0'); ctrl.processes = $filter('orderBy')(ctrl.processes, 'name'); ctrl.current = ctrl.processes[0]; //$state.go('projects.project.processes.list.view', {process_id: ctrl.current.id}); } /////////////////////////////////// function viewProcess(process) { ctrl.current = process; $state.go('projects.project.processes.list.view', {process_id: ctrl.current.id}); } function chooseTemplate() { mcmodal.chooseTemplate(ctrl.project); } } }(angular.module('materialscommons')));
Clean up entry point validation
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. var JupyterLab = require('jupyterlab/lib/application').JupyterLab; // ES6 Promise polyfill require('es6-promise').polyfill(); require('font-awesome/css/font-awesome.min.css'); require('material-design-icons/iconfont/material-icons.css'); require('jupyterlab/lib/default-theme/index.css'); /** * Validate an entry point given by the user. */ function validateEntryPoint(entryPoint) { var data = jupyter.require(entryPoint); if (!Array.isArray(data)) { data = [data]; } var plugins = []; for (let i = 0; i < data.length; i++) { var plugin = data[i]; if (!plugin.hasOwnProperty('id') || !typeof(plugin['activate']) == 'function') { console.warn('Invalid plugin found in: ', entryPoint); continue; } plugins.push(plugin); } return plugins; } jupyter.lab = new JupyterLab(); jupyter.validateEntryPoint = validateEntryPoint; module.exports = jupyter.lab;
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. var JupyterLab = require('jupyterlab/lib/application').JupyterLab; // ES6 Promise polyfill require('es6-promise').polyfill(); require('font-awesome/css/font-awesome.min.css'); require('material-design-icons/iconfont/material-icons.css'); require('jupyterlab/lib/default-theme/index.css'); /** * Test whether a value is a function. */ function isFunction(obj) { // http://stackoverflow.com/a/6000016. return !!(obj && obj.constructor && obj.call && obj.apply); } /** * Validate an entry point given by the user. */ function validateEntryPoint(entryPoint) { var data = jupyter.require(entryPoint); if (!Array.isArray(data)) { data = [data]; } var plugins = []; for (let i = 0; i < data.length; i++) { var plugin = data[i]; if (!plugin.hasOwnProperty('id') || !isFunction(plugin['activate'])) { console.warn('Invalid plugin found in: ', entryPoint); continue; } plugins.push(plugin); } return plugins; } jupyter.lab = new JupyterLab(); jupyter.validateEntryPoint = validateEntryPoint; module.exports = jupyter.lab;
Clarify fetch handler in the api-analytics recipe
// In a real use case, the endpoint could point to another origin. var LOG_ENDPOINT = 'report/logs'; // The code in `oninstall` and `onactive` force the service worker to // control the clients ASAP. self.oninstall = function(event) { event.waitUntil(self.skipWaiting()); }; self.onactivate = function(event) { event.waitUntil(self.clients.claim()); }; self.onfetch = function(event) { event.respondWith( // Log the request ... log(event.request) // .. and then actually perform it. .then(fetch) ); }; // Post basic information of the request to a backend for historical purposes. function log(request) { var returnRequest = function() { return request; }; var data = { method: request.method, url: request.url }; return fetch(LOG_ENDPOINT, { method: 'POST', body: JSON.stringify(data), headers: { 'content-type': 'application/json' } }) .then(returnRequest, returnRequest); }
// In a real use case, the endpoint could point to another origin. var LOG_ENDPOINT = 'report/logs'; // The code in `oninstall` and `onactive` force the service worker to // control the clients ASAP. self.oninstall = function(event) { event.waitUntil(self.skipWaiting()); }; self.onactivate = function(event) { event.waitUntil(self.clients.claim()); }; // Fetch is as simply as log the request and passthrough. // Water clear thanks to the promise syntax! self.onfetch = function(event) { event.respondWith(log(event.request).then(fetch)); }; // Post basic information of the request to a backend for historical purposes. function log(request) { var returnRequest = function() { return Promise.resolve(request); }; var data = { method: request.method, url: request.url }; return fetch(LOG_ENDPOINT, { method: 'POST', body: JSON.stringify(data), headers: { 'content-type': 'application/json' } }).then(returnRequest, returnRequest); }
Fix 404 when no path in URL
from django.conf import settings from django.conf.urls import patterns, include, url from django.conf.urls.static import static from django.views.generic import RedirectView class FakeTenant(object): is_main = lambda self: False is_configured = lambda self: True id = 'di' def chat_host(self): if settings.DEBUG: return 'network1.localhost' return 'network1.ditto.technology' # NOTE: this MUST come first in the middleware order class CurrentTenantMiddleware(object): def process_request(self, request): request.tenant = FakeTenant() request.urlconf = _get_urls('di') def _get_urls(tenant_slug): # Note, need 'tuple' here otherwise url stuff blows up return tuple( patterns( '', (r'^$', RedirectView.as_view( pattern_name='ditto:home', permanent=True, )), url(r'^%s/' % tenant_slug, include('network_urls')), url(r'^main/', include('multitenancy.urls', namespace="ditto")), ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT))
from django.conf import settings from django.conf.urls import patterns, include, url from django.conf.urls.static import static class FakeTenant(object): is_main = lambda self: False is_configured = lambda self: True id = 'di' def chat_host(self): if settings.DEBUG: return 'network1.localhost' return 'network1.ditto.technology' # NOTE: this MUST come first in the middleware order class CurrentTenantMiddleware(object): def process_request(self, request): request.tenant = FakeTenant() request.urlconf = _get_urls('di') def _get_urls(tenant_slug): # Note, need 'tuple' here otherwise url stuff blows up return tuple( patterns( '', url(r'^%s/' % tenant_slug, include('network_urls')), url(r'^main/', include('multitenancy.urls', namespace="ditto")), ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT))
Update properties taxonomy type meta data
<?php class Properties_Taxonomy_Type extends Papi_Taxonomy_Type { /** * Define our Page Type meta data. * * @return array */ public function meta() { return [ 'name' => 'Properties taxonomy', 'description' => 'This is a properties taxonomy', 'template' => 'pages/properties-taxonomy.php', 'taxonomy' => 'post_tag' ]; } /** * Remove meta boxes. * * @return array */ public function remove() { return ['editor', 'commentsdiv', 'commentstatusdiv', 'authordiv', 'slugdiv']; } /** * Define our properties. */ public function register() { $this->box( papi_template( __DIR__ . '/../page-types/boxes/properties.php' ) ); } }
<?php class Properties_Taxonomy_Type extends Papi_Taxonomy_Type { /** * Define our Page Type meta data. * * @return array */ public function meta() { return [ 'name' => 'Properties taxonomy type', 'description' => 'This is a properties taxonomy page', 'template' => 'pages/properties-taxonomy-page.php', 'taxonomy' => 'post_tag' ]; } /** * Remove meta boxes. * * @return array */ public function remove() { return ['editor', 'commentsdiv', 'commentstatusdiv', 'authordiv', 'slugdiv']; } /** * Define our properties. */ public function register() { $this->box( papi_template( __DIR__ . '/../page-types/boxes/properties.php' ) ); } }
Use list comprehension to evaluate PYTZ_TIME_ZONE_CHOICES During Python 3 conversion this must have been missed.
import pytz from dateutil.rrule import DAILY, WEEKLY from django.utils.translation import ugettext_lazy as _ GENDER_CHOICES = ( ('M', _('Male')), ('F', _('Female')), ('X', _('Unspecified')), ) SEASON_MODE_CHOICES = ( (WEEKLY, _("Season")), (DAILY, _("Tournament")), ) WIN_LOSE = { 'W': _("Winner"), 'L': _("Loser"), } ################### # TIME ZONE NAMES # ################### """ Ideally this would be a better list for the specific uses of the site in question. For example, it is perhaps much easier to list just the Australian time zones for sites deployed for Australian customers. This is also implemented in touchtechnology.common.forms and should probably be moved and better leveraged in future release. See https://bitbucket.org/touchtechnology/common/issue/16/ """ PYTZ_TIME_ZONE_CHOICES = [('\x20Standard', (('UTC', 'UTC'), ('GMT', 'GMT')))] for iso, name in pytz.country_names.items(): values = sorted(pytz.country_timezones.get(iso, [])) names = [s.rsplit("/", 1)[1].replace("_", " ") for s in values] PYTZ_TIME_ZONE_CHOICES.append((name, [each for each in zip(values, names)])) PYTZ_TIME_ZONE_CHOICES.sort()
import pytz from dateutil.rrule import DAILY, WEEKLY from django.utils.translation import ugettext_lazy as _ GENDER_CHOICES = ( ('M', _('Male')), ('F', _('Female')), ('X', _('Unspecified')), ) SEASON_MODE_CHOICES = ( (WEEKLY, _("Season")), (DAILY, _("Tournament")), ) WIN_LOSE = { 'W': _("Winner"), 'L': _("Loser"), } ################### # TIME ZONE NAMES # ################### """ Ideally this would be a better list for the specific uses of the site in question. For example, it is perhaps much easier to list just the Australian time zones for sites deployed for Australian customers. This is also implemented in touchtechnology.common.forms and should probably be moved and better leveraged in future release. See https://bitbucket.org/touchtechnology/common/issue/16/ """ PYTZ_TIME_ZONE_CHOICES = [('\x20Standard', (('UTC', 'UTC'), ('GMT', 'GMT')))] for iso, name in pytz.country_names.items(): values = sorted(pytz.country_timezones.get(iso, [])) names = [s.rsplit("/", 1)[1].replace("_", " ") for s in values] PYTZ_TIME_ZONE_CHOICES.append((name, zip(values, names))) PYTZ_TIME_ZONE_CHOICES.sort()
Use new timezone-aware datetime.now with Django versions that support it
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 import datetime from rapidsms.apps.base import AppBase from .models import Message try: from django.utils.timezone import now as datetime_now except ImportError: datetime_now = datetime.datetime.now class App(AppBase): def _who(self, msg): to_return = {} if msg.contact: to_return["contact"] = msg.contact if msg.connection: to_return["connection"] = msg.connection if not to_return: raise ValueError return to_return def _log(self, direction, who, text): return Message.objects.create( date=datetime_now(), direction=direction, text=text, **who) def parse(self, msg): # annotate the message as we log them in case any other apps # want a handle to them msg.logger_msg = self._log("I", self._who(msg), msg.raw_text) def outgoing(self, msg): msg.logger_msg = self._log("O", self._who(msg), msg.text)
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 import datetime from rapidsms.apps.base import AppBase from .models import Message class App(AppBase): def _who(self, msg): to_return = {} if msg.contact: to_return["contact"] = msg.contact if msg.connection: to_return["connection"] = msg.connection if not to_return: raise ValueError return to_return def _log(self, direction, who, text): return Message.objects.create( date=datetime.datetime.now(), direction=direction, text=text, **who) def parse(self, msg): # annotate the message as we log them in case any other apps # want a handle to them msg.logger_msg = self._log("I", self._who(msg), msg.raw_text) def outgoing(self, msg): msg.logger_msg = self._log("O", self._who(msg), msg.text)
Use the correct location of view_counter in test
""" Simple test for the view counter that verifies that it is updating properly """ from collections import namedtuple from mock import Mock from xblock.runtime import KvsFieldData, DictKeyValueStore from sample_xblocks.basic.view_counter import ViewCounter from xblock.test.tools import assert_in, assert_equals TestUsage = namedtuple('TestUsage', 'id, def_id') # pylint: disable=C0103 def test_view_counter_state(): key_store = DictKeyValueStore() db_model = KvsFieldData(key_store) tester = ViewCounter(Mock(), db_model, Mock()) assert_equals(tester.views, 0) # View the XBlock five times for i in xrange(5): generated_html = tester.student_view({}) # Make sure the html fragment we're expecting appears in the body_html assert_in('<span class="views">{0}</span>'.format(i + 1), generated_html.body_html()) assert_equals(tester.views, i + 1)
""" Simple test for the view counter that verifies that it is updating properly """ from collections import namedtuple from mock import Mock from xblock.runtime import KvsFieldData, DictKeyValueStore from xblock.view_counter import ViewCounter from xblock.test.tools import assert_in, assert_equals TestUsage = namedtuple('TestUsage', 'id, def_id') # pylint: disable=C0103 def test_view_counter_state(): key_store = DictKeyValueStore() db_model = KvsFieldData(key_store) tester = ViewCounter(Mock(), db_model, Mock()) assert_equals(tester.views, 0) # View the XBlock five times for i in xrange(5): generated_html = tester.student_view({}) # Make sure the html fragment we're expecting appears in the body_html assert_in('<span class="views">{0}</span>'.format(i + 1), generated_html.body_html()) assert_equals(tester.views, i + 1)