text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Remove map and filter use
from operator import itemgetter from itertools import chain from ...utils.py3_hook import with_hook with with_hook(): from arcrest import Catalog import numpy as np def get_layers(service): layers = service.layers return { layer.name: layer for layer in layers } def mend_extent(extent): extent.wkid = extent.spatialReference.wkid return extent def get_data(requested_layers): catalog = Catalog('http://services.ga.gov.au/site_7/rest/services') service = catalog['NM_Transport_Infrastructure'] layers = get_layers(service) return chain.from_iterable( layers[layer].QueryLayer(Geometry=mend_extent(layers[layer].extent)) for layer in requested_layers ) def get_paths(request_layers): paths = get_data(request_layers) paths = map(itemgetter('geometry'), paths) paths = chain.from_iterable( geometry.paths for geometry in paths if hasattr(geometry, 'paths') ) return np.array([ tuple( (part.x, part.y) for part in path ) for path in paths ])
from operator import attrgetter, itemgetter from itertools import chain from ...utils.py3_hook import with_hook with with_hook(): from arcrest import Catalog import numpy as np def get_layers(service): layers = service.layers return { layer.name: layer for layer in layers } def mend_extent(extent): extent.wkid = extent.spatialReference.wkid return extent def get_data(requested_layers): catalog = Catalog('http://services.ga.gov.au/site_7/rest/services') service = catalog['NM_Transport_Infrastructure'] layers = get_layers(service) return chain.from_iterable( layers[layer].QueryLayer(Geometry=mend_extent(layers[layer].extent)) for layer in requested_layers ) def get_paths(request_layers): paths = get_data(request_layers) paths = map(itemgetter('geometry'), paths) paths = filter(lambda path: hasattr(path, 'paths'), paths) paths = map(attrgetter('paths'), paths) paths = chain.from_iterable(paths) return np.array([ tuple( (part.x, part.y) for part in path ) for path in paths ])
Update dates passed in python3
""" Coda Replication Model factories for test fixtures. """ from datetime import datetime import factory from factory import fuzzy from . import models class QueueEntryFactory(factory.django.DjangoModelFactory): ark = factory.Sequence(lambda n: 'ark:/00001/id{0}'.format(n)) bytes = fuzzy.FuzzyInteger(100000000) files = fuzzy.FuzzyInteger(50, 500) url_list = fuzzy.FuzzyText(length=500) status = fuzzy.FuzzyChoice(str(i) for i in range(1, 10)) harvest_start = fuzzy.FuzzyNaiveDateTime(datetime(2015, 1, 1)) harvest_end = fuzzy.FuzzyNaiveDateTime(datetime(2015, 6, 1)) queue_position = fuzzy.FuzzyInteger(1, 100) class Meta: model = models.QueueEntry
""" Coda Replication Model factories for test fixtures. """ from datetime import datetime import factory from factory import fuzzy from . import models class QueueEntryFactory(factory.django.DjangoModelFactory): ark = factory.Sequence(lambda n: 'ark:/00001/id{0}'.format(n)) bytes = fuzzy.FuzzyInteger(100000000) files = fuzzy.FuzzyInteger(50, 500) url_list = fuzzy.FuzzyText(length=500) status = fuzzy.FuzzyChoice(str(i) for i in range(1, 10)) harvest_start = fuzzy.FuzzyNaiveDateTime(datetime(2015, 01, 01)) harvest_end = fuzzy.FuzzyNaiveDateTime(datetime(2015, 06, 01)) queue_position = fuzzy.FuzzyInteger(1, 100) class Meta: model = models.QueueEntry
Change dimensions of output in python wrapper
import pycuda.autoinit import pycuda.driver as drv import numpy from scipy import misc from color_histogram_cuda_module import histogram_atomics, histogram_accum def histogram(image_path, num_bins): image = misc.imread(image_path) bin_size = 256 / num_bins # calculate image dimensions (w, h, c) = image.shape # reinterpret image with 4-byte type image = image.view(numpy.uint32) dest = numpy.zeros((c, bin_size), numpy.uint32) parts = num_bins * c block1 = (32, 4, 1) grid1 = (16, 16, 1) partial = numpy.zeros(grid1[0] * grid1[1] * parts, numpy.uint32) block2 = (128,1, 1) grid2 = ((c * num_bins + block2[0] - 1) / block2[0], 1, 1) W = numpy.dtype(numpy.int32).type(w) H = numpy.dtype(numpy.int32).type(h) histogram_atomics(drv.In(image), W, H, drv.Out(partial), block=block1, grid=grid1) sz = numpy.dtype(numpy.int32).type(grid1[0] * grid1[1]) histogram_accum(drv.In(partial), sz, drv.Out(dest), block=block2, grid=grid2) return dest
import pycuda.autoinit import pycuda.driver as drv import numpy from scipy import misc from color_histogram_cuda_module import histogram_atomics, histogram_accum def histogram(image_path, num_bins): image = misc.imread(image_path) bin_size = 256 / num_bins # calculate image dimensions (w, h, c) = image.shape # reinterpret image with 4-byte type image = image.view(numpy.uint32) dest = numpy.zeros((bin_size, c), numpy.uint32) parts = num_bins * c block1 = (32, 4, 1) grid1 = (16, 16, 1) partial = numpy.zeros(grid1[0] * grid1[1] * parts, numpy.uint32) block2 = (128,1, 1) grid2 = ((c * num_bins + block2[0] - 1) / block2[0], 1, 1) W = numpy.dtype(numpy.int32).type(w) H = numpy.dtype(numpy.int32).type(h) histogram_atomics(drv.In(image), W, H, drv.Out(partial), block=block1, grid=grid1) sz = numpy.dtype(numpy.int32).type(grid1[0] * grid1[1]) histogram_accum(drv.In(partial), sz, drv.Out(dest), block=block2, grid=grid2) return dest
Add Transaction Requires New to Action Log service
package edu.harvard.iq.dataverse.actionlogging; import java.util.Date; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; /** * A service bean that persists {@link ActionLogRecord}s to the DB. * @author michael */ @Stateless public class ActionLogServiceBean { @PersistenceContext(unitName = "VDCNet-ejbPU") private EntityManager em; /** * Log the record. Set default values. * @param rec */ @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public void log( ActionLogRecord rec ) { if ( rec.getEndTime() == null ) { rec.setEndTime( new Date() ); } if ( rec.getActionResult() == null && rec.getActionType() != ActionLogRecord.ActionType.Command ) { rec.setActionResult(ActionLogRecord.Result.OK); } em.persist(rec); } }
package edu.harvard.iq.dataverse.actionlogging; import java.util.Date; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; /** * A service bean that persists {@link ActionLogRecord}s to the DB. * @author michael */ @Stateless public class ActionLogServiceBean { @PersistenceContext(unitName = "VDCNet-ejbPU") private EntityManager em; /** * Log the record. Set default values. * @param rec */ public void log( ActionLogRecord rec ) { if ( rec.getEndTime() == null ) { rec.setEndTime( new Date() ); } if ( rec.getActionResult() == null && rec.getActionType() != ActionLogRecord.ActionType.Command ) { rec.setActionResult(ActionLogRecord.Result.OK); } em.persist(rec); } }
Include babel polyfill for github pages demo
/* global require, module */ var EmberAddon = require('ember-cli/lib/broccoli/ember-addon') module.exports = function (defaults) { var app = new EmberAddon(defaults, { babel: { includePolyfill: true, optional: ['es7.decorators'] }, codemirror: { modes: ['javascript', 'handlebars', 'markdown'], themes: ['mdn-like'] }, 'ember-cli-mocha': { useLintTree: false }, 'ember-prism': { components: ['javascript'], theme: 'coy' }, sassOptions: { includePaths: [ ] } }) app.import('bower_components/sinonjs/sinon.js') /* This build file specifes the options for the dummy test app of this addon, located in `/tests/dummy` This build file does *not* influence how the addon or the app using it behave. You most likely want to be modifying `./index.js` or app's build file */ return app.toTree() }
/* global require, module */ var EmberAddon = require('ember-cli/lib/broccoli/ember-addon') module.exports = function (defaults) { var app = new EmberAddon(defaults, { babel: { optional: ['es7.decorators'] }, codemirror: { modes: ['javascript', 'handlebars', 'markdown'], themes: ['mdn-like'] }, 'ember-cli-mocha': { useLintTree: false }, 'ember-prism': { components: ['javascript'], theme: 'coy' }, sassOptions: { includePaths: [ ] } }) app.import('bower_components/sinonjs/sinon.js') /* This build file specifes the options for the dummy test app of this addon, located in `/tests/dummy` This build file does *not* influence how the addon or the app using it behave. You most likely want to be modifying `./index.js` or app's build file */ return app.toTree() }
Split out main into process(), and add shortened version in process2().
package com.ticketmanor.rest.client; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; //import org.glassfish.jersey.jackson.JacksonFeature; import com.ticketmanor.model.Event; /** This will become an example of the JAX-RS 2.0 Client API. * It has a dependency on Jersey (which is in our POM file now). * It is confused by some fields in the returned JSON data... * @author Ian Darwin */ public class JaxRsClientMain { private static final String URL = "http://localhost:8080/ticketmanor/rest/events/-1"; public static void main(String[] args) { process(); } public static Event process() { Client cl = ClientBuilder.newClient(); //cl.register(JacksonFeature.class); WebTarget target = cl.target(URL); Event e = target.request(MediaType.APPLICATION_JSON).get(Event.class); System.out.println("Got an event: " + e); return e; } public static Event process2() { Event e = ClientBuilder.newClient() .target(URL) .request(MediaType.APPLICATION_JSON) .get(Event.class); System.out.println("Got an event: " + e); return e; } }
package com.ticketmanor.rest.client; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; //import org.glassfish.jersey.jackson.JacksonFeature; import com.ticketmanor.model.Event; /** This will become an example of the JAX-RS 2.0 Client API. * It has a dependency on Jersey (which is in our POM file now). * It is confused by some fields in the returned JSON data... * @author Ian Darwin */ public class JaxRsClientMain { private static final String URL = "http://localhost:8080/ticketmanor/rest/events/-1"; public static void main(String[] args) { Client cl = ClientBuilder.newClient(); //cl.register(JacksonFeature.class); WebTarget target = cl.target(URL); Event e = target.request(MediaType.APPLICATION_JSON).get(Event.class); System.out.println("Got an event: " + e); } }
Change paths for twitter API
package fr.oni.gaagaa.api; import java.util.List; import fr.oni.gaagaa.model.twitter.Authenticated; import fr.oni.gaagaa.model.twitter.Tweet; import fr.oni.gaagaa.model.twitter.TwitterUser; import retrofit.http.Body; import retrofit.http.Field; import retrofit.http.FormUrlEncoded; import retrofit.http.GET; import retrofit.http.Header; import retrofit.http.Headers; import retrofit.http.POST; import retrofit.http.Query; public interface TwitterApi { @GET("/lists/statuses.json") List<Tweet> getTwitterStream(@Query("slug") String slug, @Query("owner_screen_name") String screenName); @GET("/account/verify_credentials.json") TwitterUser verifyCredentials(@Header("Authorization") String authorization); @POST("/statuses/update.json") Tweet sendUpdate(@Header("Authorization") String authorization, @Body String status); @GET("/statuses/user_timeline.json") List<Tweet> getUserTimeline(@Query("screen_name") String screenName, @Query("count") int count); }
package fr.oni.gaagaa.api; import java.util.List; import fr.oni.gaagaa.model.twitter.Authenticated; import fr.oni.gaagaa.model.twitter.Tweet; import fr.oni.gaagaa.model.twitter.TwitterUser; import retrofit.http.Body; import retrofit.http.Field; import retrofit.http.FormUrlEncoded; import retrofit.http.GET; import retrofit.http.Header; import retrofit.http.Headers; import retrofit.http.POST; import retrofit.http.Query; public interface TwitterApi { @FormUrlEncoded @POST("/oauth2/token") Authenticated authorizeUser(@Header("Authorization") String authorization, @Field("grant_type") String grantType); @Headers({ "Content-Type: application/json" }) @GET("/1.1/lists/statuses.json") List<Tweet> getTwitterStream(@Query("slug") String slug, @Query("owner_screen_name") String screenName); @GET("/1.1/account/verify_credentials.json") TwitterUser verifyCredentials(@Header("Authorization") String authorization); @POST("/1.1/statuses/update.json") Tweet sendUpdate(@Header("Authorization") String authorization, @Body String status); @GET("/statuses/user_timeline.json") List<Tweet> getUserTimeline(@Query("screen_name") String screenName, @Query("count") int count); }
Use newer package import syntax for Flask
# Application models # # Copyright (c) 2016, Alexandre Hamelin <alexandre.hamelin gmail.com> import os, os.path from datetime import datetime from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from {{PROJECTNAME}} import app app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///{}'.format( os.path.join(app.root_path, app.name + '.db')) db = SQLAlchemy(app) migrate = Migrate(app, db) #class MyModel(db.Model): # id = db.Column(db.Integer, primary_key=True) # # Quickref: # # types: Integer, String(L), Text, DateTime, ForeignKey('table.col') # # keywords: primary_key, nullable, unique, default # # rels: db.relationship('OtherModel', backref=db.backref('mymodels')) # # # def __init__(self, ...): # pass # # # def __str__(self): # return self.name # # # def __repr__(self): # return '<{} {!r}>'.format(self.__class__.__name__, self.id)
# Application models # # Copyright (c) 2016, Alexandre Hamelin <alexandre.hamelin gmail.com> import os, os.path from datetime import datetime from flask.ext.sqlalchemy import SQLAlchemy from {{PROJECTNAME}} import app app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///{}'.format( os.path.join(app.root_path, app.name + '.db')) db = SQLAlchemy(app) #class MyModel(db.Model): # id = db.Column(db.Integer, primary_key=True) # # Quickref: # # types: Integer, String(L), Text, DateTime, ForeignKey('table.col') # # keywords: primary_key, nullable, unique, default # # rels: db.relationship('OtherModel', backref=db.backref('mymodels')) # # # def __init__(self, ...): # pass # # # def __str__(self): # return self.name # # # def __repr__(self): # return '<{} {!r}>'.format(self.__class__.__name__, self.id)
Use feed as the foreign key of image
# This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table # Feel free to rename the models, but don't rename db_table values or field names. # # Also note: You'll have to insert the output of 'django-admin sqlcustom [app_label]' # into your database. from __future__ import unicode_literals from django.db import models import django_pgjsonb class Feed(models.Model): id = models.AutoField(primary_key=True) article_id = models.BigIntegerField(unique=True) article_json = django_pgjsonb.JSONField() class Meta: db_table = 'feed' class Image(models.Model): id = models.AutoField(primary_key=True) feed = models.ForeignKey(Feed, blank=True, null=True) url = models.TextField() nude_percent = models.IntegerField(blank=True, null=True) path = models.ImageField(null=True) class Meta: db_table = 'image' unique_together = (('url', 'feed'),)
# This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table # Feel free to rename the models, but don't rename db_table values or field names. # # Also note: You'll have to insert the output of 'django-admin sqlcustom [app_label]' # into your database. from __future__ import unicode_literals from django.db import models import django_pgjsonb class Feed(models.Model): id = models.AutoField(primary_key=True) article_id = models.BigIntegerField(unique=True) article_json = django_pgjsonb.JSONField() class Meta: db_table = 'feed' class Image(models.Model): id = models.AutoField(primary_key=True) article = models.ForeignKey(Feed, blank=True, null=True) url = models.TextField() nude_percent = models.IntegerField(blank=True, null=True) path = models.ImageField(null=True) class Meta: db_table = 'image' unique_together = (('url', 'article'),)
Fix versioning and add scripts directory
import os from setuptools import setup, find_packages import glob src_dir = os.path.dirname(__file__) def read(filename): full_path = os.path.join(src_dir, filename) with open(full_path) as fd: return fd.read() setup( name='nymms', version='0.2.1', author='Michael Barrett', author_email='loki77@gmail.com', license="New BSD license", url="https://github.com/cloudtools/nymms", description='Not Your Mother\'s Monitoring System (NYMMS)', long_description=read('README.rst'), classifiers=[ "Topic :: System :: Monitoring", "License :: OSI Approved :: BSD License", "Development Status :: 3 - Alpha"], packages=find_packages(), scripts=glob.glob(os.path.join(src_dir, 'scripts', '*')), )
import os from setuptools import setup, find_packages def read(filename): full_path = os.path.join(os.path.dirname(__file__), filename) with open(full_path) as fd: return fd.read() setup( name='nymms', version='0.4.2', author='Michael Barrett', author_email='loki77@gmail.com', license="New BSD license", url="https://github.com/cloudtools/nymms", description='Not Your Mother\'s Monitoring System (NYMMS)', long_description=read('README.rst'), classifiers=[ "Topic :: System :: Monitoring", "License :: OSI Approved :: BSD License", "Development Status :: 3 - Alpha"], packages=find_packages(), )
Fix module name: test.mysql -> test.mysqld
# -*- coding: utf-8 -*- from setuptools import setup, find_packages classifiers = [ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.3", "Topic :: Database", "Topic :: Software Development", "Topic :: Software Development :: Testing", ] setup( name='test.mysqld', version='0.1.0', description='automatically setups a mysqld instance in a temporary directory, and destroys it after testing', long_description='', classifiers=classifiers, keywords=[], author='Takeshi Komiya', author_email='i.tkomiya at gmail.com', url='http://bitbucket.org/tk0miya/test.mysql', license='Apache License 2.0', packages=find_packages('src'), package_dir={'': 'src'}, package_data = {'': ['buildout.cfg']}, include_package_data=True, install_requires=[ 'pymysql', ], extras_require=dict( test=[ 'Nose', 'pep8', ], ), test_suite='nose.collector', )
# -*- coding: utf-8 -*- from setuptools import setup, find_packages classifiers = [ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.3", "Topic :: Database", "Topic :: Software Development", "Topic :: Software Development :: Testing", ] setup( name='test.mysql', version='0.1.0', description='automatically setups a mysqld instance in a temporary directory, and destroys it after testing', long_description='', classifiers=classifiers, keywords=[], author='Takeshi Komiya', author_email='i.tkomiya at gmail.com', url='http://bitbucket.org/tk0miya/test.mysql', license='Apache License 2.0', packages=find_packages('src'), package_dir={'': 'src'}, package_data = {'': ['buildout.cfg']}, include_package_data=True, install_requires=[ 'pymysql', ], extras_require=dict( test=[ 'Nose', 'pep8', ], ), test_suite='nose.collector', )
Rename public function to match task name
import patch from '../node/patch'; import Transaction from '../transaction'; import { CreateNodeHookCache, VTree } from '../util/types'; import globalThis from '../util/global'; /** * Processes a set of patches onto a tracked DOM Node. * * @param {Transaction} transaction * @return {void} */ export default function patchNode(transaction) { const { mount, state, patches } = transaction; const { mutationObserver, measure, scriptsToExecute } = state; measure('patch node'); const { ownerDocument } = /** @type {HTMLElement} */ (mount); const promises = transaction.promises || []; state.ownerDocument = ownerDocument || globalThis.document; // Always disconnect a MutationObserver before patching. if (mutationObserver) { mutationObserver.disconnect(); } // Hook into the Node creation process to find all script tags, and mark them // for execution. const collectScripts = (/** @type {VTree} */vTree) => { if (vTree.nodeName === 'script') { scriptsToExecute.set(vTree, vTree.attributes.type); } }; CreateNodeHookCache.add(collectScripts); // Skip patching completely if we aren't in a DOM environment. if (state.ownerDocument) { promises.push(...patch(patches, state)); } CreateNodeHookCache.delete(collectScripts); transaction.promises = promises; measure('patch node'); }
import patchNode from '../node/patch'; import Transaction from '../transaction'; import { CreateNodeHookCache, VTree } from '../util/types'; import globalThis from '../util/global'; /** * Processes a set of patches onto a tracked DOM Node. * * @param {Transaction} transaction * @return {void} */ export default function patch(transaction) { const { mount, state, patches } = transaction; const { mutationObserver, measure, scriptsToExecute } = state; measure('patch node'); const { ownerDocument } = /** @type {HTMLElement} */ (mount); const promises = transaction.promises || []; state.ownerDocument = ownerDocument || globalThis.document; // Always disconnect a MutationObserver before patching. if (mutationObserver) { mutationObserver.disconnect(); } // Hook into the Node creation process to find all script tags, and mark them // for execution. const collectScripts = (/** @type {VTree} */vTree) => { if (vTree.nodeName === 'script') { scriptsToExecute.set(vTree, vTree.attributes.type); } }; CreateNodeHookCache.add(collectScripts); // Skip patching completely if we aren't in a DOM environment. if (state.ownerDocument) { promises.push(...patchNode(patches, state)); } CreateNodeHookCache.delete(collectScripts); transaction.promises = promises; measure('patch node'); }
Set EOL style to Native. Remove tab characters. git-svn-id: 306be505b4acf4ccace778b4b2465237cc9581ba@581081 13f79535-47bb-0310-9956-ffa450edef68
/* * 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 org.apache.commons.logging; /** * Dummy exception that unit tests create instances of when they want to test * logging of an Exception object. */ public class DummyException extends Exception { private static final long serialVersionUID = 1L; public DummyException() { // super("Dummy Exception for unit testing"); } }
/* * 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 org.apache.commons.logging; /** * Dummy exception that unit tests create instances of when they want to test * logging of an Exception object. */ public class DummyException extends Exception { private static final long serialVersionUID = 1L; public DummyException() { // super("Dummy Exception for unit testing"); } }
Remove CRC from data returned by DecodePacket
package medtronic import ( "fmt" ) func (pump *Pump) DecodePacket(packet []byte) []byte { data, err := Decode6b4b(packet) if err != nil { pump.err = err pump.DecodingErrors++ return data } last := len(data) - 1 pktCrc := data[last] data = data[:last] // without CRC calcCrc := Crc8(data) if pktCrc != calcCrc { pump.err = fmt.Errorf("CRC should be %X, not %X", calcCrc, pktCrc) pump.CrcErrors++ } return data } func EncodePacket(data []byte) []byte { // Don't use append() to add the CRC, because append // may write into the array underlying the caller's slice. buf := make([]byte, len(data)+1) copy(buf, data) buf[len(data)] = Crc8(data) return Encode4b6b(buf) } func (pump *Pump) PrintStats() { stats := pump.Radio.Statistics() good := stats.Packets.Received - pump.DecodingErrors - pump.CrcErrors fmt.Printf("\nTX: %6d RX: %6d decode errs: %6d CRC errs: %6d\n", stats.Packets.Sent, good, pump.DecodingErrors, pump.CrcErrors) fmt.Printf("State: %s\n", pump.Radio.State()) }
package medtronic import ( "fmt" ) func (pump *Pump) DecodePacket(packet []byte) []byte { data, err := Decode6b4b(packet) if err != nil { pump.err = err pump.DecodingErrors++ return data } crc := Crc8(data[:len(data)-1]) if data[len(data)-1] != crc { pump.err = fmt.Errorf("CRC should be %X, not %X", crc, data[len(data)-1]) pump.CrcErrors++ } return data } func EncodePacket(data []byte) []byte { // Don't use append() to add the CRC, because append // may write into the array underlying the caller's slice. buf := make([]byte, len(data)+1) copy(buf, data) buf[len(data)] = Crc8(data) return Encode4b6b(buf) } func (pump *Pump) PrintStats() { stats := pump.Radio.Statistics() good := stats.Packets.Received - pump.DecodingErrors - pump.CrcErrors fmt.Printf("\nTX: %6d RX: %6d decode errs: %6d CRC errs: %6d\n", stats.Packets.Sent, good, pump.DecodingErrors, pump.CrcErrors) fmt.Printf("State: %s\n", pump.Radio.State()) }
Fix function name and add missing else block in HMAC.
/**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * HMAC - keyed-Hash Message Authentication Code **~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~**/ (function HMAC(self) { self.fn.hmac = function hmac(hash, data, hkey, block) { var i, akey, ipad, opad; data = self.Encoder(data).trunc(); hkey = self.Encoder(hkey).trunc(); if (hkey.length > block) { akey = hash(hkey).trunc(); } else { akey = self.Encoder(hkey).trunc(); } for (i = 0, ipad = [], opad = []; i < block; i += 1) { ipad[i] = (akey[i] || 0x00) ^ 0x36; opad[i] = (akey[i] || 0x00) ^ 0x5c; } return hash(opad.concat(hash(ipad.concat(data)).trunc())); }; }(Digest));
/**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * HMAC - keyed-Hash Message Authentication Code **~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~**/ (function HMAC(self) { self.fn.hmac = function hmac(hash, data, hkey, block) { var i, akey, ipad, opad; data = self.Encoder(data).trunc(); hkey = self.Encoder(hkey).trunc(); if (hkey.length > block) { akey = hash(hkey).trunc(); } for (i = 0, ipad = [], opad = []; i < block; i += 1) { ipad[i] = (akey[i] || 0x00) ^ 0x36; opad[i] = (akey[i] || 0x00) ^ 0x5c; } return hash(opad.concat(hash(ipad.concat(data)).trunk())); }; }(Digest));
Update unit tests to match correct behaviour
import os import sys import unittest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from smartbot import events class TestEvents(unittest.TestCase): def test_empty(self): event = events.Event() self.assertEqual(len(event.trigger()), 0) def test_with_handlers(self): event = events.Event() event.register(lambda: None) self.assertEqual(len(event.trigger()), 1) def test_custom_comparator(self): comparator = lambda *args, **kwargs: False event = events.Event(default_comparator=comparator) event.register(lambda: None) self.assertEqual(len(event.trigger()), 0) event = events.Event() event.register(lambda: None) self.assertEqual(len(event.trigger(comparator=comparator)), 0) def test_default_comparator(self): event = events.Event() event.register(lambda *args, **kwargs: None, a=10) self.assertEqual(len(event.trigger()), 1) self.assertEqual(len(event.trigger(a=10)), 1) def test_decorator(self): event = events.Event() event()(lambda: None) self.assertEqual(len(event.trigger()), 1)
import os import sys import unittest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from smartbot import events class TestEvents(unittest.TestCase): def test_empty(self): event = events.Event() self.assertEqual(len(event.trigger()), 0) def test_with_handlers(self): event = events.Event() event.register(lambda: None) self.assertEqual(len(event.trigger()), 1) def test_custom_comparator(self): comparator = lambda *args, **kwargs: False event = events.Event(default_comparator=comparator) event.register(lambda: None) self.assertEqual(len(event.trigger()), 0) event = events.Event() event.register(lambda: None) self.assertEqual(len(event.trigger(comparator=comparator)), 0) def test_default_comparator(self): event = events.Event() event.register(lambda *args, **kwargs: None, a=10) self.assertEqual(len(event.trigger()), 0) self.assertEqual(len(event.trigger(a=10)), 1) def test_decorator(self): event = events.Event() event()(lambda: None) self.assertEqual(len(event.trigger()), 1)
Handle namespacing properly so pylons imports without errors. --HG-- branch : trunk
"""Base objects to be exported for use in Controllers""" # Import pkg_resources first so namespace handling is properly done so the # paste imports work import pkg_resources from paste.registry import StackedObjectProxy from pylons.configuration import config __all__ = ['app_globals', 'cache', 'config', 'request', 'response', 'session', 'tmpl_context', 'url'] def __figure_version(): try: from pkg_resources import require import os # NOTE: this only works when the package is either installed, # or has an .egg-info directory present (i.e. wont work with raw # SVN checkout) info = require('pylons')[0] if os.path.dirname(os.path.dirname(__file__)) == info.location: return info.version else: return '(not installed)' except: return '(not installed)' __version__ = __figure_version() app_globals = StackedObjectProxy(name="app_globals") cache = StackedObjectProxy(name="cache") request = StackedObjectProxy(name="request") response = StackedObjectProxy(name="response") session = StackedObjectProxy(name="session") tmpl_context = StackedObjectProxy(name="tmpl_context or C") url = StackedObjectProxy(name="url") translator = StackedObjectProxy(name="translator")
"""Base objects to be exported for use in Controllers""" from paste.registry import StackedObjectProxy from pylons.configuration import config __all__ = ['app_globals', 'cache', 'config', 'request', 'response', 'session', 'tmpl_context', 'url'] def __figure_version(): try: from pkg_resources import require import os # NOTE: this only works when the package is either installed, # or has an .egg-info directory present (i.e. wont work with raw # SVN checkout) info = require('pylons')[0] if os.path.dirname(os.path.dirname(__file__)) == info.location: return info.version else: return '(not installed)' except: return '(not installed)' __version__ = __figure_version() app_globals = StackedObjectProxy(name="app_globals") cache = StackedObjectProxy(name="cache") request = StackedObjectProxy(name="request") response = StackedObjectProxy(name="response") session = StackedObjectProxy(name="session") tmpl_context = StackedObjectProxy(name="tmpl_context or C") url = StackedObjectProxy(name="url") translator = StackedObjectProxy(name="translator")
Fix the circle to rectangle code Was totally incorrect previously
from menpo.shape import PointDirectedGraph import numpy as np def pointgraph_from_circle(fitting): diameter = fitting.diameter radius = diameter / 2.0 y, x = fitting.center y -= radius x -= radius return PointDirectedGraph(np.array(((y, x), (y + diameter, x), (y + diameter, x + diameter), (y, x + diameter))), np.array([[0, 1], [1, 2], [2, 3], [3, 0]]))
from menpo.shape import PointDirectedGraph import numpy as np def pointgraph_from_circle(fitting): y, x = fitting.center radius = fitting.diameter / 2.0 return PointDirectedGraph(np.array(((y, x), (y + radius, x), (y + radius, x + radius), (y, x + radius))), np.array([[0, 1], [1, 2], [2, 3], [3, 0]]))
Set figshare's MAX_FILE_SIZE to 50mb
import os from . import routes, views, model # noqa MODELS = [ model.AddonFigShareUserSettings, model.AddonFigShareNodeSettings, model.FigShareGuidFile ] USER_SETTINGS_MODEL = model.AddonFigShareUserSettings NODE_SETTINGS_MODEL = model.AddonFigShareNodeSettings ROUTES = [routes.settings_routes, routes.api_routes] SHORT_NAME = 'figshare' FULL_NAME = 'figshare' OWNERS = ['user', 'node'] ADDED_DEFAULT = [] ADDED_MANDATORY = [] VIEWS = [] CONFIGS = ['user', 'node'] CATEGORIES = ['storage'] INCLUDE_JS = {} INCLUDE_CSS = {} HAS_HGRID_FILES = True GET_HGRID_DATA = views.hgrid.figshare_hgrid_data MAX_FILE_SIZE = 50 HERE = os.path.dirname(os.path.abspath(__file__)) NODE_SETTINGS_TEMPLATE = None # use default nodes settings templates USER_SETTINGS_TEMPLATE = os.path.join(HERE, 'templates', 'figshare_user_settings.mako')
import os from . import routes, views, model # noqa MODELS = [ model.AddonFigShareUserSettings, model.AddonFigShareNodeSettings, model.FigShareGuidFile ] USER_SETTINGS_MODEL = model.AddonFigShareUserSettings NODE_SETTINGS_MODEL = model.AddonFigShareNodeSettings ROUTES = [routes.settings_routes, routes.api_routes] SHORT_NAME = 'figshare' FULL_NAME = 'figshare' OWNERS = ['user', 'node'] ADDED_DEFAULT = [] ADDED_MANDATORY = [] VIEWS = [] CONFIGS = ['user', 'node'] CATEGORIES = ['storage'] INCLUDE_JS = {} INCLUDE_CSS = {} HAS_HGRID_FILES = True GET_HGRID_DATA = views.hgrid.figshare_hgrid_data HERE = os.path.dirname(os.path.abspath(__file__)) NODE_SETTINGS_TEMPLATE = None # use default nodes settings templates USER_SETTINGS_TEMPLATE = os.path.join(HERE, 'templates', 'figshare_user_settings.mako')
fix(shop): Update admin order show page Update admin order show page see #401
<?php namespace App\Http\Controllers\Admin; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Order; class OrderController extends Controller { public function index() { $orders = Order::all(); return view('admin.orders.index')->with('orders', $orders); } public function show($id) { $order = Order::findOrFail($id); $status = $order->status; $total_amount = 0; foreach ($order->orderProducts as $product) { $amount = $product->price*$product->quantity; $total_amount = $amount + $total_amount; } return view('admin.orders.show') ->with('order', $order) ->with('status', $status) ->with('total_amount', $total_amount); } public function edit(Request $request, $id) { $order = Order::findOrFail($id); $order->update($request->all()); return redirect()->route('adminOrdersShow', ['id' => $id]); } }
<?php namespace App\Http\Controllers\Admin; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Order; class OrderController extends Controller { public function index() { $orders = Order::all(); return view('admin.orders.index')->with('orders', $orders); } public function show($id) { $order = Order::findOrFail($id); $status = $order->status; $total_amount = 0; foreach ($order->orderProducts as $product) { $amount = $product->price*$product->quantity; $total_amount = $amount + $total_amount; } return view('admin.orders.show') ->with('order', $order) ->with('status', $status) ->with('total_amount', $total_amount); } public function edit(Request $request, $id) { $aa = $request->status; $order = Order::findOrFail($id); $order->update($request->all()); return redirect()->route('adminOrdersShow', ['id' => $id]); } }
PUT and DELETE return altered config
module.exports = function(Config, XIBLE, EXPRESS_APP) { EXPRESS_APP.get('/api/config', (req, res) => { res.json(Config.getAll()); }); EXPRESS_APP.put('/api/config/value', (req, res) => { let path = req.body.path; let value = req.body.value; if (typeof path !== 'string' || typeof value === 'undefined') { return res.status(400).end(); } Config.setValue(path, value); res.json(Config.getAll()); }); EXPRESS_APP.delete('/api/config/value', (req, res) => { let path = req.body.path; if (typeof path !== 'string') { return res.status(400).end(); } Config.deleteValue(path); res.json(Config.getAll()); }); EXPRESS_APP.get('/api/config/validatePermissions', (req, res) => { Config.validatePermissions().then((result) => { res.json(result); }); }); };
module.exports = function(Config, XIBLE, EXPRESS_APP) { EXPRESS_APP.get('/api/config', (req, res) => { res.json(Config.getAll()); }); EXPRESS_APP.put('/api/config/value', (req, res) => { let path = req.body.path; let value = req.body.value; if (typeof path !== 'string' || typeof value === 'undefined') { return res.status(400).end(); } Config.setValue(path, value); res.end(); }); EXPRESS_APP.delete('/api/config/value', (req, res) => { let path = req.body.path; if (typeof path !== 'string') { return res.status(400).end(); } Config.deleteValue(path); res.end(); }); EXPRESS_APP.get('/api/config/validatePermissions', (req, res) => { Config.validatePermissions().then((result) => { res.json(result); }); }); };
Include create-react-class in Rollup configuration :newspaper:.
// Rollup plugins. import babel from 'rollup-plugin-babel' import cjs from 'rollup-plugin-commonjs' import globals from 'rollup-plugin-node-globals' import replace from 'rollup-plugin-replace' import resolve from 'rollup-plugin-node-resolve' export default { dest: 'build/app.js', entry: 'src/index.js', format: 'iife', plugins: [ babel({ babelrc: false, exclude: 'node_modules/**', presets: [ [ 'es2015', { modules: false } ], 'stage-0', 'react' ], plugins: [ 'external-helpers' ] }), cjs({ exclude: 'node_modules/process-es6/**', include: [ 'node_modules/create-react-class/**', 'node_modules/fbjs/**', 'node_modules/object-assign/**', 'node_modules/react/**', 'node_modules/react-dom/**', 'node_modules/prop-types/**' ] }), globals(), replace({ 'process.env.NODE_ENV': JSON.stringify('development') }), resolve({ browser: true, main: true }) ], sourceMap: true }
// Rollup plugins. import babel from 'rollup-plugin-babel' import cjs from 'rollup-plugin-commonjs' import globals from 'rollup-plugin-node-globals' import replace from 'rollup-plugin-replace' import resolve from 'rollup-plugin-node-resolve' export default { dest: 'build/app.js', entry: 'src/index.js', format: 'iife', plugins: [ babel({ babelrc: false, exclude: 'node_modules/**', presets: [ [ 'es2015', { modules: false } ], 'stage-0', 'react' ], plugins: [ 'external-helpers' ] }), cjs({ exclude: 'node_modules/process-es6/**', include: [ 'node_modules/fbjs/**', 'node_modules/object-assign/**', 'node_modules/react/**', 'node_modules/react-dom/**', 'node_modules/prop-types/**' ] }), globals(), replace({ 'process.env.NODE_ENV': JSON.stringify('development') }), resolve({ browser: true, main: true }) ], sourceMap: true }
Support any options mapbox source supports. Maintain backwards compatibility.
import Ember from 'ember'; import layout from '../templates/components/mapbox-gl-source'; const { Component, computed, get, getProperties, guidFor } = Ember; export default Component.extend({ layout, tagName: '', map: null, dataType: 'geojson', data: null, options: null, sourceId: computed({ get() { return guidFor(this); }, set(key, val) { return val; } }), init() { this._super(...arguments); const { sourceId, dataType, data } = getProperties(this, 'sourceId', 'dataType', 'data'); let options = get(this, 'options') || {}; if (dataType) { options.type = dataType; } if (data) { options.data = data; } this.map.addSource(sourceId, options); }, didUpdateAttrs() { this._super(...arguments); const { sourceId, data } = getProperties(this, 'sourceId', 'data'); this.map.getSource(sourceId).setData(data); }, willDestroy() { this._super(...arguments); this.map.removeSource(get(this, 'sourceId')); } });
import Ember from 'ember'; import layout from '../templates/components/mapbox-gl-source'; const { Component, computed, get, getProperties, guidFor } = Ember; export default Component.extend({ layout, tagName: '', map: null, dataType: 'geojson', data: null, sourceId: computed({ get() { return guidFor(this); }, set(key, val) { return val; } }), init() { this._super(...arguments); const { sourceId, dataType, data } = getProperties(this, 'sourceId', 'dataType', 'data'); this.map.addSource(sourceId, { type: dataType, data }); }, didUpdateAttrs() { this._super(...arguments); const { sourceId, data } = getProperties(this, 'sourceId', 'data'); this.map.getSource(sourceId).setData(data); }, willDestroy() { this._super(...arguments); this.map.removeSource(get(this, 'sourceId')); } });
Switch from share to singleton The share method has been deprecated.
<?php namespace Badawy\Embedly; use Illuminate\Support\ServiceProvider; class EmbedlyServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application services. * * @return void */ public function boot() { $this->publishes([ __DIR__.'/config/Embedly.php' => config_path('embedly.php'), ]); } /** * Register the application services. * * @return void */ public function register() { $this->mergeConfigFrom(__DIR__.'/config/Embedly.php', 'embedly'); $this->app->singleton('Embedly', function(){ return new Embedly(); }); } }
<?php namespace Badawy\Embedly; use Illuminate\Support\ServiceProvider; class EmbedlyServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application services. * * @return void */ public function boot() { $this->publishes([ __DIR__.'/config/Embedly.php' => config_path('embedly.php'), ]); } /** * Register the application services. * * @return void */ public function register() { $this->mergeConfigFrom(__DIR__.'/config/Embedly.php', 'embedly'); $this->app['Embedly'] = $this->app->share( function($app) { return new Embedly(); } ); } }
Initialize controllers to empty array
var registerSystem = require('../core/system').registerSystem; /** * Tracked controls system. * Maintain list with available tracked controllers. */ module.exports.System = registerSystem('tracked-controls-webxr', { init: function () { this.controllers = []; this.addSessionEventListeners = this.addSessionEventListeners.bind(this); this.onInputSourcesChange = this.onInputSourcesChange.bind(this); this.addSessionEventListeners(); this.el.sceneEl.addEventListener('enter-vr', this.addSessionEventListeners); }, addSessionEventListeners: function () { var sceneEl = this.el; if (!sceneEl.xrSession) { return; } this.onInputSourcesChange(); sceneEl.xrSession.addEventListener('inputsourceschange', this.onInputSourcesChange); }, onInputSourcesChange: function () { this.controllers = this.el.xrSession.getInputSources(); this.el.emit('controllersupdated', undefined, false); } });
var registerSystem = require('../core/system').registerSystem; /** * Tracked controls system. * Maintain list with available tracked controllers. */ module.exports.System = registerSystem('tracked-controls-webxr', { init: function () { this.addSessionEventListeners = this.addSessionEventListeners.bind(this); this.onInputSourcesChange = this.onInputSourcesChange.bind(this); this.addSessionEventListeners(); this.el.sceneEl.addEventListener('enter-vr', this.addSessionEventListeners); }, addSessionEventListeners: function () { var sceneEl = this.el; if (!sceneEl.xrSession) { return; } this.onInputSourcesChange(); sceneEl.xrSession.addEventListener('inputsourceschange', this.onInputSourcesChange); }, onInputSourcesChange: function () { this.controllers = this.el.xrSession.getInputSources(); this.el.emit('controllersupdated', undefined, false); } });
Fix flake8 line length issue Signed-off-by: Chris Harris <a361e89d1eba6c570561222d75facbbf7aaeeafe@kitware.com>
from setuptools import setup, find_packages jsonpatch_uri \ = 'jsonpatch@https://github.com/cjh1/python-json-patch/archive/tomviz.zip' setup( name='tomviz-pipeline', version='0.0.1', description='Tomviz python external pipeline execution infrastructure.', author='Kitware, Inc.', author_email='kitware@kitware.com', url='https://www.tomviz.org/', license='BSD 3-Clause', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: BSD 3-Clause', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5' ], packages=find_packages(), install_requires=['tqdm', 'h5py', 'numpy==1.16.4', 'click', 'scipy'], extras_require={ 'interactive': [ jsonpatch_uri, 'marshmallow'], 'itk': ['itk'], 'pyfftw': ['pyfftw'] }, entry_points={ 'console_scripts': [ 'tomviz-pipeline = tomviz.cli:main' ] } )
from setuptools import setup, find_packages setup( name='tomviz-pipeline', version='0.0.1', description='Tomviz python external pipeline execution infrastructure.', author='Kitware, Inc.', author_email='kitware@kitware.com', url='https://www.tomviz.org/', license='BSD 3-Clause', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: BSD 3-Clause', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5' ], packages=find_packages(), install_requires=['tqdm', 'h5py', 'numpy==1.16.4', 'click', 'scipy'], extras_require={ 'interactive': ['jsonpatch@https://github.com/cjh1/python-json-patch/archive/tomviz.zip', 'marshmallow'], 'itk': ['itk'], 'pyfftw': ['pyfftw'] }, entry_points={ 'console_scripts': [ 'tomviz-pipeline = tomviz.cli:main' ] } )
Move most expensive type check to last
'use strict'; // MODULES // var debug = require( 'debug' )( 'time-series:set:x' ); var isTypedArray = require( '@stdlib/utils/is-typed-array' ); var isNumberArray = require( '@stdlib/utils/is-number' ).isPrimitiveNumberArray; var isEmptyArray = require( '@stdlib/utils/is-empty-array' ); var events = require( './../../events' ); // VARIABLES // var CHANGE_EVENT = events( 'x' ); // SET // /** * Sets the plot x-values. * * @private * @param {(NumericArray|EmptyArray)} x - x-values * @throws {TypeError} must be a numeric or empty array */ function set( x ) { /*jshint validthis: true */ // TODO: eslint // TODO: allow a Date array; convert to timestamps if ( !isTypedArray( x ) && !isEmptyArray( x ) && !isNumberArray( x ) ) { throw new TypeError( 'invalid value. `x` must be a numeric or empty array. Value: `' + x + '`.' ); } debug( 'Current value: %s.', JSON.stringify( this._xData ) ); // TODO: copy? this._xData = x; debug( 'New Value: %s.', JSON.stringify( this._xData ) ); this.emit( CHANGE_EVENT ); } // end FUNCTION set() // EXPORTS // module.exports = set;
'use strict'; // MODULES // var debug = require( 'debug' )( 'time-series:set:x' ); var isTypedArray = require( '@stdlib/utils/is-typed-array' ); var isNumberArray = require( '@stdlib/utils/is-number' ).isPrimitiveNumberArray; var isEmptyArray = require( '@stdlib/utils/is-empty-array' ); var events = require( './../../events' ); // VARIABLES // var CHANGE_EVENT = events( 'x' ); // SET // /** * Sets the plot x-values. * * @private * @param {(NumericArray|EmptyArray)} x - x-values * @throws {TypeError} must be a numeric or empty array */ function set( x ) { /*jshint validthis: true */ // TODO: eslint // TODO: allow a Date array; convert to timestamps if ( !isTypedArray( x ) && !isNumberArray( x ) && !isEmptyArray( x ) ) { throw new TypeError( 'invalid value. `x` must be a numeric or empty array. Value: `' + x + '`.' ); } debug( 'Current value: %s.', JSON.stringify( this._xData ) ); // TODO: copy? this._xData = x; debug( 'New Value: %s.', JSON.stringify( this._xData ) ); this.emit( CHANGE_EVENT ); } // end FUNCTION set() // EXPORTS // module.exports = set;
Use strict mode in karma E2E test congig file
// Karma configuration // http://karma-runner.github.io/0.10/config/configuration-file.html module.exports = function(config) { 'use strict'; config.set({ // base path, that will be used to resolve files and exclude basePath: '', // testing framework to use (jasmine/mocha/qunit/...) frameworks: ['ng-scenario'], // list of files / patterns to load in the browser files: [ 'test/e2e/**/*.js' ], // list of files / patterns to exclude exclude: [], // web server port port: 8080, // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: false, // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) browsers: ['Chrome'], // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun: false // Uncomment the following lines if you are using grunt's server to run the tests // proxies: { // '/': 'http://localhost:9000/' // }, // URL root prevent conflicts with the site root // urlRoot: '_karma_' }); };
// Karma configuration // http://karma-runner.github.io/0.10/config/configuration-file.html module.exports = function(config) { config.set({ // base path, that will be used to resolve files and exclude basePath: '', // testing framework to use (jasmine/mocha/qunit/...) frameworks: ['ng-scenario'], // list of files / patterns to load in the browser files: [ 'test/e2e/**/*.js' ], // list of files / patterns to exclude exclude: [], // web server port port: 8080, // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: false, // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) browsers: ['Chrome'], // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun: false // Uncomment the following lines if you are using grunt's server to run the tests // proxies: { // '/': 'http://localhost:9000/' // }, // URL root prevent conflicts with the site root // urlRoot: '_karma_' }); };
Make get_readable_list process tuples, too
def get_readable_list(passed_list, sep=', ', end=''): output = "" if isinstance(passed_list, list) or isinstance(passed_list, tuple): for i, item in enumerate(passed_list): if len(passed_list) is 1: output += str(item) else: if i is not (len(passed_list) - 1): output += str(item) + sep else: output += str(item) elif isinstance(passed_list, dict): for i, item in enumerate(passed_list.values()): if len(passed_list) is 1: output += str(item) else: if i is not (len(passed_list) - 1): output += str(item) + sep else: output += str(item) return output + end def get_list_as_english(passed_list): output = "" for i, item in enumerate(passed_list): if len(passed_list) is 1: output += str(item) + ' ' elif len(passed_list) is 2: output += str(item) if i is not (len(passed_list) - 1): output += " and " else: output += "" else: if i is not (len(passed_list) - 1): output += str(item) + ", " else: output += "and " + str(item) + ", " return output
def get_readable_list(passed_list, sep=', ', end=''): output = "" if isinstance(passed_list, list): for i, item in enumerate(passed_list): if len(passed_list) is 1: output += str(item) else: if i is not (len(passed_list) - 1): output += str(item) + sep else: output += str(item) elif isinstance(passed_list, dict): for i, item in enumerate(passed_list.values()): if len(passed_list) is 1: output += str(item) else: if i is not (len(passed_list) - 1): output += str(item) + sep else: output += str(item) return output + end def get_list_as_english(passed_list): output = "" for i, item in enumerate(passed_list): if len(passed_list) is 1: output += str(item) + ' ' elif len(passed_list) is 2: output += str(item) if i is not (len(passed_list) - 1): output += " and " else: output += "" else: if i is not (len(passed_list) - 1): output += str(item) + ", " else: output += "and " + str(item) + ", " return output
Make the name of an organization required
from rest_framework import serializers from bluebottle.organizations.models import Organization from bluebottle.utils.serializers import URLField class OrganizationSerializer(serializers.ModelSerializer): class Meta: model = Organization fields = ('id', 'name', 'slug', 'address_line1', 'address_line2', 'city', 'state', 'country', 'postal_code', 'phone_number', 'website', 'email') class ManageOrganizationSerializer(serializers.ModelSerializer): slug = serializers.SlugField(required=False, allow_null=True) name = serializers.CharField(required=True) website = URLField(required=False, allow_blank=True) email = serializers.EmailField(required=False, allow_blank=True) class Meta: model = Organization fields = OrganizationSerializer.Meta.fields + ('partner_organizations', 'created', 'updated')
from rest_framework import serializers from bluebottle.organizations.models import Organization from bluebottle.utils.serializers import URLField class OrganizationSerializer(serializers.ModelSerializer): class Meta: model = Organization fields = ('id', 'name', 'slug', 'address_line1', 'address_line2', 'city', 'state', 'country', 'postal_code', 'phone_number', 'website', 'email') class ManageOrganizationSerializer(serializers.ModelSerializer): slug = serializers.SlugField(required=False, allow_null=True) name = serializers.CharField(required=True, allow_blank=True) website = URLField(required=False, allow_blank=True) email = serializers.EmailField(required=False, allow_blank=True) class Meta: model = Organization fields = OrganizationSerializer.Meta.fields + ('partner_organizations', 'created', 'updated')
Print a stacktrace when a failure is caused by an exception When a spec fails due to an exception, the exception's stacktrace is printed when running the spec in Rhino. This helps to locate the code that caused the exception.
(function($) { $(Screw).bind("before", function(){ function example_name(element){ // TODO: handle nested describes! var context_name = $(element).parents(".describe").children("h1").text(); var example_name = $(element).children("h2").text(); return context_name + " - " + example_name; } $('.it') .bind('passed', function(){ java.lang.System.out.print("."); }) .bind('failed', function(e, reason){ print("\nFAILED: " + example_name(this)); print(" " + reason + "\n"); if (reason.rhinoException) { print(reason.rhinoException.scriptStackTrace); } }); }); $(Screw).bind("after", function(){ var testCount = $('.passed').length + $('.failed').length; var failures = $('.failed').length; var elapsedTime = ((new Date() - Screw.suite_start_time)/1000.0); print("\n") print(testCount + ' test(s), ' + failures + ' failure(s)'); print(elapsedTime.toString() + " seconds elapsed"); if(failures > 0) { java.lang.System.exit(1) }; }); })(jQuery);
(function($) { $(Screw).bind("before", function(){ function example_name(element){ // TODO: handle nested describes! var context_name = $(element).parents(".describe").children("h1").text(); var example_name = $(element).children("h2").text(); return context_name + " - " + example_name; } $('.it') .bind('passed', function(){ java.lang.System.out.print("."); }) .bind('failed', function(e, reason){ print("\nFAILED: " + example_name(this)); print(" " + reason + "\n"); }); }); $(Screw).bind("after", function(){ var testCount = $('.passed').length + $('.failed').length; var failures = $('.failed').length; var elapsedTime = ((new Date() - Screw.suite_start_time)/1000.0); print("\n") print(testCount + ' test(s), ' + failures + ' failure(s)'); print(elapsedTime.toString() + " seconds elapsed"); if(failures > 0) { java.lang.System.exit(1) }; }); })(jQuery);
Increase timeouts for e2e tests on Sauce Labs.
// Protractor configuration // https://github.com/angular/protractor/blob/master/docs/referenceConf.js var TIMEOUT = 120000; exports.config = { specs: ['e2e/**/*.js'], sauceUser: process.env.SAUCE_USERNAME, sauceKey: process.env.SAUCE_ACCESS_KEY, multiCapabilities: [{ name: 'End-to-End Tests: Chrome 36', browserName: 'chrome', version: '36', 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER, build: process.env.TRAVIS_BUILD_NUMBER, tags: ['CI'] }, { name: 'End-to-End Tests: Firefox', browserName: 'firefox', 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER, build: process.env.TRAVIS_BUILD_NUMBER, tags: ['CI'] }, { name: 'End-to-End Tests: Safari', browserName: 'safari', platform: 'OS X 10.9', version: '7', 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER, build: process.env.TRAVIS_BUILD_NUMBER, tags: ['CI'] }], getPageTimeout: TIMEOUT, allScriptsTimeout: TIMEOUT, jasmineNodeOpts: { defaultTimeoutInterval: TIMEOUT } };
// Protractor configuration // https://github.com/angular/protractor/blob/master/docs/referenceConf.js exports.config = { specs: ['e2e/**/*.js'], sauceUser: process.env.SAUCE_USERNAME, sauceKey: process.env.SAUCE_ACCESS_KEY, multiCapabilities: [{ name: 'End-to-End Tests: Chrome 36', browserName: 'chrome', version: '36', 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER, build: process.env.TRAVIS_BUILD_NUMBER, tags: ['CI'] }, { name: 'End-to-End Tests: Firefox', browserName: 'firefox', 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER, build: process.env.TRAVIS_BUILD_NUMBER, tags: ['CI'] }, { name: 'End-to-End Tests: Safari', browserName: 'safari', platform: 'OS X 10.9', version: '7', 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER, build: process.env.TRAVIS_BUILD_NUMBER, tags: ['CI'] }] };
Fix table names in flask-admin
from flask import Flask from flask_login import LoginManager from flask_bcrypt import Bcrypt from flask_admin import Admin from flask_admin.contrib.peewee import ModelView from playhouse.flask_utils import FlaskDB app = Flask(__name__) app.config.from_object('config') @app.before_request def _db_connect(): db.connect() @app.teardown_request def _db_close(exc): if not db.is_closed(): db.close() login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'users.login' flask_db = FlaskDB(app) db = flask_db.database bcrypt = Bcrypt(app) from app.models import User, Page, Post, Event admin = Admin(app, name='teknologkoren.se') admin.add_view(ModelView(User, name='User')) admin.add_view(ModelView(Page, name='Page')) admin.add_view(ModelView(Post, name='Post')) admin.add_view(ModelView(Event, name='Event')) from app.views import (general, users, index, about, intranet) app.register_blueprint(general.mod) app.register_blueprint(users.mod) app.register_blueprint(index.mod) app.register_blueprint(about.mod) app.register_blueprint(intranet.mod)
from flask import Flask from flask_login import LoginManager from flask_bcrypt import Bcrypt from flask_admin import Admin from flask_admin.contrib.peewee import ModelView from playhouse.flask_utils import FlaskDB app = Flask(__name__) app.config.from_object('config') @app.before_request def _db_connect(): db.connect() @app.teardown_request def _db_close(exc): if not db.is_closed(): db.close() login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'users.login' flask_db = FlaskDB(app) db = flask_db.database bcrypt = Bcrypt(app) from app.models import User, Page, Post, Event admin = Admin(app, name='teknologkoren.se') admin.add_view(ModelView(User, db)) admin.add_view(ModelView(Page, db)) admin.add_view(ModelView(Post, db)) admin.add_view(ModelView(Event, db)) from app.views import (general, users, index, about, intranet) app.register_blueprint(general.mod) app.register_blueprint(users.mod) app.register_blueprint(index.mod) app.register_blueprint(about.mod) app.register_blueprint(intranet.mod)
Use slideToggle for brief animated show / hide
$(document).ready(function() { $(".additional-options-toggle").on("click", function(e) { e.preventDefault(); $("#" + $(this).data("export-section") + "_options").slideToggle(200); }); jQuery.validator.addMethod("wanikaniLevelRange", function(value, element) { return this.optional(element) || /^[0-9]+(,[0-9]+)*$/.test(value); }, "Please use a list of comma-separated numbers (e.g. '1,10,25')"); $(".full-lists-form input[name='argument']").on("click", function() { $(this).prev("input[id='selected_levels_specific']").prop("checked", true); }); $("#critical_items_form").validate({ rules: { argument: { required: false, range: [1, 99] } }, messages: { argument: "Please enter a value between 1 and 99, or leave blank for a default of 75." } }); var fullListsValidation = { rules: { argument: { wanikaniLevelRange: true } } }; $("#kanji_form").validate(fullListsValidation); $("#vocabulary_form").validate(fullListsValidation); $("#radicals_form").validate(fullListsValidation); });
$(document).ready(function() { $(".additional-options-toggle").on("click", function(e) { e.preventDefault(); $("#" + $(this).data("export-section") + "_options").toggle(); }); jQuery.validator.addMethod("wanikaniLevelRange", function(value, element) { return this.optional(element) || /^[0-9]+(,[0-9]+)*$/.test(value); }, "Please use a list of comma-separated numbers (e.g. '1,10,25')"); $(".full-lists-form input[name='argument']").on("click", function() { $(this).prev("input[id='selected_levels_specific']").prop("checked", true); }); $("#critical_items_form").validate({ rules: { argument: { required: false, range: [1, 99] } }, messages: { argument: "Please enter a value between 1 and 99, or leave blank for a default of 75." } }); var fullListsValidation = { rules: { argument: { wanikaniLevelRange: true } } }; $("#kanji_form").validate(fullListsValidation); $("#vocabulary_form").validate(fullListsValidation); $("#radicals_form").validate(fullListsValidation); });
Make sure all package files are committed correctly when bumping a version
module.exports = function(grunt) { // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), uglify: { options: { banner: '/*! Version: <%= pkg.version %>\nDate: <%= grunt.template.today("yyyy-mm-dd") %> */\n', preserveComments: 'some' }, build: { src: 'src/L.Control.Locate.js', dest: 'dist/L.Control.Locate.min.js' } }, cssmin: { combine: { files: { 'dist/L.Control.Locate.min.css': ['src/L.Control.Locate.css'], 'dist/L.Control.Locate.ie.min.css': ['src/L.Control.Locate.ie.css'] } } }, bump: { options: { files: ['package.json', 'bower.json'], commitFiles: ['package.json', 'bower.json'], push: false } }, }); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.loadNpmTasks('grunt-bump'); // Default task(s). grunt.registerTask('default', ['uglify', 'cssmin']); };
module.exports = function(grunt) { // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), uglify: { options: { banner: '/*! Version: <%= pkg.version %>\nDate: <%= grunt.template.today("yyyy-mm-dd") %> */\n', preserveComments: 'some' }, build: { src: 'src/L.Control.Locate.js', dest: 'dist/L.Control.Locate.min.js' } }, cssmin: { combine: { files: { 'dist/L.Control.Locate.min.css': ['src/L.Control.Locate.css'], 'dist/L.Control.Locate.ie.min.css': ['src/L.Control.Locate.ie.css'] } } }, bump: { options: { files: ['package.json', 'bower.json'], push: false } }, }); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.loadNpmTasks('grunt-bump'); // Default task(s). grunt.registerTask('default', ['uglify', 'cssmin']); };
Return all properties (including nulls)
$.fn.filterByData = function(prop, val) { return this.filter( function() { return $(this).data(prop)==val; } ); }; $(document).ready(function() { var radios = $('.table-view.radio'); var saveBtn = $('#save'); var options = $.url().param(); radios.each(function (index) { var radio = $(this); var buttons = radio.find('li.table-view-cell > a'); if (options[radio.data('name')]) { var button = buttons.filterByData('value', options[radio.data('name')]); button.addClass('active'); } buttons.click(function() { buttons.removeClass('active'); $(this).addClass('active'); }); }); saveBtn.click(function() { var object = {}; radios.each(function (index) { var radio = $(this); var key = radio.data('name'); var value = radio.find('.active').first().data('value'); object[key] = value; }); window.location.href = "pebblejs://close#" + encodeURIComponent(JSON.stringify(object)); }); });
$.fn.filterByData = function(prop, val) { return this.filter( function() { return $(this).data(prop)==val; } ); }; $(document).ready(function() { var radios = $('.table-view.radio'); var saveBtn = $('#save'); var options = $.url().param(); radios.each(function (index) { var radio = $(this); var buttons = radio.find('li.table-view-cell > a'); if (options[radio.data('name')]) { var button = buttons.filterByData('value', options[radio.data('name')]); button.addClass('active'); } buttons.click(function() { buttons.removeClass('active'); $(this).addClass('active'); }); }); saveBtn.click(function() { var object = {}; radios.each(function (index) { var radio = $(this); var key = radio.data('name'); var value = radio.find('.active').first().data('value'); if (value) { object[key] = value; } }); window.location.href = "pebblejs://close#" + encodeURIComponent(JSON.stringify(object)); }); });
Allow picking people from NHA.
<?php $db->query('SELECT alliance_id,alliance_name,leader_id FROM alliance WHERE game_id=' . SmrSession::$game_id . ' AND alliance_id=' . $player->getAllianceID() . ' LIMIT 1'); $db->nextRecord(); $template->assign('PageTopic',stripslashes($db->getField('alliance_name')) . ' (' . $db->getField('alliance_id') . ')'); include(get_file_loc('menue.inc')); create_alliance_menue($alliance_id,$db->getField('leader_id')); $players = array(); $db->query('SELECT * FROM player WHERE game_id='.$db->escapeNumber($player->getGameID()).' AND (alliance_id=0 OR alliance_id=302) AND account_id NOT IN (SELECT account_id FROM draft_leaders WHERE draft_leaders.account_id=player.account_id) AND sector_id!=1;'); while($db->nextRecord()) { $pickPlayer =& SmrPlayer::getPlayer($db->getRow(), $player->getGameID()); $players[] = array('Player' => &$pickPlayer, 'PlayerPickHREF' => SmrSession::get_new_href(create_container('alliance_pick_processing.php','',array('PickedAccountID'=>$pickPlayer->getAccountID())))); } $template->assignByRef('PickPlayers', $players); ?>
<?php $db->query('SELECT alliance_id,alliance_name,leader_id FROM alliance WHERE game_id=' . SmrSession::$game_id . ' AND alliance_id=' . $player->getAllianceID() . ' LIMIT 1'); $db->nextRecord(); $template->assign('PageTopic',stripslashes($db->getField('alliance_name')) . ' (' . $db->getField('alliance_id') . ')'); include(get_file_loc('menue.inc')); create_alliance_menue($alliance_id,$db->getField('leader_id')); $players = array(); $db->query('SELECT * FROM player WHERE game_id='.$db->escapeNumber($player->getGameID()).' AND alliance_id=0 AND account_id NOT IN (SELECT account_id FROM draft_leaders WHERE draft_leaders.account_id=player.account_id) AND sector_id!=1;'); while($db->nextRecord()) { $pickPlayer =& SmrPlayer::getPlayer($db->getRow(), $player->getGameID()); $players[] = array('Player' => &$pickPlayer, 'PlayerPickHREF' => SmrSession::get_new_href(create_container('alliance_pick_processing.php','',array('PickedAccountID'=>$pickPlayer->getAccountID())))); } $template->assignByRef('PickPlayers', $players); ?>
[Misc] Add missing newline (new checkstyle rule)
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.rendering.internal.macro.message; import javax.inject.Named; import javax.inject.Singleton; import org.xwiki.component.annotation.Component; /** * Displays an error message. * * @version $Id$ * @since 2.0M3 */ @Component @Named("error") @Singleton public class ErrorMessageMacro extends AbstractMessageMacro { /** * Create and initialize the descriptor of the macro. */ public ErrorMessageMacro() { super("Error Message", "Displays an error message note."); setDefaultCategory(DEFAULT_CATEGORY_FORMATTING); } }
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.rendering.internal.macro.message; import javax.inject.Named; import javax.inject.Singleton; import org.xwiki.component.annotation.Component; /** * Displays an error message. * * @version $Id$ * @since 2.0M3 */ @Component @Named("error") @Singleton public class ErrorMessageMacro extends AbstractMessageMacro { /** * Create and initialize the descriptor of the macro. */ public ErrorMessageMacro() { super("Error Message", "Displays an error message note."); setDefaultCategory(DEFAULT_CATEGORY_FORMATTING); } }
Add a test for functions with keyword only arguments This adds a test to ensure that no error is raised if a trailing comma is missing from a function definition that has keyword only arguments. Reviewed-by: Jakub Stasiak <1d3764b91b902f6b45836e2498da81fe35caf6d6@stasiak.at>
def f1(a, # S100 b): # S101 pass def f2( a, b # S101 ): pass def f3( a, b, ): pass # trailing comma after *args or **kwargs is a syntax error therefore # we don't want to enforce it such situations def f4( a, *args ): pass def f5( b, **kwargs ): pass def f6( *, d ): pass f3(1, # S100 2) # S101 f3( 1, 2) # S101 f3( 1, 2 # S101 ) f3( 1, 2, ) kwargs = {} f5('-o', # S100 some_keyword_argument='./') # S101 f5( b='something', ) ( ''. format())
def f1(a, # S100 b): # S101 pass def f2( a, b # S101 ): pass def f3( a, b, ): pass # trailing comma after *args or **kwargs is a syntax error therefore # we don't want to enforce it such situations def f4( a, *args ): pass def f5( b, **kwargs ): pass f3(1, # S100 2) # S101 f3( 1, 2) # S101 f3( 1, 2 # S101 ) f3( 1, 2, ) kwargs = {} f5('-o', # S100 some_keyword_argument='./') # S101 f5( b='something', ) ( ''. format())
Enable turning on SSL for apiHost with ?apiSSL=yes
/*jslint browser: true ,undef: true *//*global Ext*/ Ext.define('Slate.API', { extend: 'Emergence.util.AbstractAPI', singleton: true, // example function getMySections: function(callback, scope) { this.request({ url: '/sections', method: 'GET', params: { AllCourses: 'false' }, success: callback, scope: scope }); } }, function(API) { var pageParams = Ext.Object.fromQueryString(location.search); // allow API host to be overridden via apiHost param if (pageParams.apiHost) { API.setHost(pageParams.apiHost); API.setUseSSL(!!pageParams.apiSSL); } });
/*jslint browser: true ,undef: true *//*global Ext*/ Ext.define('Slate.API', { extend: 'Emergence.util.AbstractAPI', singleton: true, // example function getMySections: function(callback, scope) { this.request({ url: '/sections', method: 'GET', params: { AllCourses: 'false' }, success: callback, scope: scope }); } }, function(API) { var pageParams = Ext.Object.fromQueryString(location.search); // allow API host to be overridden via apiHost param if (pageParams.apiHost) { API.setHost(pageParams.apiHost); API.setUseSSL(false); } });
Remove dependency on ExecutionTool to break a build cycle. PiperOrigin-RevId: 304627771
// Copyright 2014 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.buildtool.buildevent; import com.google.common.collect.ImmutableList; import com.google.devtools.build.lib.analysis.TransitiveInfoCollection; import java.util.Collection; /** * This event is fired from {@link com.google.devtools.build.lib.buildtool.ExecutionTool} to * indicate that the execution phase of the build is starting. */ public class ExecutionStartingEvent { private final Collection<TransitiveInfoCollection> targets; /** * Construct the event with a set of targets. * @param targets Remaining active targets. */ public ExecutionStartingEvent(Collection<? extends TransitiveInfoCollection> targets) { this.targets = ImmutableList.copyOf(targets); } /** * @return The set of active targets remaining, which is a subset * of the targets in the user request. */ public Collection<TransitiveInfoCollection> getTargets() { return targets; } }
// Copyright 2014 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.buildtool.buildevent; import com.google.common.collect.ImmutableList; import com.google.devtools.build.lib.analysis.TransitiveInfoCollection; import com.google.devtools.build.lib.buildtool.ExecutionTool; import java.util.Collection; /** * This event is fired from {@link ExecutionTool#executeBuild} to indicate that the execution phase * of the build is starting. */ public class ExecutionStartingEvent { private final Collection<TransitiveInfoCollection> targets; /** * Construct the event with a set of targets. * @param targets Remaining active targets. */ public ExecutionStartingEvent(Collection<? extends TransitiveInfoCollection> targets) { this.targets = ImmutableList.copyOf(targets); } /** * @return The set of active targets remaining, which is a subset * of the targets in the user request. */ public Collection<TransitiveInfoCollection> getTargets() { return targets; } }
Implement lookupItemController() function in controller array
import Em from 'ember'; import Column from './column'; var ArrayProxy = Em.ArrayProxy; var Sortable = Em.SortableMixin; var ControllerArray = ArrayProxy.extend({ itemController: Em.ObjectController, lookupItemController: function (object) { return this.get('itemController'); }, mapController: function (obj) { var controllerClass = this.lookupItemController(obj); if (controllerClass) { return controllerClass.create({ target: this, parentController: this, content: obj }); } }, arrangedContent: function () { return this.get('content').map(this.mapController, this); }.property('content'), contentArrayDidChange: function (arr, i, removedCount, addedCount) { var addedObjects = arr.slice(i, i + addedCount); addedObjects = addedObjects.map(this.mapController, this); this.get('arrangedContent').replace(i, removedCount, addedObjects); } }); var Columns = ArrayProxy.extend(Sortable, { content: function (key, value) { return ControllerArray.create({ itemController: Column, content: value }); }.property() }); export default Columns;
import Em from 'ember'; import Column from './column'; var ArrayProxy = Em.ArrayProxy; var Sortable = Em.SortableMixin; var ControllerArray = ArrayProxy.extend({ itemController: Em.ObjectController, mapController: function (obj) { return this.itemController.create({ content: obj }); }, arrangedContent: function () { return this.get('content').map(this.mapController, this); }.property('content'), contentArrayDidChange: function (arr, i, removedCount, addedCount) { var addedObjects = arr.slice(i, i + addedCount); addedObjects = addedObjects.map(this.mapController, this); this.get('arrangedContent').replace(i, removedCount, addedObjects); } }); var Columns = ArrayProxy.extend(Sortable, { content: function (key, value) { return ControllerArray.create({ itemController: Column, content: value }); }.property() }); export default Columns;
Select correct for vote detection
# -*- coding: utf-8 -*- from django.core.urlresolvers import reverse from django.views.generic import ListView, TemplateView, RedirectView from django.contrib import auth from bakery.cookies.models import Cookie from bakery.socialize.models import Vote class HomeView(ListView): model = Cookie template_name = 'home.html' def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) user_votes = Vote.objects.get_for_user(self.request.user.id) voted_cookie_ids = user_votes.values_list('cookie_id', flat=True).all() context['voted_cookie_ids'] = voted_cookie_ids return context home = HomeView.as_view() class StylesView(TemplateView): template_name = 'styles.html' styles = StylesView.as_view() class LoginErrorView(TemplateView): template_name = 'error.html' login_error = LoginErrorView.as_view() class LogoutView(RedirectView): permanent = False def get_redirect_url(self, **kwargs): auth.logout(self.request) return reverse('home') logout = LogoutView.as_view()
# -*- coding: utf-8 -*- from django.core.urlresolvers import reverse from django.views.generic import ListView, TemplateView, RedirectView from django.contrib import auth from bakery.cookies.models import Cookie from bakery.socialize.models import Vote class HomeView(ListView): model = Cookie template_name = 'home.html' def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) user_votes = Vote.objects.get_for_user(self.request.user.id) voted_cookie_ids = user_votes.values_list('pk', flat=True).all() context['voted_cookie_ids'] = voted_cookie_ids return context home = HomeView.as_view() class StylesView(TemplateView): template_name = 'styles.html' styles = StylesView.as_view() class LoginErrorView(TemplateView): template_name = 'error.html' login_error = LoginErrorView.as_view() class LogoutView(RedirectView): permanent = False def get_redirect_url(self, **kwargs): auth.logout(self.request) return reverse('home') logout = LogoutView.as_view()
Split up the external url validation in a valid and an invalid test
<?php namespace ForkCMS\Bundle\CoreBundle\Tests\Validator; use ForkCMS\Bundle\CoreBundle\Validator\UrlValidator; use PHPUnit\Framework\TestCase; class UrlValidatorTest extends TestCase { public function testValidExternalUrlValidation() { $urlValidator = new UrlValidator(); $urls = [ 'http://test.com/index.js', 'https://test.com/index.js', ]; foreach ($urls as $url) { $this->assertTrue($urlValidator->isExternalUrl($url), $url . ' was not validated correctly'); } } public function testInvalidExternalUrlValidation() { $urlValidator = new UrlValidator(); $urls = [ '/index.js', 'index.js', 'dev/index.js', '/dev/index.js', ]; foreach ($urls as $url) { $this->assertFalse($urlValidator->isExternalUrl($url), $url . ' was not validated correctly'); } } }
<?php namespace ForkCMS\Bundle\CoreBundle\Tests\Validator; use ForkCMS\Bundle\CoreBundle\Validator\UrlValidator; use PHPUnit\Framework\TestCase; class UrlValidatorTest extends TestCase { public function testExternalUrlValidation() { $urlValidator = new UrlValidator(); $urls = [ 'http://test.com/index.js' => true, 'https://test.com/index.js' => true, '/index.js' => false, 'index.js' => false, 'dev/index.js' => false, '/dev/index.js' => false, ]; foreach ($urls as $url => $isExternal) { $this->assertEquals($isExternal, $urlValidator->isExternalUrl($url), $url . ' was not validated correctly'); } } }
Add new decorator for suvery_data
from django.conf.urls.defaults import * from . import views urlpatterns = patterns('', url(r'^profile/$', views.profile_index, name='survey_profile'), url(r'^profile/electric/$', views.profile_electric, name='survey_profile_electric'), #url(r'^profile/intake/$', views.survey_intake, name='survey_profile_intake'), url(r'^profile/surveys/$', views.survey_management, name='survey_management'), url(r'^main/$', views.main_index), url(r'^survey_management/$', views.survey_management, name='survey_management'), #url(r'^survey_data/(?P<survey_shortname>.+)/(?P<id>\d+)/$', views.survey_data, name='survey_data'), url(r'^intake/$', views.survey_data, name='survey_data'), url(r'^monthly/(?P<id>\d+)/$', views.survey_data_monthly ,name='survey_data_monthly'), url(r'^monthly/(?P<id>\d+)/update/$', views.survey_update_monthly ,name='survey_update_monthly'), url(r'^thanks_profile/$', views.thanks_profile, name='profile_thanks'), #url(r'^select/$', views.select_user, name='survey_select_user'), url(r'^$', views.index, name='survey_index'), )
from django.conf.urls.defaults import * from . import views urlpatterns = patterns('', url(r'^profile/$', views.profile_index, name='survey_profile'), url(r'^profile/electric/$', views.profile_electric, name='survey_profile_electric'), url(r'^profile/surveys/$', views.survey_management, name='survey_management'), url(r'^main/$', views.main_index), url(r'^survey_management/$', views.survey_management, name='survey_management'), url(r'^intake/view/$', views.survey_intake_view, name='survey_intake_view'), url(r'^intake/update/$', views.survey_intake_update, name='survey_intake_update'), url(r'^monthly/(?P<id>\d+)/$', views.survey_monthly ,name='survey_monthly'), url(r'^monthly/(?P<id>\d+)/update/$', views.survey_monthly_update ,name='survey_monthly_update'), url(r'^thanks_profile/$', views.thanks_profile, name='profile_thanks'), #url(r'^select/$', views.select_user, name='survey_select_user'), url(r'^$', views.index, name='survey_index'), )
Move splash screen farther afield on click.
#pragma strict private var _gameManager : GameManager; private var _isTriggered = false; function Start() { _gameManager = GameManager.Instance(); } function Update() { } function OnMouseDown() { if (!_isTriggered) { rollAway(); _isTriggered = true; } } private function rollAway() { iTween.RotateBy(gameObject, iTween.Hash( 'amount', Vector3(0,0,0.05) ,'easetype', 'easeInOutBack' ,'time', 1.0 )); iTween.MoveTo(gameObject, iTween.Hash( 'position', transform.position + Vector3(-Screen2D.worldWidth() * 1.5,0,0) ,'easetype', 'easeInOutBack' ,'time', 1.0 )); yield WaitForSeconds(0.5); _gameManager.SetState(GameManager.GameState.Game); }
#pragma strict private var _gameManager : GameManager; private var _isTriggered = false; function Start() { _gameManager = GameManager.Instance(); } function Update() { } function OnMouseDown() { if (!_isTriggered) { rollAway(); _isTriggered = true; } } private function rollAway() { iTween.RotateBy(gameObject, iTween.Hash( 'amount', Vector3(0,0,0.05) ,'easetype', 'easeInOutBack' ,'time', 1.0 )); iTween.MoveTo(gameObject, iTween.Hash( 'position', transform.position + Vector3(-Screen2D.worldWidth(),0,0) ,'easetype', 'easeInOutBack' ,'time', 1.0 )); yield WaitForSeconds(0.5); _gameManager.SetState(GameManager.GameState.Game); }
Remove unnecessary functions in SockJSConnection
'use strict'; const debug = require('debug')('sockjs:connection'); const stream = require('stream'); const uuid = require('uuid'); class SockJSConnection extends stream.Duplex { constructor(session) { super({ decodeStrings: false, encoding: 'utf8' }); this._session = session; this.id = uuid.v4(); this.headers = {}; this.prefix = this._session.prefix; debug('new connection', this.id, this.prefix); } toString() { return `<SockJSConnection ${this.id}>`; } _write(chunk, encoding, callback) { if (Buffer.isBuffer(chunk)) { chunk = chunk.toString(); } this._session.send(chunk); callback(); } _read() { } end(chunk, encoding, callback) { super.end(chunk, encoding, callback); this.close(); } close(code, reason) { debug('close', code, reason); return this._session.close(code, reason); } get readyState() { return this._session.readyState; } } module.exports = SockJSConnection;
'use strict'; const debug = require('debug')('sockjs:connection'); const stream = require('stream'); const uuid = require('uuid'); class SockJSConnection extends stream.Duplex { constructor(_session) { super({ decodeStrings: false, encoding: 'utf8' }); this._session = _session; this.id = uuid.v4(); this.headers = {}; this.prefix = this._session.prefix; debug('new connection', this.id, this.prefix); } toString() { return `<SockJSConnection ${this.id}>`; } _write(chunk, encoding, callback) { if (Buffer.isBuffer(chunk)) { chunk = chunk.toString(); } this._session.send(chunk); callback(); } _read() { } end(string) { if (string) { this.write(string); } this.close(); return null; } close(code, reason) { debug('close', code, reason); return this._session.close(code, reason); } destroy() { this.end(); this.removeAllListeners(); } destroySoon() { this.destroy(); } get readyState() { return this._session.readyState; } } module.exports = SockJSConnection;
Remove phone number from email body
<?php // Check for empty fields if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['message']) || !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)) { echo "No arguments Provided!"; return false; } $name = $_POST['name']; $email_address = $_POST['email']; $message = $_POST['message']; // Create the email and send the message $to = 'hello@zing.org.uk'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to. $email_subject = "Website Contact Form: $name"; $email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nMessage:\n$message"; $headers = "From: noreply@zing.org.uk\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com. $headers .= "Reply-To: $email_address"; mail($to,$email_subject,$email_body,$headers); return true; ?>
<?php // Check for empty fields if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['message']) || !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)) { echo "No arguments Provided!"; return false; } $name = $_POST['name']; $email_address = $_POST['email']; $phone = $_POST['phone']; $message = $_POST['message']; // Create the email and send the message $to = 'hello@zing.org.uk'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to. $email_subject = "Website Contact Form: $name"; $email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message"; $headers = "From: noreply@zing.org.uk\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com. $headers .= "Reply-To: $email_address"; mail($to,$email_subject,$email_body,$headers); return true; ?>
Fix build break with Fixtures 1.3 Our explicit call to cleanUp messes things up in latest fixture, so we need to call _clear_cleanups to stop the test from breaking Change-Id: I8ce2309a94736b47fb347f37ab4027857e19c8a8
# Copyright 2014 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslotest import base from oslotest import moxstubout class TestMoxStubout(base.BaseTestCase): def _stubable(self): pass def test_basic_stubout(self): f = self.useFixture(moxstubout.MoxStubout()) before = TestMoxStubout._stubable f.mox.StubOutWithMock(TestMoxStubout, '_stubable') after = TestMoxStubout._stubable self.assertNotEqual(before, after) f.cleanUp() after2 = TestMoxStubout._stubable self.assertEqual(before, after2) f._clear_cleanups()
# Copyright 2014 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslotest import base from oslotest import moxstubout class TestMoxStubout(base.BaseTestCase): def _stubable(self): pass def test_basic_stubout(self): f = self.useFixture(moxstubout.MoxStubout()) before = TestMoxStubout._stubable f.mox.StubOutWithMock(TestMoxStubout, '_stubable') after = TestMoxStubout._stubable self.assertNotEqual(before, after) f.cleanUp() after2 = TestMoxStubout._stubable self.assertEqual(before, after2)
Update ZeroClipboard to the newest version available at CDN @XhmikosR, No 1.3.4 yet. I guess next time we'll update to 2.x.
'use strict'; angular.module('osscdnApp', ['ngAnimate', 'ui.router', 'ngDropdowns', 'semverSort', 'ngClipboard', 'angular-flash.service', 'angular-flash.flash-alert-directive']) .config(function($stateProvider, $urlRouterProvider, flashProvider, ngClipProvider) { $urlRouterProvider.otherwise('/'); $stateProvider.state('libraries', { url: '/:name', templateUrl: 'views/main.html', controller: 'MainCtrl' }); ngClipProvider.setPath('//oss.maxcdn.com/zeroclipboard/1.3.3/ZeroClipboard.swf'); flashProvider.successClassnames.push('alert-success'); });
'use strict'; angular.module('osscdnApp', ['ngAnimate', 'ui.router', 'ngDropdowns', 'semverSort', 'ngClipboard', 'angular-flash.service', 'angular-flash.flash-alert-directive']) .config(function($stateProvider, $urlRouterProvider, flashProvider, ngClipProvider) { $urlRouterProvider.otherwise('/'); $stateProvider.state('libraries', { url: '/:name', templateUrl: 'views/main.html', controller: 'MainCtrl' }); ngClipProvider.setPath('//oss.maxcdn.com/libs/zeroclipboard/1.3.1/ZeroClipboard.swf'); flashProvider.successClassnames.push('alert-success'); });
Include DemoModule in module list for simple Android example.
/* * Copyright (C) 2013 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.dagger.simple; import android.app.Application; import dagger.ObjectGraph; import java.util.Arrays; import java.util.List; public class DemoApplication extends Application { private ObjectGraph graph; @Override public void onCreate() { super.onCreate(); graph = ObjectGraph.create(getModules().toArray()); } protected List<Object> getModules() { return Arrays.asList( new AndroidModule(this), new DemoModule() ); } public void inject(Object object) { graph.inject(object); } }
/* * Copyright (C) 2013 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.dagger.simple; import android.app.Application; import dagger.ObjectGraph; import java.util.Arrays; import java.util.List; public class DemoApplication extends Application { private ObjectGraph graph; @Override public void onCreate() { super.onCreate(); graph = ObjectGraph.create(getModules().toArray()); } protected List<Object> getModules() { return Arrays.<Object>asList( new AndroidModule(this) ); } public void inject(Object object) { graph.inject(object); } }
Fix association model with user and email
'use strict'; var fs = require('fs'); var path = require('path'); var Sequelize = require('sequelize'); var basename = path.basename(module.filename); var env = process.env.NODE_ENV || 'development'; if(env !== 'production') { var config = require(__dirname + '/../config/development.json')[env]; } else{ config = require(__dirname + '/../config/production.json')[env]; } var db = {}; if (config.use_env_variable) { config = {}; config.define = {underscored: true}; var sequelize = new Sequelize(process.env[config.use_env_variable]); } else { config.define = {underscored: true}; var sequelize = new Sequelize(config.database, config.username, config.password, config); } fs .readdirSync(__dirname) .filter(function(file) { return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js'); }) .forEach(function(file) { var model = sequelize['import'](path.join(__dirname, file)); db[model.name] = model; }); Object.keys(db).forEach(function(modelName) { if (db[modelName].associate) { db[modelName].associate(db); } }); db.sequelize = sequelize; db.Sequelize = Sequelize; module.exports = db;
'use strict'; var fs = require('fs'); var path = require('path'); var Sequelize = require('sequelize'); var basename = path.basename(module.filename); var env = process.env.NODE_ENV || 'development'; if(env !== 'production') { var config = require(__dirname + '/../config/development.json')[env]; } else{ config = require(__dirname + '/../config/production.json')[env]; } var db = {}; if (config.use_env_variable) { var sequelize = new Sequelize(process.env[config.use_env_variable]); } else { config.define = {underscored: true}; var sequelize = new Sequelize(config.database, config.username, config.password, config); } fs .readdirSync(__dirname) .filter(function(file) { return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js'); }) .forEach(function(file) { var model = sequelize['import'](path.join(__dirname, file)); db[model.name] = model; }); Object.keys(db).forEach(function(modelName) { if (db[modelName].associate) { db[modelName].associate(db); } }); db.sequelize = sequelize; db.Sequelize = Sequelize; module.exports = db;
Use SHAs for commit_range rather than refs Refs are local and might not always be present in the checkout.
#!/usr/bin/env python3 import os import argparse from github import Github def from_pr(project, repo, pr_number): gh = Github() pr = gh.get_repo(f'{project}/{repo}').get_pull(pr_number) base = pr.base.sha head = pr.base.sha return f'{base}...{head}' def main(): argparser = argparse.ArgumentParser() argparser.add_argument( 'project', default=os.environ['CIRCLE_PROJECT_USERNAME'], nargs='?' ) argparser.add_argument( 'repo', default=os.environ['CIRCLE_PROJECT_REPONAME'], nargs='?' ) argparser.add_argument( '--pr-number', type=int, nargs='?' ) args = argparser.parse_args() if not args.pr_number: pr_number = int(os.environ['CIRCLE_PR_NUMBER']) else: pr_number = args.pr_number print(from_pr(args.project, args.repo, pr_number)) if __name__ == '__main__': main()
#!/usr/bin/env python3 import os import argparse from github import Github def from_pr(project, repo, pr_number): gh = Github() pr = gh.get_repo(f'{project}/{repo}').get_pull(pr_number) base = pr.base.ref head = pr.head.ref return f'origin/{base}...{head}' def main(): argparser = argparse.ArgumentParser() argparser.add_argument( 'project', default=os.environ['CIRCLE_PROJECT_USERNAME'], nargs='?' ) argparser.add_argument( 'repo', default=os.environ['CIRCLE_PROJECT_REPONAME'], nargs='?' ) argparser.add_argument( '--pr-number', type=int, nargs='?' ) args = argparser.parse_args() if not args.pr_number: pr_number = int(os.environ['CIRCLE_PR_NUMBER']) else: pr_number = args.pr_number print(from_pr(args.project, args.repo, pr_number)) if __name__ == '__main__': main()
Add old method for setting val to pin named set_val_old
# Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( # Application name: name="blynkapi", # Version number (initial): version="0.1.6", description="This is a simple blynk HTTP/HTTPS API wrapper.", long_description=long_description, #URL url='https://github.com/xandr2/blynkapi', download_url = 'https://github.com/xandr2/blynkapi/archive/0.1.6.tar.gz', # Application author details: author="Alexandr Borysov", author_email="xandr2@gmail.com", # License license='MIT', keywords=['python', 'blynk', 'HTTP/HTTPS', 'API', 'wrapper'], # Packages packages=["blynkapi"], # Include additional files into the package #include_package_data=True, # # license="LICENSE.txt", # long_description=open("README.txt").read(), # Dependent packages (distributions) #install_requires=[ # "urllib2", #], classifiers = [], )
# Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( # Application name: name="blynkapi", # Version number (initial): version="0.1.5", description="This is a simple blynk HTTP/HTTPS API wrapper.", long_description=long_description, #URL url='https://github.com/xandr2/blynkapi', download_url = 'https://github.com/xandr2/blynkapi/archive/0.1.5.tar.gz', # Application author details: author="Alexandr Borysov", author_email="xandr2@gmail.com", # License license='MIT', keywords=['python', 'blynk', 'HTTP/HTTPS', 'API', 'wrapper'], # Packages packages=["blynkapi"], # Include additional files into the package #include_package_data=True, # # license="LICENSE.txt", # long_description=open("README.txt").read(), # Dependent packages (distributions) #install_requires=[ # "urllib2", #], classifiers = [], )
Update component class to take foundation contract
<?php namespace Xu\Components; use Xu\Contracts\Foundation\Foundation as FoundationContract; /** * Component class. */ abstract class Component { /** * xu instance. * * @var \Xu\Contracts\Foundation\Foundation */ protected $xu; /** * Create a new component instance. * * @param \Xu\Contracts\Foundation\Foundation $xu */ public function __construct( FoundationContract $xu ) { $this->xu = $xu; } /** * Bootstrap the component. * * @codeCoverageIgnore */ public function bootstrap() { } /** * Return the given object. Useful for chaining. * * @param mixed $obj * * @return mixed */ protected function with( $obj ) { return $obj; } }
<?php namespace Xu\Components; use Xu\Foundation\Foundation; /** * Component class. */ abstract class Component { /** * xu instance. * * @var \Xu\Foundation\Xu */ protected $xu; /** * Create a new component instance. * * @param \Xu\Foundation\Foundation $xu */ public function __construct( Foundation $xu ) { $this->xu = $xu; } /** * Bootstrap the component. * * @codeCoverageIgnore */ public function bootstrap() { } /** * Return the given object. Useful for chaining. * * @param mixed $obj * * @return mixed */ protected function with( $obj ) { return $obj; } }
SWITCHYARD-329: Add BPM annotations to mark methods as process action triggers
/* * JBoss, Home of Professional Open Source * Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @author tags. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.switchyard.quickstarts.demos.helpdesk; import org.switchyard.component.bpm.Process; import org.switchyard.component.bpm.task.jbpm.CommandBasedWSHumanTaskHandler; /** * @author David Ward &lt;<a href="mailto:dward@jboss.org">dward@jboss.org</a>&gt; (C) 2011 Red Hat Inc. */ @Process( value=HelpDeskService.class, taskHandlers={CommandBasedWSHumanTaskHandler.class}) public interface HelpDeskServiceProcess {}
/* * JBoss, Home of Professional Open Source * Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @author tags. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.switchyard.quickstarts.demos.helpdesk; import org.switchyard.component.bpm.BPM; import org.switchyard.component.bpm.jbpm.CommandBasedWSHumanTaskHandler; /** * @author David Ward &lt;<a href="mailto:dward@jboss.org">dward@jboss.org</a>&gt; (C) 2011 Red Hat Inc. */ @BPM( processInterface = HelpDeskService.class, taskHandlers = { CommandBasedWSHumanTaskHandler.class } ) public final class HelpDeskServiceProcess {}
Fix socket closed on connection reset bug
var net = require("net"); var express = require("express"); var bodyParser = require("body-parser"); var config = require('./config'); var app; // Create a simple server var server = net.createServer(function (conn) { app = express(); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); conn.on("error", function(err) { console.log("Connection Closed: " + err.stack); exp_server.close(); }); conn.on('end', function() { console.log("Connection Closed Properly"); exp_server.close(); }); // Handle data from client conn.on("data", function(data) { data = JSON.parse(data); conn.write(JSON.stringify({response: "Received Message: " + data.response})) }); // Let's response with a hello message conn.write( JSON.stringify( { response: "Hey there client!" } ) ); app.post('/command', function(req, res) { conn.write(JSON.stringify({response: req.body.command})); res.end("yes"); }); var exp_server = app.listen(config.PORT_APP, function() { console.log("Express started"); }); }); // Listen for connections server.listen(config.PORT_NET, config.ALLOWED_IPS, config.HOST, function () { console.log("Server: Listening"); });
var net = require("net"); var express = require("express"); var bodyParser = require("body-parser"); var config = require('./config'); var app = express(); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); // Create a simple server var server = net.createServer(function (conn) { conn.on("error", function(err) { console.log("Connection Closed: " + err); }); // Handle data from client conn.on("data", function(data) { data = JSON.parse(data); conn.write(JSON.stringify({response: "Received Message: " + data.response})) }); // Let's response with a hello message conn.write( JSON.stringify( { response: "Hey there client!" } ) ); app.post('/command', function(req, res) { conn.write(JSON.stringify({response: req.body.command})); res.end("yes"); }); }); // Listen for connections server.listen(config.PORT_NET, config.ALLOWED_IPS, config.HOST, function () { console.log("Server: Listening"); }); app.listen(config.PORT_APP, function() { console.log("Express started"); });
Move to static file serving from ./public. Add possibility to remove rules.
var express = require('express'); var fs = require('fs'); var parser = require('body-parser'); var app = express(); var jsonParser = parser.json(); var rules = [ { rulename: 'must be 5 characters' }, { rulename: 'must not be used elsewhere' }, { rulename: 'must be really cool' } ]; var rulesSize = rules.length; // Save original size for reset // Static file serving. app.use(express.static(__dirname + '/public')); app.get('/api', function(req, res) { res.json(rules); }); app.post('/api', jsonParser, function(req, res) { console.log(req.body); if(req.body.reset) rules = rules.slice(0, rulesSize); else if(req.body.remove) rules.splice(req.body.remove, 1); else rules.push({ rulename: req.body.newRule }); // Return new rules set res.json(rules); }); // app.get('/:file', function(req, res) { // fs.createReadStream(`${__dirname}/${req.params.file}`).pipe(res) // }); var port = process.env.NODE_PORT || 3100; console.log(`Listening on port ${port}`); app.listen(port);
var express = require('express'); var fs = require('fs'); var parser = require('body-parser'); var app = express(); var jsonParser = parser.json(); var rules = [ { rulename: 'must be 5 characters' }, { rulename: 'must not be used elsewhere' }, { rulename: 'must be really cool' } ]; var rulesSize = rules.length; // Save original size for reset app.get('/api', function(req, res) { res.json(rules); }); app.post('/api', jsonParser, function(req, res) { console.log(req.body); if(req.body.reset) rules = rules.slice(0, rulesSize); else rules.push({ rulename: req.body.newRule }); // Return new rules set res.json(rules); }); app.get('/:file', function(req, res) { fs.createReadStream(`${__dirname}/${req.params.file}`).pipe(res) }); var port = process.env.NODE_PORT || 3100; console.log(`Listening on port ${port}`); app.listen(port);
Update to js-jupyter-services 0.5 for some reconnect fixes that are nice to have
/* * Copyright 2015 IBM Corp. * * 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. */ global.XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest; global.WebSocket = require('ws'); function EclairJS() { // SparkContext handles our Toree connection, so it returns an array of [ToreeKernelPromise, SparkContextClass] var result = require('./SparkContext.js')(); var kernelP = result[0]; return { SparkContext: result[1], SQLContext: require('./sql/SQLContext.js'), sql: { functions: require('./sql/functions.js')(kernelP) }, storage: { StorageLevel: require('./storage/StorageLevel.js')(kernelP) }, StreamingContext: require('./streaming/StreamingContext.js'), streaming: { KafkaUtils: require('./streaming/KafkaUtils.js'), Duration: require('./streaming/Duration.js') } } } module.exports = new EclairJS();
/* * Copyright 2015 IBM Corp. * * 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. */ global.XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest; global.WebSocket = require('ws'); function EclairJS() { // SparkContext handles our Toree connection, so it returns an array of [ToreeKernelPromise, SparkContextClass] var result = require('./SparkContext.js')(); var kernelP = result[0]; return { SparkContext: result[1], SQLContext: require('./sql/SQLContext.js'), sql: { functions: require('./sql/functions.js')(kernelP), }, storage: { StorageLevel: require('./storage/StorageLevel.js')(kernelP) }, StreamingContext: require('./streaming/StreamingContext.js'), streaming: { KafkaUtils: require('./streaming/KafkaUtils.js'), Duration: require('./streaming/Duration.js') } } } module.exports = new EclairJS();
Make sure numpy exists on the cpython side
import pytest from pymetabiosis.module import import_module from pymetabiosis.numpy_convert import \ register_cpy_numpy_to_pypy_builtin_converters register_cpy_numpy_to_pypy_builtin_converters() def test_scalar_converter(): try: numpy = import_module("numpy") except ImportError: pytest.skip("numpy isn't installed on the cpython side") assert numpy.bool_(True) is True assert numpy.bool_(False) is False assert numpy.int8(10) == 10 assert numpy.int16(-10) == -10 assert numpy.int32(2**31-1) == 2**31-1 assert numpy.int64(42) == 42 assert numpy.float16(10.0) == 10.0 assert numpy.float32(-10) == -10.0 assert numpy.float64(42.0) == 42.0 if hasattr(numpy, "float128"): assert numpy.float128(-42.0) == -42.0
from pymetabiosis.module import import_module from pymetabiosis.numpy_convert import \ register_cpy_numpy_to_pypy_builtin_converters register_cpy_numpy_to_pypy_builtin_converters() def test_scalar_converter(): numpy = import_module("numpy") assert numpy.bool_(True) is True assert numpy.bool_(False) is False assert numpy.int8(10) == 10 assert numpy.int16(-10) == -10 assert numpy.int32(2**31-1) == 2**31-1 assert numpy.int64(42) == 42 assert numpy.float16(10.0) == 10.0 assert numpy.float32(-10) == -10.0 assert numpy.float64(42.0) == 42.0 assert numpy.float128(-42.0) == -42.0
Stop sending undefined version to TrackJS
/* eslint-disable import/no-extraneous-dependencies */ import 'babel-polyfill'; import 'jquery-ui/ui/widgets/dialog'; import 'notifyjs-browser'; import '../../common/binary-ui/dropdown'; import Elevio from '../../common/elevio'; import View from './View'; $.ajaxSetup({ cache: false, }); // eslint-disable-next-line no-underscore-dangle window._trackJs = { token : '346262e7ffef497d85874322fff3bbf8', application: 'binary-bot', enabled : window.location.hostname !== 'localhost', console : { display: false, }, }; // Should stay below the window._trackJs config require('trackjs'); const view = new View(); view.initPromise.then(() => { $('.show-on-load').show(); $('.barspinner').hide(); window.dispatchEvent(new Event('resize')); Elevio.init(); trackJs.configure({ userId: $('.account-id') .first() .text(), }); });
/* eslint-disable import/no-extraneous-dependencies */ import 'babel-polyfill'; import 'jquery-ui/ui/widgets/dialog'; import 'notifyjs-browser'; import '../../common/binary-ui/dropdown'; import Elevio from '../../common/elevio'; import View from './View'; import { version } from '../../../package.json'; $.ajaxSetup({ cache: false, }); // eslint-disable-next-line no-underscore-dangle window._trackJs = { token : '346262e7ffef497d85874322fff3bbf8', application: 'binary-bot', enabled : window.location.hostname !== 'localhost', console : { display: false, }, }; // Should stay below the window._trackJs config require('trackjs'); const view = new View(); view.initPromise.then(() => { $('.show-on-load').show(); $('.barspinner').hide(); window.dispatchEvent(new Event('resize')); Elevio.init(); trackJs.addMetadata('version', version); trackJs.configure({ userId: $('.account-id') .first() .text(), }); });
Fix issue with "readonly" table - Using getSelect() was leading to an issue against current ZF2 master whereby the table was being marked as readonly; this meant that later calling from() led to an exception. This patch fixes that issue by pulling the select() from a Sql object and then calling setTable().
<?php namespace ScnSocialAuth\Mapper; use ZfcBase\Mapper\AbstractDbMapper; use Zend\Stdlib\Hydrator\HydratorInterface; class UserProvider extends AbstractDbMapper implements UserProviderInterface { protected $tableName = 'user_provider'; public function findUserByProviderId($providerId, $provider) { $sql = $this->getSql(); $select = $sql->select(); $select->from($this->tableName) ->where(array( 'provider_id' => $providerId, 'provider' => $provider, )); $entity = $this->select($select)->current(); $this->getEventManager()->trigger('find', $this, array('entity' => $entity)); return $entity; } public function insert($entity, $tableName = null, HydratorInterface $hydrator = null) { return parent::insert($entity, $tableName, $hydrator); } }
<?php namespace ScnSocialAuth\Mapper; use ZfcBase\Mapper\AbstractDbMapper; use Zend\Stdlib\Hydrator\HydratorInterface; class UserProvider extends AbstractDbMapper implements UserProviderInterface { protected $tableName = 'user_provider'; public function findUserByProviderId($providerId, $provider) { $select = $this ->getSelect() ->from($this->tableName) ->where( array( 'provider_id' => $providerId, 'provider' => $provider, ) ); $entity = $this->select($select)->current(); $this->getEventManager()->trigger('find', $this, array('entity' => $entity)); return $entity; } public function insert($entity, $tableName = null, HydratorInterface $hydrator = null) { return parent::insert($entity, $tableName, $hydrator); } }
Fix bug in gather-metadata-plot script
"""Plot metadata info {{header}} """ from subprocess import run import numpy as np import seaborn as sns from matplotlib import pyplot as plt from msmbuilder.io import load_meta, render_meta sns.set_style('ticks') colors = sns.color_palette() ## Load meta = load_meta() ## Plot logic def plot_lengths(ax): lengths_ns = meta['nframes'] * (meta['step_ps'] / 1000) ax.hist(lengths_ns) ax.set_xlabel("Lenths / ns", fontsize=16) ax.set_ylabel("Count", fontsize=16) total_label = ("Total length: {us:.2e}" .format(us=np.sum(lengths_ns) / 1000)) total_label += r" / $\mathrm{\mu s}$" ax.annotate(total_label, xy=(0.05, 0.95), xycoords='axes fraction', fontsize=18, va='top', ) ## Plot fig, ax = plt.subplots(figsize=(7, 5)) plot_lengths(ax) fig.tight_layout() fig.savefig("lengths.pdf") run(['xdg-open', 'lengths.pdf']) ## Save metadata as html table render_meta(meta, 'meta.pandas.html')
"""Plot metadata info {{header}} """ from subprocess import run import numpy as np import seaborn as sns from matplotlib import pyplot as plt from msmbuilder.io import load_meta, render_meta sns.set_style('ticks') colors = sns.color_palette() ## Load meta = load_meta() ## Plot logic def plot_lengths(ax): lengths_ns = meta['nframes'] / meta['step_ps'] / 1000 ax.hist(lengths_ns) ax.set_xlabel("Lenths / ns", fontsize=16) ax.set_ylabel("Count", fontsize=16) total_label = ("Total length: {us:.2e}" .format(us=np.sum(lengths_ns) / 1000)) total_label += r" / $\mathrm{\mu s}$" ax.annotate(total_label, xy=(0.05, 0.95), xycoords='axes fraction', fontsize=18, va='top', ) ## Plot fig, ax = plt.subplots(figsize=(7, 5)) plot_lengths(ax) fig.tight_layout() fig.savefig("lengths.pdf") run(['xdg-open', 'lengths.pdf']) ## Save metadata as html table render_meta(meta, 'meta.pandas.html')
Add Server header to identify Lapitar
package server import ( "flag" "github.com/zenazn/goji" "github.com/zenazn/goji/web" "github.com/zenazn/goji/web/middleware" "net/http" ) var ( defaults *config //decoder = schema.NewDecoder() ) func start(conf *config) { defaults = conf flag.Set("bind", conf.Address) // Uh, I guess that's a bit strange if conf.Proxy { goji.Insert(middleware.RealIP, middleware.Logger) } goji.Use(serveLapitar) register("/skin/:player", serveSkin) register("/head/:player", serveHeadNormal) register("/head/:size/:player", serveHeadWithSize) register("/face/:player", serveFaceNormal) register("/face/:size/:player", serveFaceWithSize) goji.Get("/*", http.FileServer(http.Dir("www"))) // TODO: How to find the correct dir? goji.Serve() } func register(pattern string, handler interface{}) { goji.Get(pattern+".png", handler) goji.Get(pattern, handler) } func serveLapitar(c *web.C, h http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Server", "Lapitar") // TODO: Version h.ServeHTTP(w, r) } return http.HandlerFunc(fn) }
package server import ( "flag" "github.com/zenazn/goji" "github.com/zenazn/goji/web/middleware" "net/http" ) var ( defaults *config //decoder = schema.NewDecoder() ) func start(conf *config) { defaults = conf flag.Set("bind", conf.Address) // Uh, I guess that's a bit strange if conf.Proxy { goji.Insert(middleware.RealIP, middleware.Logger) } register("/skin/:player", serveSkin) register("/head/:player", serveHeadNormal) register("/head/:size/:player", serveHeadWithSize) register("/face/:player", serveFaceNormal) register("/face/:size/:player", serveFaceWithSize) goji.Get("/*", http.FileServer(http.Dir("www"))) // TODO: How to find the correct dir? goji.Serve() } func register(pattern string, handler interface{}) { goji.Get(pattern+".png", handler) goji.Get(pattern, handler) }
Add method definition generator and some sample for test
import os import json import sys from pprint import pprint def loadJSON(fInput): with open(fInput) as f: return json.load(f) return None if __name__ == '__main__': filePath = 'data/example.json' data = loadJSON(filePath) # check if the data is loaded correctly if data is None: sys.exit('wrong json file'); name = data.get('name') lstTypes = data.get('types') lstFuncs = data.get('functions') ''' from dsFileBuilder import DSFileBuilder dsb = DSFileBuilder(name, lstTypes) dsb.buildDS() dicNumpyDS = dsb.getGeneratedNumpyDS() from kernelFuncBuilder import KernelFuncBuilder kfb = KernelFuncBuilder(name, lstFuncs) kfb.buildKF() dicKFuncDS = kfb.getGeneratedKFuncDS() from oclPyObjGenerator import OCLPyObjGenerator opg = OCLPyObjGenerator(name, dicNumpyDS, dicKFuncDS) opg.generateOCLPyObj() pass '''
import os import json import sys from pprint import pprint def loadJSON(fInput): with open(fInput) as f: return json.load(f) return None if __name__ == '__main__': filePath = 'data/example.json' data = loadJSON(filePath) # check if the data is loaded correctly if data is None: sys.exit('wrong json file'); name = data.get('name') lstTypes = data.get('types') lstFuncs = data.get('functions') from dsFileBuilder import DSFileBuilder dsb = DSFileBuilder(name, lstTypes) dsb.buildDS() dicNumpyDS = dsb.getGeneratedNumpyDS() from kernelFuncBuilder import KernelFuncBuilder kfb = KernelFuncBuilder(name, lstFuncs) kfb.buildKF() dicKFuncDS = kfb.getGeneratedKFuncDS() from oclPyObjGenerator import OCLPyObjGenerator opg = OCLPyObjGenerator(name, dicNumpyDS, dicKFuncDS) opg.generateOCLPyObj() pass
Fix for Python 3.4 html module not containing _escape_map_full
# -*- coding: utf-8 -*- import re from html.entities import codepoint2name try: from html import _escape_map_full except: # taken from the 3.3 standard lib, as it's removed in 3.4 _escape_map_full = {ord('&'): '&amp;', ord('<'): '&lt;', ord('>'): '&gt;', ord('"'): '&quot;', ord('\''): '&#x27;'} html_entities = {_ord: '&{0};'.format(value) for _ord, value in codepoint2name.items()} html_entities.update(_escape_map_full) entities_html = {value: _ord for _ord, value in html_entities.items()} def encode(string): """Encodes html entities. This is a little more full featured than html.escape, as it will replace all charactes from codepoint2name. Returns: string with replaced html entities. """ return string.translate(html_entities) def decode(string): """Decodes html entities. Returns: string with html entities decoded. """ return ( re.sub( '&(?:[#a-z][a-z0-9]+);', lambda m: chr(entities_html[m.group()]), string) )
# -*- coding: utf-8 -*- import re from html import _escape_map_full from html.entities import codepoint2name html_entities = {_ord: '&{0};'.format(value) for _ord, value in codepoint2name.items()} html_entities.update(_escape_map_full) entities_html = {value: _ord for _ord, value in html_entities.items()} def encode(string): """Encodes html entities. This is a little more full featured than html.escape, as it will replace all charactes from codepoint2name. Returns: string with replaced html entities. """ return string.translate(html_entities) def decode(string): """Decodes html entities. Returns: string with html entities decoded. """ return ( re.sub( '&(?:[#a-z][a-z0-9]+);', lambda m: chr(entities_html[m.group()]), string) )
Fix Doctrine Migrations commands to work with new bundles.
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien.potencier@symfony-project.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bundle\DoctrineMigrationsBundle\Command; use Symfony\Bundle\FrameworkBundle\Console\Application; use Symfony\Bundle\DoctrineBundle\Command\DoctrineCommand as BaseCommand; use Doctrine\DBAL\Migrations\Configuration\Configuration; use Doctrine\Common\Util\Inflector; /** * Base class for Doctrine console commands to extend from. * * @author Fabien Potencier <fabien.potencier@symfony-project.com> */ abstract class DoctrineCommand extends BaseCommand { public static function configureMigrationsForBundle(Application $application, $bundle, Configuration $configuration) { $bundle = $application->getKernel()->getBundle($bundle); $dir = $bundle->getPath().'/DoctrineMigrations'; $configuration->setMigrationsNamespace($bundle->getNamespace().'\DoctrineMigrations'); $configuration->setMigrationsDirectory($dir); $configuration->registerMigrationsFromDirectory($dir); $configuration->setName($bundle->getName().' Migrations'); $configuration->setMigrationsTableName(Inflector::tableize($bundle->getName()).'_migration_versions'); } }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien.potencier@symfony-project.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bundle\DoctrineMigrationsBundle\Command; use Symfony\Bundle\FrameworkBundle\Console\Application; use Symfony\Bundle\DoctrineBundle\Command\DoctrineCommand as BaseCommand; use Doctrine\DBAL\Migrations\Configuration\Configuration; use Doctrine\Common\Util\Inflector; /** * Base class for Doctrine console commands to extend from. * * @author Fabien Potencier <fabien.potencier@symfony-project.com> */ abstract class DoctrineCommand extends BaseCommand { public static function configureMigrationsForBundle(Application $application, $bundle, Configuration $configuration) { $configuration->setMigrationsNamespace($bundle.'\DoctrineMigrations'); $bundle = $application->getKernel()->getBundle($bundle); $dir = $bundle->getPath().'/DoctrineMigrations'; $configuration->setMigrationsDirectory($dir); $configuration->registerMigrationsFromDirectory($dir); $configuration->setName($bundle->getName().' Migrations'); $configuration->setMigrationsTableName(Inflector::tableize($bundle->getName()).'_migration_versions'); } }
Add new field to factory
# MIT License # Copyright (c) 2017 MassChallenge, Inc. from __future__ import unicode_literals import swapper from factory import ( DjangoModelFactory, Sequence, ) from accelerator.apps import AcceleratorConfig ProgramFamily = swapper.load_model(AcceleratorConfig.name, 'ProgramFamily') class ProgramFamilyFactory(DjangoModelFactory): class Meta: model = ProgramFamily name = Sequence(lambda n: "Program Family {0}".format(n)) short_description = 'A program family for testing' url_slug = Sequence(lambda n: "pf{0}".format(n)) email_domain = Sequence(lambda n: "pf{0}.accelerator.org".format(n)) phone_number = "617-555-1212" physical_address = "Boston" is_open_for_startups = True is_open_for_experts = True use_site_tree_side_nav = False
# MIT License # Copyright (c) 2017 MassChallenge, Inc. from __future__ import unicode_literals import swapper from factory import ( DjangoModelFactory, Sequence, ) from accelerator.apps import AcceleratorConfig ProgramFamily = swapper.load_model(AcceleratorConfig.name, 'ProgramFamily') class ProgramFamilyFactory(DjangoModelFactory): class Meta: model = ProgramFamily name = Sequence(lambda n: "Program Family {0}".format(n)) short_description = 'A program family for testing' url_slug = Sequence(lambda n: "pf{0}".format(n)) email_domain = Sequence(lambda n: "pf{0}.accelerator.org".format(n)) phone_number = "617-555-1212" physical_address = "Boston" is_open_for_startups = True is_open_for_experts = True
Correct ValidateInput's use of BadRequestHttpException
<?php namespace Fuzz\ApiServer\Validation; use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; trait ValidatesInput { /** * Validate the given request with the given rules. * * @param array $input * @param array $rules * @param array $messages * @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException */ public function validate(array $input, array $rules, array $messages = []) { $validator = $this->getValidationFactory()->make($input, $rules, $messages); if ($validator->fails()) { throw new BadRequestHttpException('Request validation failed, see supporting documentation for information on properly formatting the request.'); } } /** * Get a validation factory instance. * * @return \Illuminate\Contracts\Validation\Factory */ protected function getValidationFactory() { return app('Illuminate\Contracts\Validation\Factory'); } }
<?php namespace Fuzz\ApiServer\Validation; use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; trait ValidatesInput { /** * Validate the given request with the given rules. * * @param array $input * @param array $rules * @param array $messages * @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException */ public function validate(array $input, array $rules, array $messages = []) { $validator = $this->getValidationFactory()->make($input, $rules, $messages); if ($validator->fails()) { throw new BadRequestHttpException('Request validation failed.', $validator->errors()->getMessages()); } } /** * Get a validation factory instance. * * @return \Illuminate\Contracts\Validation\Factory */ protected function getValidationFactory() { return app('Illuminate\Contracts\Validation\Factory'); } }
Fix default get_user_home with dynamic dashboards The existing get_user_home implementation expects both the 'admin' and 'project' dashboards to exist and throws an exception if they are missing. With the inclusion of configurable dashboard loading, we can no longer count on certain dashboards being loaded. Closes-Bug: #1293727 Change-Id: I4ee0b7b313f4e1b27c0daea829c8b38282fa78d9
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from django import shortcuts from django.views.decorators import vary import horizon from horizon import base from openstack_auth import views def get_user_home(user): dashboard = None if user.is_superuser: try: dashboard = horizon.get_dashboard('admin') except base.NotRegistered: pass if dashboard is None: dashboard = horizon.get_default_dashboard() return dashboard.get_absolute_url() @vary.vary_on_cookie def splash(request): if request.user.is_authenticated(): return shortcuts.redirect(horizon.get_user_home(request.user)) form = views.Login(request) request.session.clear() request.session.set_test_cookie() return shortcuts.render(request, 'splash.html', {'form': form})
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from django import shortcuts from django.views.decorators import vary import horizon from openstack_auth import views def get_user_home(user): if user.is_superuser: return horizon.get_dashboard('admin').get_absolute_url() return horizon.get_dashboard('project').get_absolute_url() @vary.vary_on_cookie def splash(request): if request.user.is_authenticated(): return shortcuts.redirect(horizon.get_user_home(request.user)) form = views.Login(request) request.session.clear() request.session.set_test_cookie() return shortcuts.render(request, 'splash.html', {'form': form})
Reset Neon version to 0.1.0
''' Copyright 2015 University of Auckland Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' from PySide import QtCore VERSION_MAJOR = 0 VERSION_MINOR = 1 VERSION_PATCH = 0 VERSION_STRING = str(VERSION_MAJOR) + "." + str(VERSION_MINOR) + "." + str(VERSION_PATCH) APPLICATION_NAME = 'Neon' ORGANISATION_NAME = 'OpenCMISS' ORGANISATION_DOMAIN = 'opencmiss.org' def setApplicationSettings(app): app.setOrganizationDomain(ORGANISATION_DOMAIN) app.setOrganizationName(ORGANISATION_NAME) app.setApplicationName(APPLICATION_NAME) app.setApplicationVersion(VERSION_STRING) QtCore.QSettings.setDefaultFormat(QtCore.QSettings.IniFormat)
''' Copyright 2015 University of Auckland Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' from PySide import QtCore VERSION_MAJOR = 3 VERSION_MINOR = 9 VERSION_PATCH = 0 VERSION_STRING = str(VERSION_MAJOR) + "." + str(VERSION_MINOR) + "." + str(VERSION_PATCH) APPLICATION_NAME = 'Neon' ORGANISATION_NAME = 'OpenCMISS' ORGANISATION_DOMAIN = 'opencmiss.org' def setApplicationSettings(app): app.setOrganizationDomain(ORGANISATION_DOMAIN) app.setOrganizationName(ORGANISATION_NAME) app.setApplicationName(APPLICATION_NAME) app.setApplicationVersion(VERSION_STRING) QtCore.QSettings.setDefaultFormat(QtCore.QSettings.IniFormat)
Add check for valid type of tracks
import time from mycroft.messagebus.message import Message class AudioService(): def __init__(self, emitter): self.emitter = emitter self.emitter.on('MycroftAudioServiceTrackInfoReply', self._track_info) self.info = None def _track_info(self, message=None): self.info = message.data def play(self, tracks=[], utterance=''): if isinstance(tracks, basestring): tracks = [tracks] elif not isinstance(tracks, list): raise ValueError self.emitter.emit(Message('MycroftAudioServicePlay', data={'tracks': tracks, 'utterance': utterance})) def track_info(self): self.info = None self.emitter.emit(Message('MycroftAudioServiceTrackInfo')) while self.info is None: time.sleep(0.1) return self.info
import time from mycroft.messagebus.message import Message class AudioService(): def __init__(self, emitter): self.emitter = emitter self.emitter.on('MycroftAudioServiceTrackInfoReply', self._track_info) self.info = None def _track_info(self, message=None): self.info = message.data def play(self, tracks=[], utterance=''): self.emitter.emit(Message('MycroftAudioServicePlay', data={'tracks': tracks, 'utterance': utterance})) def track_info(self): self.info = None self.emitter.emit(Message('MycroftAudioServiceTrackInfo')) while self.info is None: time.sleep(0.1) return self.info
Add no-defined users to the 'default' group
package markehme.FactionsPerms.listeners; import java.io.IOException; import java.util.Arrays; import java.util.logging.Level; import markehme.FactionsPerms.FactionsPerms; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerLoginEvent; import org.bukkit.event.player.PlayerLoginEvent.Result; public class ReadyCheck implements Listener { /** * Checks if FactionsPerms is ready * @param event */ @EventHandler(priority = EventPriority.HIGH) public void onLogin(PlayerLoginEvent event) { if(!FactionsPerms.isReady) { event.disallow(Result.KICK_OTHER, "Server is still starting up.. please try again."); return; } if(!FactionsPerms.userSet.containsKey(event.getPlayer().getName().toLowerCase())) { FactionsPerms.get().getLogger().log(Level.INFO, "Adding " + event.getPlayer().getName() + " to default group"); FactionsPerms.usersConfig.set("Users." + event.getPlayer().getName() + ".groups", Arrays.asList("default")); FactionsPerms.usersConfig.set("Users." + event.getPlayer().getName() + ".permissions", Arrays.asList("")); FactionsPerms.loadUser(event.getPlayer().getName()); try { FactionsPerms.usersConfig.save(FactionsPerms.usersConfigFile); } catch (IOException e) { e.printStackTrace(); } } } }
package markehme.FactionsPerms.listeners; import markehme.FactionsPerms.FactionsPerms; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerLoginEvent; import org.bukkit.event.player.PlayerLoginEvent.Result; public class ReadyCheck implements Listener { /** * Checks if FactionsPerms is ready * @param event */ @EventHandler(priority = EventPriority.HIGH) public void onLogin(PlayerLoginEvent event) { if(!FactionsPerms.isReady) { event.disallow(Result.KICK_OTHER, "Server is still starting up.. please try again."); return; } if(!FactionsPerms.userSet.containsKey(event.getPlayer().getName().toLowerCase())) { } } }
Change the vertical position to work correctly in standards mode.
"use strict"; function createDialog(pageMantle, dialogHtml, dialogCss) { var dialog = {}; // write dialog HTML to document var dialogDiv = jQuery('<div title="Create a feed"></div>'); dialogDiv.appendTo(document.body); // create iframe var iframe = jQuery('<iframe frameborder="0" style="width:100%; height:100%;">'); iframe.appendTo(dialogDiv); iframe.load(function() { var dialogDocument = iframe[0].contentWindow.document; // document.write() has the advantage to actually use the doctype from the given string. dialogDocument.write(dialogHtml); dialogDocument.close(); // write dialog content CSS to dialog var dialogCssElement = jQuery('<style type="text/css">' + dialogCss + '</style>'); dialogCssElement.appendTo(dialogDocument.head); var dialogContent = createDialogContent(dialogDocument, pageMantle); var keepPositionFixed = function(event) { $(event.target).parent().css('position', 'fixed'); }; $(dialogDiv).dialog({ dialogClass : 'ftc_dialogDiv', position : ['center', 'bottom'], // FIXME in quirks mode the vertical position is unpredictable and sometimes even invisible width : 750, height : 270, create : keepPositionFixed, resize : keepPositionFixed, close : pageMantle.destroy }); }); return dialog; }
"use strict"; function createDialog(pageMantle, dialogHtml, dialogCss) { var dialog = {}; // write dialog HTML to document var dialogDiv = jQuery('<div title="Create a feed"></div>'); dialogDiv.appendTo(document.body); // create iframe var iframe = jQuery('<iframe frameborder="0" style="width:100%; height:100%;">'); iframe.appendTo(dialogDiv); iframe.load(function() { var dialogDocument = iframe[0].contentWindow.document; dialogDocument.write(dialogHtml); // document.write() has the advantage to actually use the doctype from the given string. dialogDocument.close(); // write dialog content CSS to dialog var dialogCssElement = jQuery('<style type="text/css">' + dialogCss + '</style>'); dialogCssElement.appendTo(dialogDocument.head); var dialogContent = createDialogContent(dialogDocument, pageMantle); var keepPositionFixed = function(event) { $(event.target).parent().css('position', 'fixed'); }; $(dialogDiv).dialog({ dialogClass : 'ftc_dialogDiv', /*TODO fix the vertical position. This seems especially difficult for pages without html5 doctype. position : ['center', 'bottom'], //this works with the html5 doctype, but not in quirks mode */ width : 750, height : 270, create : keepPositionFixed, resize : keepPositionFixed, close : pageMantle.destroy }); }); return dialog; }
Add getSRID() method to geometry
<?php /** * Copyright (C) 2016 Derek J. Lambert * * 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. */ namespace CrEOF\Geo\Obj; /** * Abstract class Geometry * * @author Derek J. Lambert <dlambert@dereklambert.com> * @license http://dlambert.mit-license.org MIT */ abstract class Geometry extends Object implements GeometryInterface { /** * @return array */ public function getCoordinates() { return $this->data['value']; } /** * @return null|int */ public function getSRID() { return $this->data['srid']; } }
<?php /** * Copyright (C) 2016 Derek J. Lambert * * 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. */ namespace CrEOF\Geo\Obj; /** * Abstract class Geometry * * @author Derek J. Lambert <dlambert@dereklambert.com> * @license http://dlambert.mit-license.org MIT */ abstract class Geometry extends Object implements GeometryInterface { /** * @return array */ public function getCoordinates() { return $this->data['value']; } }
Fix warning error about missing $title
<?php /* * Hackwork * * Simple, layout-based PHP microframework for making HTML5 sites. * http://git.io/hackwork */ define('ROOT', $_SERVER['DOCUMENT_ROOT']); define('PATH', ROOT); define('ASSETS', '/assets'); define('DATA', PATH . '/data'); define('LAYOUTS', PATH . '/layouts'); // Generate layout // // `$layout` => layout name // `$data` => data file name // `$title` => [optional] page title function layout($layout, $data, $title = '') { foreach (glob(PATH . "/layouts/$layout/*.php") as $item) { if (preg_match('/set.*.php$/', $item)) { require_once($item); } } include_once LAYOUTS . "/$layout/header.php"; include_once DATA . "/$data.php"; include_once LAYOUTS . "/$layout/footer.php"; }
<?php /* * Hackwork * * Simple, layout-based PHP microframework for making HTML5 sites. * http://git.io/hackwork */ define('ROOT', $_SERVER['DOCUMENT_ROOT']); define('PATH', ROOT); define('ASSETS', '/assets'); define('DATA', PATH . '/data'); define('LAYOUTS', PATH . '/layouts'); // Generate layout // // `$layout` => layout name // `$data` => data file name // `$title` => page title function layout($layout, $data, $title) { foreach (glob(PATH . "/layouts/$layout/*.php") as $item) { if (preg_match('/set.*.php$/', $item)) { require_once($item); } } include_once LAYOUTS . "/$layout/header.php"; include_once DATA . "/$data.php"; include_once LAYOUTS . "/$layout/footer.php"; }
Update template away from legacy variation setting Former-commit-id: 79522c8565f4c21c0536f106532295321a0f7b07 Former-commit-id: 8be9e6f171ae33ab163b02dee0d4b5b4449ece03
$(function () { // We move the background image and class from data-stripe-wrapper up to the closest // div containing the special custom template class. Because it's this DIV that should // have the parallax image close to it. var $parallax = $('div[data-stripe-wrapper=parallax]'); $parallax.each(function () { var $self = $(this); $wrapper = $self.closest('div.ccm-block-custom-template-parallax'), $children = $wrapper.children(), $inner = $children.first(); $wrapper.attr('data-stripe', 'parallax').attr('data-background-image', $self.attr('data-background-image')); $inner.addClass('parallax-stripe-inner'); $wrapper.parallaxize({ speed: 0.2 }); }); });
$(function () { // We move the background image and class from data-stripe-wrapper up to the closest // div containing the special custom template class. Because it's this DIV that should // have the parallax image close to it. var $parallax = $('div[data-stripe-wrapper=parallax]'); $parallax.each(function () { var $self = $(this); $wrapper = $self.closest('div.ccm-block-custom-template-parallax'), $children = $wrapper.children(), $inner = $children.first(); $wrapper.attr('data-stripe', 'parallax').attr('data-background-image', $self.attr('data-background-image')); $inner.addClass('parallax-stripe-inner'); $wrapper.parallaxize({ variation: $wrapper.height() }); }); });
Remove test that sporadically gives false negatives Nothing worse than an unreliable test; remove this test as there can be errors in the logs that do not necessarily correspond to a broken image. Relates #119
from .fixtures import elasticsearch import pytest image_flavor = pytest.config.getoption('--image-flavor') def test_elasticsearch_logs_are_in_docker_logs(elasticsearch): elasticsearch.assert_in_docker_log('o.e.n.Node') # eg. elasticsearch1 | [2017-07-04T00:54:22,604][INFO ][o.e.n.Node ] [docker-test-node-1] initializing ... @pytest.mark.skipif(image_flavor != 'platinum', reason="x-pack.security not installed in the -{} image.".format(image_flavor)) def test_security_audit_logs_are_in_docker_logs(elasticsearch): elasticsearch.assert_in_docker_log('x.s.a.l.LoggingAuditTrail') # eg. elasticsearch1 | [2017-07-04T01:10:19,189][INFO ][o.e.x.s.a.l.LoggingAuditTrail] [transport] [access_granted] def test_info_level_logs_are_in_docker_logs(elasticsearch): elasticsearch.assert_in_docker_log('INFO')
from .fixtures import elasticsearch import pytest image_flavor = pytest.config.getoption('--image-flavor') def test_elasticsearch_logs_are_in_docker_logs(elasticsearch): elasticsearch.assert_in_docker_log('o.e.n.Node') # eg. elasticsearch1 | [2017-07-04T00:54:22,604][INFO ][o.e.n.Node ] [docker-test-node-1] initializing ... @pytest.mark.skipif(image_flavor != 'platinum', reason="x-pack.security not installed in the -{} image.".format(image_flavor)) def test_security_audit_logs_are_in_docker_logs(elasticsearch): elasticsearch.assert_in_docker_log('x.s.a.l.LoggingAuditTrail') # eg. elasticsearch1 | [2017-07-04T01:10:19,189][INFO ][o.e.x.s.a.l.LoggingAuditTrail] [transport] [access_granted] def test_info_level_logs_are_in_docker_logs(elasticsearch): elasticsearch.assert_in_docker_log('INFO') def test_no_errors_are_in_docker_logs(elasticsearch): elasticsearch.assert_not_in_docker_log('ERROR')
Implement dynamic username and collection type
from createCollection import createCollection from ObjectFactories.ItemFactory import ItemFactory from DataObjects.Collection import Collection import datetime, json, os.path, argparse CONST_COLLECTIONS_NAME = 'collections' def generateArgumentsFromParser(): parser = parser = argparse.ArgumentParser(description="Runs the PyInventory utility for creating a collection of items.") parser.add_argument('--user', dest='username', required=True) parser.add_argument('--type', dest='collectionName', required=True) return parser.parse_args() def generateItemsCollection(collectionName, username): items = [] now = datetime.datetime.now() for i in range(0,10): item = ItemFactory.factory('item', [i, 'item' + str(i), now, now]) print(item.name) items.append(item) return Collection(collectionName, username, items) def main(): arguments = generateArgumentsFromParser() createCollection(arguments.username, arguments.collectionName) itemCollection = generateItemsCollection(arguments.collectionName, arguments.username) collectionsFilePath = CONST_COLLECTIONS_NAME+'/'+arguments.username+'_'+CONST_COLLECTIONS_NAME+'/'+arguments.username+'_'+arguments.collectionName+'_'+'collection.dat' if os.path.isfile(collectionsFilePath): collectionFile = open(collectionsFilePath, 'w') collectionFile.write(itemCollection.toJSON()) collectionFile.close() if __name__ == '__main__': main()
from createCollection import createCollection from ObjectFactories.ItemFactory import ItemFactory from DataObjects.Collection import Collection import datetime, json, os.path, argparse CONST_COLLECTIONS_NAME = 'collections' def generateArgumentsFromParser(): parser = parser = argparse.ArgumentParser(description="Runs PyTriSearch googling utility.") return parser.parse_args() def generateItemsCollection(collectionName, username): items = [] now = datetime.datetime.now() for i in range(0,10): item = ItemFactory.factory('item', [i, 'item' + str(i), now, now]) print(item.name) items.append(item) return Collection(collectionName, username, items) def main(): arguments = generateArgumentsFromParser() username = 'agarner' collectionName = 'Items' createCollection(username,collectionName) itemCollection = generateItemsCollection(collectionName, username) collectionsFilePath = CONST_COLLECTIONS_NAME+'/'+username+'_'+CONST_COLLECTIONS_NAME+'/'+username+'_'+collectionName+'_'+'collection.dat' if os.path.isfile(collectionsFilePath): collectionFile = open(collectionsFilePath, 'w') collectionFile.write(itemCollection.toJSON()) collectionFile.close() if __name__ == '__main__': main()
Fix permission check on /getrp command
package com.elmakers.mine.bukkit.magic.command; import com.elmakers.mine.bukkit.api.magic.MagicAPI; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.ArrayList; import java.util.Collection; public class RPCommandExecutor extends MagicTabExecutor { public RPCommandExecutor(MagicAPI api) { super(api); } @Override public Collection<String> onTabComplete(CommandSender sender, String commandName, String[] args) { return new ArrayList<>(); } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (!api.hasPermission(sender, "Magic.commands.getrp")) { sendNoPermission(sender); return true; } if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + "This command may only be used in-game"); return true; } api.getController().sendResourcePack((Player)sender); return true; } }
package com.elmakers.mine.bukkit.magic.command; import com.elmakers.mine.bukkit.api.magic.MagicAPI; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.ArrayList; import java.util.Collection; public class RPCommandExecutor extends MagicTabExecutor { public RPCommandExecutor(MagicAPI api) { super(api); } @Override public Collection<String> onTabComplete(CommandSender sender, String commandName, String[] args) { return new ArrayList<>(); } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (!api.hasPermission(sender, "Magic.commands.rp")) { sendNoPermission(sender); return true; } if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + "This command may only be used in-game"); return true; } api.getController().sendResourcePack((Player)sender); return true; } }
Fix to default cron time
import 'babel-polyfill'; import { existsSync } from 'fs'; import { resolve } from 'path'; import merge from 'lodash.merge'; import TipsBot from './Tipsbot'; const tokenPath = resolve(__dirname, '..', '..', 'token.js'); const defaultToken = existsSync(tokenPath) ? require(tokenPath) : ''; const defaultName = 'Tipsbot'; const defaultTips = resolve(__dirname, '..', '..', 'data', 'pragmatic-programmer.json'); const defaultChannel = 'general'; const defaultSchedule = '0 9 * * 1-5'; // 09:00 on monday-friday const defaultStartIndex = 0; const defaultIconURL = ''; export const create = (options = {}) => { let defaults = { token: process.env.BOT_API_KEY || defaultToken, name: process.env.BOT_NAME || defaultName, filePath: process.env.BOT_FILE_PATH || defaultTips, channel: process.env.BOT_CHANNEL || defaultChannel, schedule: process.env.BOT_SCHEDULE || defaultSchedule, startIndex: process.env.BOT_START_INDEX || defaultStartIndex, iconURL: process.env.BOT_ICON_URL || defaultIconURL, }; return new TipsBot(merge(defaults, options)); }
import 'babel-polyfill'; import { existsSync } from 'fs'; import { resolve } from 'path'; import merge from 'lodash.merge'; import TipsBot from './Tipsbot'; const tokenPath = resolve(__dirname, '..', '..', 'token.js'); const defaultToken = existsSync(tokenPath) ? require(tokenPath) : ''; const defaultName = 'Tipsbot'; const defaultTips = resolve(__dirname, '..', '..', 'data', 'pragmatic-programmer.json'); const defaultChannel = 'general'; const defaultSchedule = '0 9 * * 1,2,3,4,5'; // 09:00 on monday-friday const defaultStartIndex = 0; const defaultIconURL = ''; export const create = (options = {}) => { let defaults = { token: process.env.BOT_API_KEY || defaultToken, name: process.env.BOT_NAME || defaultName, filePath: process.env.BOT_FILE_PATH || defaultTips, channel: process.env.BOT_CHANNEL || defaultChannel, schedule: process.env.BOT_SCHEDULE || defaultSchedule, startIndex: process.env.BOT_START_INDEX || defaultStartIndex, iconURL: process.env.BOT_ICON_URL || defaultIconURL, }; return new TipsBot(merge(defaults, options)); }
Add changes for test 4
#!/usr/bin/env node const inquirer = require('inquirer') const Listr = require('listr') const steps = [{ type: 'input', name: 'userName', message: 'Whats your name?' }] const tasks = [{ title: 'Preparing', task: (context, task) => new Promise((resolve, reject) => { setTimeout(() => resolve(), 1000) }) },{ title: 'Ask for name', task: (context, task) => new Promise((resolve, reject) => { task.output = 'Starting' setTimeout(() => { task.output = 'Calculating' resolve() }, 500) // setTimeout(() => { // }, 2000) }) }] // Test change for release // Test change for release // Test change for release const listrObject = new Listr(tasks) listrObject.run().then(res => { inquirer .prompt(steps).then(output => { console.log( 'Hello', output.userName ) }).catch(err => console.log(err)) })
#!/usr/bin/env node const inquirer = require('inquirer') const Listr = require('listr') const steps = [{ type: 'input', name: 'userName', message: 'Whats your name?' }] const tasks = [{ title: 'Preparing', task: (context, task) => new Promise((resolve, reject) => { setTimeout(() => resolve(), 1000) }) },{ title: 'Ask for name', task: (context, task) => new Promise((resolve, reject) => { task.output = 'Starting' setTimeout(() => { task.output = 'Calculating' resolve() }, 500) // setTimeout(() => { // }, 2000) }) }] // Test change for release // Test change for release const listrObject = new Listr(tasks) listrObject.run().then(res => { inquirer .prompt(steps).then(output => { console.log( 'Hello', output.userName ) }).catch(err => console.log(err)) })
Replace double quotes with single quotes as requested
from django.db import models from django_countries.fields import CountryField from model_utils.models import TimeStampedModel from .constants import JOB_COMPENSATION_CHOICES, JOB_HOURS_CHOICES, JOB_TYPE_CHOICES class Job(TimeStampedModel): """ This model contains all the fields related to a job being posted on the job board. """ title = models.CharField(max_length=255) company = models.CharField(max_length=255) type = models.CharField(max_length=255, choices=JOB_TYPE_CHOICES) compensation = models.CharField(max_length=255, choices=JOB_COMPENSATION_CHOICES) hours = models.CharField(max_length=255, choices=JOB_HOURS_CHOICES) city = models.CharField(max_length=255) country = CountryField() description = models.TextField() function = models.TextField(blank=True, null=True) responsibilities = models.TextField(blank=True, null=True) website_link = models.URLField(max_length=255, blank=True, null=True) contact_email = models.EmailField(max_length=255) logo = models.ImageField(upload_to='job-board/uploaded-logos/', blank=True, null=True)
from django.db import models from django_countries.fields import CountryField from model_utils.models import TimeStampedModel from .constants import JOB_COMPENSATION_CHOICES, JOB_HOURS_CHOICES, JOB_TYPE_CHOICES class Job(TimeStampedModel): """ This model contains all the fields related to a job being posted on the job board. """ title = models.CharField(max_length=255) company = models.CharField(max_length=255) type = models.CharField(max_length=255, choices=JOB_TYPE_CHOICES) compensation = models.CharField(max_length=255, choices=JOB_COMPENSATION_CHOICES) hours = models.CharField(max_length=255, choices=JOB_HOURS_CHOICES) city = models.CharField(max_length=255) country = CountryField() description = models.TextField() function = models.TextField(blank=True, null=True) responsibilities = models.TextField(blank=True, null=True) website_link = models.URLField(max_length=255, blank=True, null=True) contact_email = models.EmailField(max_length=255) logo = models.ImageField(upload_to="job-board/uploaded-logos/", blank=True, null=True)
Update min width and display for button.
import styled from 'styled-components'; import { darken, lighten } from 'polished'; import { pickColorFromProps } from '../utils'; import { buttonBackground, buttonColor, } from './Style'; const borderColor = (colorSet) => { return pickColorFromProps(colorSet, (color) => darken(.2, color)); }; const hoverBackgroundColor = (colorSet) => { return pickColorFromProps(colorSet, (color) => lighten(.1, color)); } const Button = styled.button` display: inline-block; min-width: 80px; margin: 2px; padding: 1em 2em; border: 1px solid ${borderColor(buttonBackground)}; background-color: ${pickColorFromProps(buttonBackground)}; color: ${pickColorFromProps(buttonColor)}; border-radius: 2px; outline: none; cursor: pointer; transition: background-color .2s; &:hover { background-color: ${hoverBackgroundColor(buttonBackground)} } `; export default Button;
import styled from 'styled-components'; import { darken, lighten } from 'polished'; import { pickColorFromProps } from '../utils'; import { buttonBackground, buttonColor, } from './Style'; const borderColor = (colorSet) => { return pickColorFromProps(colorSet, (color) => darken(.2, color)); }; const hoverBackgroundColor = (colorSet) => { return pickColorFromProps(colorSet, (color) => lighten(.1, color)); } const Button = styled.button` margin: 2px; padding: 1em 2em; border: 1px solid ${borderColor(buttonBackground)}; background-color: ${pickColorFromProps(buttonBackground)}; color: ${pickColorFromProps(buttonColor)}; border-radius: 2px; outline: none; cursor: pointer; transition: background-color .2s; &:hover { background-color: ${hoverBackgroundColor(buttonBackground)} } `; export default Button;
Add specifications for Bitcoin mainnet and testnet
from collections import namedtuple Network = namedtuple('Network', [ 'network_name', 'network_shortname', 'pubkeyhash', 'wif_prefix', 'scripthash', 'magicbytes' ]) networks = ( # Peercoin mainnet Network("Peercoin", "ppc", b'37', b'b7', b'75', b'e6e8e9e5'), # Peercoin testnet Network("Peercoin-testnet", "tppc", b'6f', b'ef', b'c4', b'cbf2c0ef') # Bitcoin mainnet Network("Bitcoin", "btc", b'00', b'80', b'05', b'd9b4bef9'), # Bitcoin testnet Network("Bitcoin-testnet", "tbtc", b'6f', b'ef', b'c4', b'dab5bffa') ) def query(query): '''find matching parameter among the networks''' for network in networks: for field in network: if field == query: return network
from collections import namedtuple Network = namedtuple('Network', [ 'network_name', 'network_shortname', 'pubkeyhash', 'wif_prefix', 'scripthash', 'magicbytes' ]) networks = ( # Peercoin mainnet Network("Peercoin", "ppc", b'37', b'b7', b'75', b'e6e8e9e5'), # Peercoin testnet Network("Peercoin-testnet", "tppc", b'6f', b'ef', b'c4', b'cbf2c0ef') ) def query(query): '''find matching parameter among the networks''' for network in networks: for field in network: if field == query: return network
Use sort_keys=True for the ConsoleWritter pretty printing
import json from exporters.writers.base_writer import BaseWriter, ItemsLimitReached class ConsoleWriter(BaseWriter): """ It is just a writer with testing purposes. It prints every item in console. """ def __init__(self, options): super(ConsoleWriter, self).__init__(options) self.logger.info('ConsoleWriter has been initiated') self.pretty_print = self.options.get('pretty_print', False) def write_batch(self, batch): for item in batch: formatted_item = item.formatted if self.pretty_print: formatted_item = self._format(formatted_item) print formatted_item self._increment_written_items() if self.items_limit and self.items_limit == self.stats['items_count']: raise ItemsLimitReached('Finishing job after items_limit reached: {} items written.'.format(self.stats['items_count'])) self.logger.debug('Wrote items') def _format(self, item): try: return json.dumps(json.loads(item), indent=2, sort_keys=True) except: return item
import json from exporters.writers.base_writer import BaseWriter, ItemsLimitReached class ConsoleWriter(BaseWriter): """ It is just a writer with testing purposes. It prints every item in console. """ def __init__(self, options): super(ConsoleWriter, self).__init__(options) self.logger.info('ConsoleWriter has been initiated') self.pretty_print = self.options.get('pretty_print', False) def write_batch(self, batch): for item in batch: formatted_item = item.formatted if self.pretty_print: formatted_item = self._format(formatted_item) print formatted_item self._increment_written_items() if self.items_limit and self.items_limit == self.stats['items_count']: raise ItemsLimitReached('Finishing job after items_limit reached: {} items written.'.format(self.stats['items_count'])) self.logger.debug('Wrote items') def _format(self, item): try: return json.dumps(json.loads(item), indent=2) except: return item
Fix another doc string mistake.
<?php /** * MiniAsset * Copyright (c) Mark Story (http://mark-story.com) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Mark Story (http://mark-story.com) * @since 1.3.0 * @license http://www.opensource.org/licenses/mit-license.php MIT License */ namespace MiniAsset\Output; use MiniAsset\AssetTarget; /** * Interface for asset compilers to implement. */ interface CompilerInterface { /** * Generate a compiled asset, with all the configured filters applied. * * @param AssetTarget $target The target to build * @return string The processed result of $target and it dependencies. * @throws RuntimeException */ public function generate(AssetTarget $build); }
<?php /** * MiniAsset * Copyright (c) Mark Story (http://mark-story.com) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Mark Story (http://mark-story.com) * @since 1.3.0 * @license http://www.opensource.org/licenses/mit-license.php MIT License */ namespace MiniAsset\Output; use MiniAsset\AssetTarget; /** * Interface for asset compilers to implement. */ interface CompilerInterface { /** * Generate a compiled asset, with all the configured filters applied. * * @param AssetTarget $target The target to build * @return The processed result of $target and it dependencies. * @throws RuntimeException */ public function generate(AssetTarget $build); }
Make the syntax checker happy
'use strict'; var Tracer = require('tracer'); function Logger (options) { this.options = options; this.tracer = this._setupTracer(options.enabled); } Logger.prototype.info = function () { this.tracer.info.apply(this.tracer, arguments); }; Logger.prototype.error = function (message) { this.tracer.error(message); }; Logger.prototype._setupTracer = function (enabled) { var noopTransport = function () {}; var options = {}; options.format = '{{message}}'; if (!enabled) { options.transport = noopTransport; } return Tracer.colorConsole(options); }; function initTheLogger (options) { return new Logger(options); } var logger; exports.logger = function (options) { if (!logger) { logger = initTheLogger(options); } return logger; };
var Tracer = require('tracer'); function Logger (options) { this.options = options; this.tracer = this._setupTracer(options.enabled); } Logger.prototype.info = function () { this.tracer.info.apply(this.tracer, arguments); }; Logger.prototype.error = function (message) { this.tracer.error(message); } Logger.prototype._setupTracer = function (enabled) { var noopTransport = function () {}; var options = {}; options.format = "{{message}}"; if (!enabled) { options.transport = noopTransport; } return Tracer.colorConsole(options); } function initTheLogger (options) { return new Logger(options); } var logger; exports.logger = function (options) { if (!logger) { logger = initTheLogger(options); } return logger; }
Remove reporter from gulp mocha options
const gulp = require('gulp'); const util = require('gulp-util'); const babel = require('gulp-babel'); const mocha = require('gulp-mocha'); const eslint = require('gulp-eslint'); const compiler = require('babel-core/register'); const src = 'src/index.js'; gulp.task('lint', () => gulp.src(src) .pipe(eslint()) .pipe(eslint.format()) ); gulp.task('test', ['lint'], () => ( gulp.src('test') .pipe(mocha({ compilers: { js: compiler, }, })) .on('error', util.log) )); gulp.task('build', ['test'], () => ( gulp.src(src) .pipe(babel()) .pipe(gulp.dest('dist')) )); gulp.task('watch', () => { gulp.watch(src, ['test']); }); gulp.task('develop', ['watch']); gulp.task('default', ['develop']);
const gulp = require('gulp'); const util = require('gulp-util'); const babel = require('gulp-babel'); const mocha = require('gulp-mocha'); const eslint = require('gulp-eslint'); const compiler = require('babel-core/register'); const src = 'src/index.js'; gulp.task('lint', () => gulp.src(src) .pipe(eslint()) .pipe(eslint.format()) ); gulp.task('test', ['lint'], () => ( gulp.src('test') .pipe(mocha({ reporter: 'spec', compilers: { js: compiler, }, })) .on('error', util.log) )); gulp.task('build', ['test'], () => ( gulp.src(src) .pipe(babel()) .pipe(gulp.dest('dist')) )); gulp.task('watch', () => { gulp.watch(src, ['test']); }); gulp.task('develop', ['watch']); gulp.task('default', ['develop']);
Use 'Animated.View.propTypes' to avoid warnings. The propTypes Validation must be based on `Animated.View.propTypes` instead of just `View.propTypes` otherwise a Warning is displayed when passing Animated values to TabBar.
'use strict'; import React, { Animated, Platform, StyleSheet, View, } from 'react-native'; import Layout from './Layout'; export default class TabBar extends React.Component { static propTypes = { ...Animated.View.propTypes, shadowStyle: View.propTypes.style, }; render() { return ( <Animated.View {...this.props} style={[styles.container, this.props.style]}> {this.props.children} <View style={[styles.shadow, this.props.shadowStyle]} /> </Animated.View> ); } } let styles = StyleSheet.create({ container: { backgroundColor: '#f8f8f8', flexDirection: 'row', justifyContent: 'space-around', height: Layout.tabBarHeight, position: 'absolute', bottom: 0, left: 0, right: 0, }, shadow: { backgroundColor: 'rgba(0, 0, 0, 0.25)', height: Layout.pixel, position: 'absolute', left: 0, right: 0, top: Platform.OS === 'android' ? 0 : -Layout.pixel, }, });
'use strict'; import React, { Animated, Platform, StyleSheet, View, } from 'react-native'; import Layout from './Layout'; export default class TabBar extends React.Component { static propTypes = { ...View.propTypes, shadowStyle: View.propTypes.style, }; render() { return ( <Animated.View {...this.props} style={[styles.container, this.props.style]}> {this.props.children} <View style={[styles.shadow, this.props.shadowStyle]} /> </Animated.View> ); } } let styles = StyleSheet.create({ container: { backgroundColor: '#f8f8f8', flexDirection: 'row', justifyContent: 'space-around', height: Layout.tabBarHeight, position: 'absolute', bottom: 0, left: 0, right: 0, }, shadow: { backgroundColor: 'rgba(0, 0, 0, 0.25)', height: Layout.pixel, position: 'absolute', left: 0, right: 0, top: Platform.OS === 'android' ? 0 : -Layout.pixel, }, });
TASK: Add newline at the end of the file
<?php namespace TYPO3\Flow\Tests\Unit\Cryptography\Fixture; /* * This file is part of the TYPO3.Flow package. * * (c) Contributors of the Neos Project - www.neos.io * * This package is Open Source Software. For the full copyright and license * information, please view the LICENSE file which was distributed with this * source code. */ use TYPO3\Flow\Security\Cryptography\PasswordHashingStrategyInterface; class TestHashingStrategy implements PasswordHashingStrategyInterface { /** * @param string $password Cleartext password that will be hashed * @param string $staticSalt Optional static salt that will not be stored in the hashed password * @return string The hashed password with dynamic salt (if used) */ public function hashPassword($password, $staticSalt = null) { return 'hashed' . $password . $staticSalt; } /** * @param string $password * @param string $hashedPasswordAndSalt Hashed password with dynamic salt (if used) * @param string $staticSalt Optional static salt that will not be stored in the hashed password * @return boolean TRUE if the given cleartext password matched the hashed password */ public function validatePassword($password, $hashedPasswordAndSalt, $staticSalt = null) { return false; } }
<?php namespace TYPO3\Flow\Tests\Unit\Cryptography\Fixture; /* * This file is part of the TYPO3.Flow package. * * (c) Contributors of the Neos Project - www.neos.io * * This package is Open Source Software. For the full copyright and license * information, please view the LICENSE file which was distributed with this * source code. */ use TYPO3\Flow\Security\Cryptography\PasswordHashingStrategyInterface; class TestHashingStrategy implements PasswordHashingStrategyInterface { /** * @param string $password Cleartext password that will be hashed * @param string $staticSalt Optional static salt that will not be stored in the hashed password * @return string The hashed password with dynamic salt (if used) */ public function hashPassword($password, $staticSalt = null) { return 'hashed' . $password . $staticSalt; } /** * @param string $password * @param string $hashedPasswordAndSalt Hashed password with dynamic salt (if used) * @param string $staticSalt Optional static salt that will not be stored in the hashed password * @return boolean TRUE if the given cleartext password matched the hashed password */ public function validatePassword($password, $hashedPasswordAndSalt, $staticSalt = null) { return false; } }
Disable fetching profile for now
import React from 'react'; import { connect } from 'react-redux'; import { clearNotices } from 'lib/actions/general'; import { doAuthWithPassword, parseAuthToken, getProfile } from 'lib/actions/auth'; import Layout from 'components/layout'; import LogInBox from 'components/log-in-box'; class App extends React.Component { componentWillMount() { if ( ! this.props.auth.token || this.props.auth.expiredToken ) { this.props.parseAuthToken(); } } componentDidMount() { this.getUserInfo( this.props ); } componentDidUpdate() { this.getUserInfo( this.props ); } getUserInfo( props ) { if ( props.auth.token && ! props.auth.user && ! props.auth.expiredToken && ! props.errors.length ) { // FIXME: the token is always invalid for some reason // props.getProfile(); } } render() { if ( this.props.auth.token ) { return ( <Layout children={ this.props.children } /> ); } return ( <LogInBox showAuth={ this.props.doAuthWithPassword } errors={ this.props.errors } onClearNotices={ this.props.clearNotices } /> ); } } App.propTypes = { auth: React.PropTypes.object.isRequired, }; function mapStateToProps( state ) { const { auth, notices } = state; return { auth, errors: notices.errors }; } export default connect( mapStateToProps, { doAuthWithPassword, getProfile, parseAuthToken, clearNotices } )( App );
import React from 'react'; import { connect } from 'react-redux'; import { clearNotices } from 'lib/actions/general'; import { doAuthWithPassword, parseAuthToken, getProfile } from 'lib/actions/auth'; import Layout from 'components/layout'; import LogInBox from 'components/log-in-box'; class App extends React.Component { componentWillMount() { if ( ! this.props.auth.token || this.props.auth.expiredToken ) { this.props.parseAuthToken(); } } componentDidMount() { this.getUserInfo( this.props ); } componentDidUpdate() { this.getUserInfo( this.props ); } getUserInfo( props ) { if ( props.auth.token && ! props.auth.user && ! props.auth.expiredToken && ! props.errors.length ) { props.getProfile(); } } render() { if ( this.props.auth.token ) { return ( <Layout children={ this.props.children } /> ); } return ( <LogInBox showAuth={ this.props.doAuthWithPassword } errors={ this.props.errors } onClearNotices={ this.props.clearNotices } /> ); } } App.propTypes = { auth: React.PropTypes.object.isRequired, }; function mapStateToProps( state ) { const { auth, notices } = state; return { auth, errors: notices.errors }; } export default connect( mapStateToProps, { doAuthWithPassword, getProfile, parseAuthToken, clearNotices } )( App );
Build: Remove CRLF line endings to fix builds on Windows Close gh-3929
var fs = require( "fs" ); module.exports = function( grunt ) { grunt.registerTask( "qunit_fixture", function() { var dest = "./test/data/qunit-fixture.js"; fs.writeFileSync( dest, "// Generated by build/tasks/qunit_fixture.js\n" + "QUnit.config.fixture = " + JSON.stringify( fs.readFileSync( "./test/data/qunit-fixture.html", "utf8" ).toString().replace( /\r\n/g, "\n" ) ) + ";\n" + "// Compat with QUnit 1.x:\n" + "document.getElementById( \"qunit-fixture\" ).innerHTML = QUnit.config.fixture;\n" ); grunt.log.ok( "Updated " + dest + "." ); } ); };
var fs = require( "fs" ); module.exports = function( grunt ) { grunt.registerTask( "qunit_fixture", function() { var dest = "./test/data/qunit-fixture.js"; fs.writeFileSync( dest, "// Generated by build/tasks/qunit_fixture.js\n" + "QUnit.config.fixture = " + JSON.stringify( fs.readFileSync( "./test/data/qunit-fixture.html", "utf8" ).toString() ) + ";\n" + "// Compat with QUnit 1.x:\n" + "document.getElementById( \"qunit-fixture\" ).innerHTML = QUnit.config.fixture;\n" ); grunt.log.ok( "Updated " + dest + "." ); } ); };
Add environment to newly-generated task IDs.
package com.twitter.aurora.scheduler; import java.util.UUID; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.inject.Inject; import com.twitter.aurora.gen.TaskConfig; import com.twitter.common.util.Clock; /** * A function that generates universally-unique (not guaranteed, but highly confident) task IDs. */ class TaskIdGenerator implements Function<TaskConfig, String> { private final Clock clock; @Inject TaskIdGenerator(Clock clock) { this.clock = Preconditions.checkNotNull(clock); } @Override public String apply(TaskConfig task) { String sep = "-"; return new StringBuilder() .append(clock.nowMillis()) // Allows chronological sorting. .append(sep) .append(task.getOwner().getRole()) // Identification and collision prevention. .append(sep) .append(task.getEnvironment()) .append(sep) .append(task.getJobName()) .append(sep) .append(task.getShardId()) // Collision prevention within job. .append(sep) .append(UUID.randomUUID()) // Just-in-case collision prevention. .toString().replaceAll("[^\\w-]", sep); // Constrain character set. } }
package com.twitter.aurora.scheduler; import java.util.UUID; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.inject.Inject; import com.twitter.aurora.gen.TaskConfig; import com.twitter.common.util.Clock; /** * A function that generates universally-unique (not guaranteed, but highly confident) task IDs. */ class TaskIdGenerator implements Function<TaskConfig, String> { private final Clock clock; @Inject TaskIdGenerator(Clock clock) { this.clock = Preconditions.checkNotNull(clock); } @Override public String apply(TaskConfig task) { String sep = "-"; return new StringBuilder() .append(clock.nowMillis()) // Allows chronological sorting. .append(sep) .append(task.getOwner().getRole()) // Identification and collision prevention. .append(sep) .append(task.getJobName()) .append(sep) .append(task.getShardId()) // Collision prevention within job. .append(sep) .append(UUID.randomUUID()) // Just-in-case collision prevention. .toString().replaceAll("[^\\w-]", sep); // Constrain character set. } }
Fix return dest stream from pipe
var PassThrough = require('stream').PassThrough var inherits = require('util').inherits function SeriesStream () { PassThrough.apply(this, arguments) this._current = null this._queue = [] } inherits(SeriesStream, PassThrough) SeriesStream.prototype.on = function (ev, fn) { var res = PassThrough.prototype.on.call(this, ev, fn) if (ev === 'data' && !this._current) { this._next() } return res } SeriesStream.prototype.pipe = function (dest) { PassThrough.prototype.pipe.call(this, dest) if (!this._current) { this._next() } return dest } SeriesStream.prototype.add = function (src) { this._queue.push(src) return this } SeriesStream.prototype._next = function () { this._current = null if (!this._queue.length) return var next = this._queue.shift() this._current = next next.once('end', this._next.bind(this)) next.pipe(this) } SeriesStream.prototype.end = function () { if (this._current) return // Only end when all streams have ended return PassThrough.prototype.end.apply(this, arguments) } module.exports = function (opts) { return new SeriesStream(opts) } module.exports.SeriesStream = SeriesStream
var PassThrough = require('stream').PassThrough var inherits = require('util').inherits function SeriesStream () { PassThrough.apply(this, arguments) this._current = null this._queue = [] } inherits(SeriesStream, PassThrough) SeriesStream.prototype.on = function (ev, fn) { var res = PassThrough.prototype.on.call(this, ev, fn) if (ev === 'data' && !this._current) { this._next() } return res } SeriesStream.prototype.pipe = function (dest) { PassThrough.prototype.pipe.call(this, dest) if (!this._current) { this._next() } } SeriesStream.prototype.add = function (src) { this._queue.push(src) } SeriesStream.prototype._next = function () { this._current = null if (!this._queue.length) return var next = this._queue.shift() this._current = next next.once('end', this._next.bind(this)) next.pipe(this) } SeriesStream.prototype.end = function () { if (this._current) return // Only end when all streams have ended PassThrough.prototype.end.apply(this, arguments) } module.exports = function (opts) { return new SeriesStream(opts) } module.exports.SeriesStream = SeriesStream
Read breakpoint file from classpath
package com.thanglequoc.aqicalculator; import java.io.IOException; import java.io.InputStream; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; public class PollutantsBreakpointGenerator { private PollutantsBreakpoint pollutantsBreakpoint; private PollutantBreakpointParser pollutantBreakpointParser; private static String breakpointFilePath = "./src/main/resources/AQIresource/aqi-breakpoint.json"; public PollutantsBreakpointGenerator() throws JsonProcessingException, IOException{ pollutantBreakpointParser = new PollutantBreakpointParser(); pollutantsBreakpoint = new PollutantsBreakpoint(); ObjectMapper mapper = new ObjectMapper(); ClassLoader classLoader = PollutantsBreakpointGenerator.class.getClassLoader(); try (InputStream inputStream = classLoader.getResourceAsStream("AQIresource/aqi-breakpoint.json")) { JsonNode root = mapper.readTree(inputStream); for(JsonNode pollutantNode: root){ PollutantBreakpoint pollutantBreakpoint = pollutantBreakpointParser.parseNode(pollutantNode); this.pollutantsBreakpoint.addPollutantBreakpoint(pollutantBreakpoint); } } } public PollutantsBreakpoint getPollutantsBreakpoint() { return pollutantsBreakpoint; } public void setPollutantsBreakpoint(PollutantsBreakpoint pollutantsBreakpoint) { this.pollutantsBreakpoint = pollutantsBreakpoint; } }
package com.thanglequoc.aqicalculator; import java.io.File; import java.io.IOException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; public class PollutantsBreakpointGenerator { private PollutantsBreakpoint pollutantsBreakpoint; private PollutantBreakpointParser pollutantBreakpointParser; private static String breakpointFilePath = "./src/main/resources/AQIresource/aqi-breakpoint.json"; private File breakpointFile; public PollutantsBreakpointGenerator() throws JsonProcessingException, IOException{ pollutantBreakpointParser = new PollutantBreakpointParser(); pollutantsBreakpoint = new PollutantsBreakpoint(); File breakpointFile = new File(breakpointFilePath); setBreakpointFile(breakpointFile); ObjectMapper mapper = new ObjectMapper(); JsonNode root = mapper.readTree(breakpointFile); for(JsonNode pollutantNode: root){ PollutantBreakpoint pollutantBreakpoint = pollutantBreakpointParser.parseNode(pollutantNode); this.pollutantsBreakpoint.addPollutantBreakpoint(pollutantBreakpoint); } } public PollutantsBreakpoint getPollutantsBreakpoint() { return pollutantsBreakpoint; } public void setPollutantsBreakpoint(PollutantsBreakpoint pollutantsBreakpoint) { this.pollutantsBreakpoint = pollutantsBreakpoint; } public File getBreakpointFile() { return breakpointFile; } public void setBreakpointFile(File breakpointFile) { this.breakpointFile = breakpointFile; } }
Change Cookie expiration to 30 days
import { serialize } from 'cookie'; export default async function cookieHandler(req, res) { const { method } = req; if (method === 'POST') { const body = JSON.parse(req.body); if (body.token) { res.setHeader( 'Set-Cookie', serialize('gfw-token', body.token, { path: '/', httpOnly: true, maxAge: 2592000, }) ); res.status(200).end('ok'); } } else if (method === 'GET') { res.setHeader( 'Set-Cookie', serialize('gfw-token', '', { path: '/', maxAge: -1 }) ); res.status(200).end('ok'); } else { res.setHeader('Allow', ['POST', 'GET']); res.status(405).end(`Method ${method} Not Allowed`); } res.status(405).end(''); }
import { serialize } from 'cookie'; export default async function cookieHandler(req, res) { const { method } = req; if (method === 'POST') { const body = JSON.parse(req.body); if (body.token) { res.setHeader( 'Set-Cookie', serialize('gfw-token', body.token, { path: '/', httpOnly: true, maxAge: 315360000, }) ); res.status(200).end('ok'); } } else if (method === 'GET') { res.setHeader( 'Set-Cookie', serialize('gfw-token', '', { path: '/', maxAge: -1 }) ); res.status(200).end('ok'); } else { res.setHeader('Allow', ['POST', 'GET']); res.status(405).end(`Method ${method} Not Allowed`); } res.status(405).end(''); }
Add self-rating flag for movies. Removed LikedOrNot table
from django.db import models # Create your models here. class Movie(models.Model): movie_id = models.IntegerField(primary_key=True) title = models.CharField(max_length=200) poster = models.ImageField(null=True, blank=True) year = models.IntegerField(null=True) genres = models.CharField(max_length=200) num_ratings = models.IntegerField(null=True) rating_median = models.FloatField(null=True) rating_mean = models.FloatField(null=True) relatable = models.BooleanField(default=True) liked_or_not = models.NullBooleanField(null=True, blank=True) def __str__(self): return self.title class Similarity(models.Model): first_movie = models.ForeignKey(Movie, related_name='first_movie') second_movie = models.ForeignKey(Movie, related_name='second_movie') similarity_score = models.FloatField() class Tag(models.Model): movie = models.ForeignKey(Movie) tag = models.CharField(max_length=50) relevance = models.FloatField() class OnlineLink(models.Model): movie = models.ForeignKey(Movie) imdb_id = models.CharField(max_length=50)
from django.db import models # Create your models here. class Movie(models.Model): movie_id = models.IntegerField(primary_key=True) title = models.CharField(max_length=200) poster = models.ImageField(null=True, blank=True) year = models.IntegerField(null=True) genres = models.CharField(max_length=200) num_ratings = models.IntegerField(null=True) rating_median = models.FloatField(null=True) rating_mean = models.FloatField(null=True) relatable = models.BooleanField(default=True) def __str__(self): return self.title class LikedOrNot(models.Model): movie = models.ForeignKey(Movie) liked_or_not = models.SmallIntegerField(null=True, blank=True, choices=((-1, "bad"), (0, "alright"), (1, "liked"))) class Similarity(models.Model): first_movie = models.ForeignKey(Movie, related_name='first_movie') second_movie = models.ForeignKey(Movie, related_name='second_movie') similarity_score = models.FloatField() class Tag(models.Model): movie = models.ForeignKey(Movie) tag = models.CharField(max_length=50) relevance = models.FloatField() class OnlineLink(models.Model): movie = models.ForeignKey(Movie) imdb_id = models.CharField(max_length=50)
Fix zero-length field error when building docs in Python 2.6
import os import taxii_services project = u'django-taxii-services' copyright = u'2014, The MITRE Corporation' version = taxii_services.__version__ release = version extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' rst_prolog = """ **Version**: {0} """.format(release) exclude_patterns = ['_build'] pygments_style = 'sphinx' on_rtd = os.environ.get('READTHEDOCS', None) == 'True' if not on_rtd: # only import and set the theme if we're building docs locally import sphinx_rtd_theme html_theme = 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] else: html_theme = 'default' latex_elements = {} latex_documents = [ ('index', 'django-taxii-services.tex', u'django-taxii-services Documentation', u'Mark Davidson', 'manual'), ]
import os import taxii_services project = u'django-taxii-services' copyright = u'2014, The MITRE Corporation' version = taxii_services.__version__ release = version extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' rst_prolog = """ **Version**: {} """.format(release) exclude_patterns = ['_build'] pygments_style = 'sphinx' on_rtd = os.environ.get('READTHEDOCS', None) == 'True' if not on_rtd: # only import and set the theme if we're building docs locally import sphinx_rtd_theme html_theme = 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] else: html_theme = 'default' latex_elements = {} latex_documents = [ ('index', 'django-taxii-services.tex', u'django-taxii-services Documentation', u'Mark Davidson', 'manual'), ]
Update KYD to KYDC listing to be conform ISO_4217
/* * This file is part of Bisq. * * Bisq 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. * * Bisq 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 Bisq. If not, see <http://www.gnu.org/licenses/>. */ package bisq.asset.coins; import bisq.asset.Base58BitcoinAddressValidator; import bisq.asset.Coin; import bisq.asset.NetworkParametersAdapter; public class KnowYourDeveloper extends Coin { public KnowYourDeveloper() { super("Know Your Developer", "KYDC", new Base58BitcoinAddressValidator(new KydMainNetParams())); } public static class KydMainNetParams extends NetworkParametersAdapter { public KydMainNetParams() { this.addressHeader = 78; this.p2shHeader = 85; this.acceptableAddressCodes = new int[]{this.addressHeader, this.p2shHeader}; } } }
/* * This file is part of Bisq. * * Bisq 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. * * Bisq 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 Bisq. If not, see <http://www.gnu.org/licenses/>. */ package bisq.asset.coins; import bisq.asset.Base58BitcoinAddressValidator; import bisq.asset.Coin; import bisq.asset.NetworkParametersAdapter; public class KnowYourDeveloper extends Coin { public KnowYourDeveloper() { super("Know Your Developer", "KYD", new Base58BitcoinAddressValidator(new KydMainNetParams())); } public static class KydMainNetParams extends NetworkParametersAdapter { public KydMainNetParams() { this.addressHeader = 78; this.p2shHeader = 85; this.acceptableAddressCodes = new int[]{this.addressHeader, this.p2shHeader}; } } }