text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Update name of pyramid function in pyramid example description
""" ==================== Build image pyramids ==================== The `pyramid_gaussian` function takes an image and yields successive images shrunk by a constant scale factor. Image pyramids are often used, e.g., to implement algorithms for denoising, texture discrimination, and scale- invariant detection. """ import numpy as np import matplotlib.pyplot as plt from skimage import data from skimage.transform import pyramid_gaussian image = data.lena() rows, cols, dim = image.shape pyramid = tuple(pyramid_gaussian(image, downscale=2)) composite_image = np.zeros((rows, cols + cols / 2, 3), dtype=np.double) composite_image[:rows, :cols, :] = pyramid[0] i_row = 0 for p in pyramid[1:]: n_rows, n_cols = p.shape[:2] composite_image[i_row:i_row + n_rows, cols:cols + n_cols] = p i_row += n_rows plt.imshow(composite_image) plt.show()
""" ==================== Build image pyramids ==================== The `build_gaussian_pyramid` function takes an image and yields successive images shrunk by a constant scale factor. Image pyramids are often used, e.g., to implement algorithms for denoising, texture discrimination, and scale- invariant detection. """ import numpy as np import matplotlib.pyplot as plt from skimage import data from skimage.transform import pyramid_gaussian image = data.lena() rows, cols, dim = image.shape pyramid = tuple(pyramid_gaussian(image, downscale=2)) composite_image = np.zeros((rows, cols + cols / 2, 3), dtype=np.double) composite_image[:rows, :cols, :] = pyramid[0] i_row = 0 for p in pyramid[1:]: n_rows, n_cols = p.shape[:2] composite_image[i_row:i_row + n_rows, cols:cols + n_cols] = p i_row += n_rows plt.imshow(composite_image) plt.show()
Test that Add actually works.
package main import ( "bsearch/index" "bsearch/ops" "fmt" "os" "flag" ) func usage() { fmt.Fprintf(os.Stderr, "usage: bsearch <path to index blob>\n") flag.PrintDefaults() os.Exit(1) } func main() { flag.Parse() if flag.NArg() != 1 { usage() } dbname := flag.Arg(0) in, err := index.Open(dbname) if err != nil { fmt.Fprintf(os.Stderr, "bindex.Open: %v\n", err) return } defer in.Close() a1 := ops.NewAttr(in, "root:10") a2 := ops.NewAttr(in, "magic:boll") a3 := ops.NewAttr(in, "status:active") q := ops.NewIntersection(a1, a2) q.Add(a3) var d *index.IbDoc for true { d = q.NextDoc(d) if d == nil { break } fmt.Printf("%v\n", string(in.Docs[d.Id])) d = d.Inc() } }
package main import ( "bsearch/index" "bsearch/ops" "fmt" "os" "flag" ) func usage() { fmt.Fprintf(os.Stderr, "usage: bsearch <path to index blob>\n") flag.PrintDefaults() os.Exit(1) } func main() { flag.Parse() if flag.NArg() != 1 { usage() } dbname := flag.Arg(0) in, err := index.Open(dbname) if err != nil { fmt.Fprintf(os.Stderr, "bindex.Open: %v\n", err) return } defer in.Close() a1 := ops.NewAttr(in, "root:10") a2 := ops.NewAttr(in, "magic:boll") a3 := ops.NewAttr(in, "status:active") q := ops.NewIntersection(a1, a2, a3) var d *index.IbDoc for true { d = q.NextDoc(d) if d == nil { break } fmt.Printf("%v\n", string(in.Docs[d.Id])) d = d.Inc() } }
Complete operators tests to pass
module("About Operators (topics/about_operators.js)"); test("addition", function() { var result = 0; //starting i at 0, add i to result and increment i by 1 until i is equal to 5 for (var i = 0; i <= 5; i++) { result = result + i; } equal(15, result, "What is the value of result?"); }); test("assignment addition", function() { var result = 0; for (var i = 0; i <=5; i++) { //the code below is just like saying result = result + i; but is more concise result += i; } equal(15, result, "What is the value of result?"); }); test("subtraction", function() { var result = 5; for (var i = 0; i <= 2; i++) { result = result - i; } equal(2, result, "What is the value of result?"); }); test("assignment subtraction", function() { var result = 5; for (var i = 0; i <= 2; i++) { result -= i; } equal(2, result, "What is the value of result?"); }); //Assignment operators are available for multiplication and division as well //let's do one more, the modulo operator, used for showing division remainder test("modulus", function() { var result = 10; var x = 5; //again this is exactly the same as result = result % x result %= x; equal(0, result, "What is the value of result?"); });
module("About Operators (topics/about_operators.js)"); test("addition", function() { var result = 0; //starting i at 0, add i to result and increment i by 1 until i is equal to 5 for (var i = 0; i <= 5; i++) { result = result + i; } equal(__, result, "What is the value of result?"); }); test("assignment addition", function() { var result = 0; for (var i = 0; i <=5; i++) { //the code below is just like saying result = result + i; but is more concise result += i; } equal(__, result, "What is the value of result?"); }); test("subtraction", function() { var result = 5; for (var i = 0; i <= 2; i++) { result = result - i; } equal(__, result, "What is the value of result?"); }); test("assignment subtraction", function() { var result = 5; for (var i = 0; i <= 2; i++) { result -= i; } equal(__, result, "What is the value of result?"); }); //Assignment operators are available for multiplication and division as well //let's do one more, the modulo operator, used for showing division remainder test("modulus", function() { var result = 10; var x = 5; //again this is exactly the same as result = result % x result %= x; equal(__, result, "What is the value of result?"); });
Change the controller to reflect the changes on read file
app.controller('MyIndexController', ['$scope', function ($scope) { $scope.searchTable = false; $scope.files = []; $scope.searchFiles = []; $scope.instance = new Index(); $scope.showIndex = false; $scope.showSearch = false; $scope.indexData = {}; $scope.objKeys = Object.keys; $scope.getFile = () => { const file = document.getElementById('filePath').files[0]; $scope.filename = file.name; $scope.files.push(file.name); $scope.searchFiles.push(file.name); $scope.alert = $scope.instance.readFile(file); } $scope.createIndex = () => { $scope.showIndex = true; $scope.showSearch = false; $scope.indexData = $scope.instance.indexObject; } $scope.search = () => { $scope.showIndex = false; $scope.showSearch = true; const selectSearch = $scope.toSearch; const terms = document.getElementById("terms").value; const opt = document.getElementById("select"); const filename = opt.options[opt.selectedIndex].text; $scope.results = $scope.instance.searchIndex(filename, terms); } }]);
app.controller('MyIndexController', ['$scope', function ($scope) { $scope.searchTable = false; $scope.files = []; $scope.searchFiles = []; $scope.instance = new Index(); $scope.showIndex = false; $scope.showSearch = false; $scope.indexData = {}; $scope.objKeys = Object.keys; $scope.getFile = () => { const file = document.getElementById('filePath').files[0]; $scope.filename = file.name; $scope.files.push(file.name); $scope.searchFiles.push(file.name); $scope.instance.readFile(file); } $scope.createIndex = () => { $scope.showIndex = true; $scope.showSearch = false; $scope.indexData = $scope.instance.indexObject; } $scope.search = () => { $scope.showIndex = false; $scope.showSearch = true; const selectSearch = $scope.toSearch; const terms = document.getElementById("terms").value; const opt = document.getElementById("select"); const filename = opt.options[opt.selectedIndex].text; console.log(filename); $scope.results = $scope.instance.searchIndex(filename, terms); console.log($scope.results); } }]);
Change PDF font to Helvetica Changing the PDF font from the default to Helvetica
from ..converter import KnowledgePostConverter from .html import HTMLConverter class PDFConverter(KnowledgePostConverter): ''' Use this as a template for new KnowledgePostConverters. ''' _registry_keys = ['pdf'] @property def dependencies(self): # Dependencies required for this converter on top of core knowledge-repo dependencies return ['weasyprint'] def from_file(self, filename, **opts): raise NotImplementedError def from_string(self, filename, **opts): raise NotImplementedError def to_file(self, filename, **opts): with open(filename, 'wb') as f: f.write(self.to_string()) def to_string(self, **opts): from weasyprint import HTML, CSS html = HTMLConverter(self.kp).to_string() return HTML(string=html).write_pdf(stylesheets=[CSS(string='body { font-family: Helvetica, sans-serif !important }')])
from ..converter import KnowledgePostConverter from .html import HTMLConverter class PDFConverter(KnowledgePostConverter): ''' Use this as a template for new KnowledgePostConverters. ''' _registry_keys = ['pdf'] @property def dependencies(self): # Dependencies required for this converter on top of core knowledge-repo dependencies return ['weasyprint'] def from_file(self, filename, **opts): raise NotImplementedError def from_string(self, filename, **opts): raise NotImplementedError def to_file(self, filename, **opts): with open(filename, 'wb') as f: f.write(self.to_string()) def to_string(self, **opts): from weasyprint import HTML html = HTMLConverter(self.kp).to_string() return HTML(string=html).write_pdf()
Update column type (json to text) for media table
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateMediaTable extends Migration { /** * Run the migrations. */ public function up() { Schema::create('media', function (Blueprint $table) { $table->increments('id'); $table->morphs('model'); $table->string('collection_name'); $table->string('name'); $table->string('file_name'); $table->string('mime_type')->nullable(); $table->string('disk'); $table->unsignedInteger('size'); $table->text('manipulations'); $table->text('custom_properties'); $table->text('responsive_images'); $table->unsignedInteger('order_column')->nullable(); $table->nullableTimestamps(); }); } /** * Reverse the migrations. */ public function down() { Schema::dropIfExists('media'); } }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateMediaTable extends Migration { /** * Run the migrations. */ public function up() { Schema::create('media', function (Blueprint $table) { $table->increments('id'); $table->morphs('model'); $table->string('collection_name'); $table->string('name'); $table->string('file_name'); $table->string('mime_type')->nullable(); $table->string('disk'); $table->unsignedInteger('size'); $table->json('manipulations'); $table->json('custom_properties'); $table->json('responsive_images'); $table->unsignedInteger('order_column')->nullable(); $table->nullableTimestamps(); }); } /** * Reverse the migrations. */ public function down() { Schema::dropIfExists('media'); } }
Move period label to a config property
define([ 'extensions/views/single-stat' ], function (SingleStatView) { var ResponeTimeNumberView = SingleStatView.extend({ changeOnSelected: true, getValue: function () { var responseTime = Math.round(this.collection.getAverageResponseTime()); return this.formatDuration(responseTime, 4); }, labelPrefix: 'mean ', periodLabel: { hour: '24 hours', day: '30 days' }, getLabel: function () { var period = this.collection.query.get('period'); return this.labelPrefix + 'for the last ' + this.periodLabel[period]; }, getValueSelected: function (selection) { return this.formatDuration(selection.selectedModel.get('avgresponse'), 4); }, getLabelSelected: function (selection) { var model = selection.selectedModel; var start = model.get('_start_at'); var end = model.get('_end_at'); return [ start.format('ha'), ' to ', end.format('ha'), ',<br>', start.format('D MMMM YYYY') ].join(''); } }); return ResponeTimeNumberView; });
define([ 'extensions/views/single-stat' ], function (SingleStatView) { var ResponeTimeNumberView = SingleStatView.extend({ changeOnSelected: true, getValue: function () { var responseTime = Math.round(this.collection.getAverageResponseTime()); return this.formatDuration(responseTime, 4); }, labelPrefix: 'mean ', getLabel: function () { var period = this.collection.query.get('period'), periodLabel = period === 'day' ? '30 days' : '24 hours'; return this.labelPrefix + 'for the last ' + periodLabel; }, getValueSelected: function (selection) { return this.formatDuration(selection.selectedModel.get('avgresponse'), 4); }, getLabelSelected: function (selection) { var model = selection.selectedModel; var start = model.get('_start_at'); var end = model.get('_end_at'); return [ start.format('ha'), ' to ', end.format('ha'), ',<br>', start.format('D MMMM YYYY') ].join(''); } }); return ResponeTimeNumberView; });
Remove last reference to array returns
/** * Exports */ module.exports = Dispatcher; /** * Dispatcher prototype */ var dispatcher = Dispatcher.prototype; /** * Dispatcher * * @return {Object} * @api public */ function Dispatcher() { if (!(this instanceof Dispatcher)) return new Dispatcher; this.callbacks = []; }; /** * Register a new store. * * dispatcher.register('update_course', callbackFunction); * * @param {String} action * @param {Function} callback * @api public */ dispatcher.register = function(action, callback) { this.callbacks.push({ action: action, callback: callback }); }; /** * Dispatch event to stores. * * dispatcher.dispatch('update_course', {id: 123, title: 'Tobi'}); * * @param {String} action * @param {Object | Object[]} data * @return {Function[]} * @api public */ dispatcher.dispatch = function(action, data) { this.getCallbacks(action) .forEach(function(callback) { callback.call(callback, data); }); }; /** * Return registered callbacks. * * @param {String} action * @return {Function[]} * @api private */ dispatcher.getCallbacks = function(action) { return this.callbacks .filter(function(callback) { return callback.action === action; }) .map(function(callback) { return callback.callback; }); };
/** * Dispatcher prototype */ var dispatcher = Dispatcher.prototype; /** * Exports */ module.exports = Dispatcher; /** * Dispatcher * * @return {Object} * @api public */ function Dispatcher() { if (!(this instanceof Dispatcher)) return new Dispatcher; this.callbacks = []; }; /** * Register a new store. * * dispatcher.register('update_course', callbackFunction); * * @param {String} action * @param {Function} callback * @api public */ dispatcher.register = function(action, callback) { this.callbacks.push({ action: action, callback: callback }); }; /** * Dispatch event to stores. * * dispatcher.dispatch('update_course', {id: 123, title: 'Tobi'}); * * @param {String} action * @param {Object | Object[]} data * @return {Function[]} * @api public */ dispatcher.dispatch = function(action, data) { this.getCallbacks(action) .map(function(callback) { return callback.call(callback, data); }); }; /** * Return registered callbacks. * * @param {String} action * @return {Function[]} * @api private */ dispatcher.getCallbacks = function(action) { return this.callbacks .filter(function(callback) { return callback.action === action; }) .map(function(callback) { return callback.callback; }); };
Update CSS selector which matched two img elements
from comics.aggregator.crawler import CrawlerBase, CrawlerResult from comics.meta.base import MetaBase class Meta(MetaBase): name = 'The PC Weenies' language = 'en' url = 'http://www.pcweenies.com/' start_date = '1998-10-21' rights = 'Krishna M. Sadasivam' class Crawler(CrawlerBase): history_capable_days = 10 schedule = 'Mo,We,Fr' time_zone = -8 def crawl(self, pub_date): feed = self.parse_feed('http://www.pcweenies.com/feed/') for entry in feed.for_date(pub_date): if 'Comic' in entry.tags: title = entry.title url = entry.content0.src(u'img[src*="/comics/"]') return CrawlerResult(url, title)
from comics.aggregator.crawler import CrawlerBase, CrawlerResult from comics.meta.base import MetaBase class Meta(MetaBase): name = 'The PC Weenies' language = 'en' url = 'http://www.pcweenies.com/' start_date = '1998-10-21' rights = 'Krishna M. Sadasivam' class Crawler(CrawlerBase): history_capable_days = 10 schedule = 'Mo,We,Fr' time_zone = -8 def crawl(self, pub_date): feed = self.parse_feed('http://www.pcweenies.com/feed/') for entry in feed.for_date(pub_date): if 'Comic' in entry.tags: title = entry.title url = entry.content0.src(u'img') return CrawlerResult(url, title)
Add a method to create a measurement.
# -*- coding: utf-8 -*- from sqlalchemy import ( Column, Date, Integer, MetaData, Numeric, String, Table, ) def define_tables(metadata): Table('measurement', metadata, Column('id', Integer, primary_key=True), Column('weight', Numeric(4, 1), nullable=False), Column('code', String(25), nullable=False), Column('note', String(140), nullable=True), Column('date_measured', Date(), nullable=False), ) class Db(object): def __init__(self, engine): self._meta = MetaData(engine) define_tables(self._meta) def make_tables(self): self._meta.create_all() def drop_tables(self): self._meta.drop_all() @property def measurement(self): return self._meta.tables['measurement'] class MeasurementService(object): def __init__(self, table): self._table = table def create(self, **kwargs): i = self._table.insert() i.execute(**kwargs)
# -*- coding: utf-8 -*- from sqlalchemy import ( Column, Date, Integer, MetaData, Numeric, String, Table, ) def define_tables(metadata): Table('measurement', metadata, Column('id', Integer, primary_key=True), Column('weight', Numeric(4, 1), nullable=False), Column('code', String(25), nullable=False), Column('note', String(140), nullable=True), Column('date_measured', Date(), nullable=False), ) class Db(object): def __init__(self, engine): self._meta = MetaData(engine) define_tables(self._meta) def make_tables(self): self._meta.create_all() def drop_tables(self): self._meta.drop_all() @property def measurement(self): return self._meta.tables['measurement'] class MeasurementService(object): def __init__(self, table): self._table = table
Remove the ability to create messages through repository
<?php /* * This file is apart of the DiscordPHP project. * * Copyright (c) 2016-2020 David Cole <david.cole1340@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the LICENSE.md file. */ namespace Discord\Repository\Channel; use Discord\Parts\Channel\Message; use Discord\Repository\AbstractRepository; /** * Contains messages sent to channels. * * @see Discord\Parts\Channel\Message * @see Discord\Parts\Channel\Channel */ class MessageRepository extends AbstractRepository { /** * {@inheritdoc} */ protected $endpoints = [ 'get' => 'channels/:channel_id/messages/:id', 'update' => 'channels/:channel_id/messages/:id', 'delete' => 'channels/:channel_id/messages/:id', ]; /** * {@inheritdoc} */ protected $part = Message::class; }
<?php /* * This file is apart of the DiscordPHP project. * * Copyright (c) 2016-2020 David Cole <david.cole1340@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the LICENSE.md file. */ namespace Discord\Repository\Channel; use Discord\Parts\Channel\Message; use Discord\Repository\AbstractRepository; /** * Contains messages sent to channels. * * @see Discord\Parts\Channel\Message * @see Discord\Parts\Channel\Channel */ class MessageRepository extends AbstractRepository { /** * {@inheritdoc} */ protected $endpoints = [ 'get' => 'channels/:channel_id/messages/:id', 'create' => 'channels/:channel_id/messages', 'update' => 'channels/:channel_id/messages/:id', 'delete' => 'channels/:channel_id/messages/:id', ]; /** * {@inheritdoc} */ protected $part = Message::class; }
Create a date object from a string representing a date
package chap3CoreJavaAPIs; import java.util.Calendar; import java.time.Month; import java.time.*; class Dates { public void createDateFromString() { Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse("2012-05-20T09:00:00.000Z"); String formattedDate = new SimpleDateFormat("yyyy-MM-dd'T'HHmmss").format(date); System.out.println(formattedDate); } public static void main(String... args) { // Be careful, old API Calendar starts at 0, new Month starts at 1 System.out.println(Calendar.APRIL); System.out.println(Month.APRIL); System.out.println(LocalDate.of(2015, Month.APRIL, 1)); System.out.println(LocalDate.of(2015, Calendar.APRIL, 1)); System.out.println(LocalDate.of(2015, Calendar.MAY, 1).equals(LocalDate.of(2015, Month.APRIL, 1))); System.out.println(Period.ofMonths(1)); System.out.println(Period.ofMonths(1).ofDays(2)); System.out.println(Period.ofDays(2)); } }
package chap3CoreJavaAPIs; import java.util.Calendar; import java.time.Month; import java.time.*; class Dates{ public static void main(String... args){ // Be careful, old API Calendar starts at 0, new Month starts at 1 System.out.println(Calendar.APRIL); System.out.println(Month.APRIL); System.out.println(LocalDate.of(2015, Month.APRIL, 1)); System.out.println(LocalDate.of(2015, Calendar.APRIL, 1)); System.out.println(LocalDate.of(2015, Calendar.MAY, 1).equals(LocalDate.of(2015, Month.APRIL, 1))); System.out.println(Period.ofMonths(1)); System.out.println(Period.ofMonths(1).ofDays(2)); System.out.println(Period.ofDays(2)); } }
Add array to sentence filter
<?php /** * SiteFilter.php * * Created By: jonathan * Date: 28/09/2017 * Time: 13:33 */ namespace Stati\Liquid\Filter; class SiteFilter { /** * Escapes an xml string * * @param string $input * * @return string */ public static function xml_escape($input) { return htmlentities($input); } /** * Counts the number of words in a string * * @param string $input * * @return string */ public static function number_of_words($input) { return str_word_count(strip_tags($input), 0); } public static function tojson($input) { return json_encode($input); } public static function jsonify($input) { return json_encode($input); } public function array_to_sentence_string($input) { if (is_array($input)) { return implode(' ', $input); } return $input; } }
<?php /** * SiteFilter.php * * Created By: jonathan * Date: 28/09/2017 * Time: 13:33 */ namespace Stati\Liquid\Filter; class SiteFilter { /** * Escapes an xml string * * @param string $input * * @return string */ public static function xml_escape($input) { return htmlentities($input); } /** * Counts the number of words in a string * * @param string $input * * @return string */ public static function number_of_words($input) { return str_word_count(strip_tags($input), 0); } public static function tojson($input) { return json_encode($input); } public static function jsonify($input) { return json_encode($input); } }
Add period on line 9 Added period on line 9 to match other comments
import createStore from './createStore' import combineReducers from './combineReducers' import bindActionCreators from './bindActionCreators' import applyMiddleware from './applyMiddleware' import compose from './compose' /* * This is a dummy function to check if the function name has been altered by minification. * If the function has been minified and NODE_ENV !== 'production', warn the user. */ function isCrushed() {} if (isCrushed.name !== 'isCrushed' && process.env.NODE_ENV !== 'production') { /*eslint-disable no-console */ console.error( 'You are currently using minified code outside of NODE_ENV === \'production\'. ' + 'This means that you are running a slower development build of Redux. ' + 'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify ' + 'or DefinePlugin for webpack (http://stackoverflow.com/questions/30030031) ' + 'to ensure you have the correct code for your production build.' ) /*eslint-enable */ } export { createStore, combineReducers, bindActionCreators, applyMiddleware, compose }
import createStore from './createStore' import combineReducers from './combineReducers' import bindActionCreators from './bindActionCreators' import applyMiddleware from './applyMiddleware' import compose from './compose' /* * This is a dummy function to check if the function name has been altered by minification. * If the function has been minified and NODE_ENV !== 'production', warn the user */ function isCrushed() {} if (isCrushed.name !== 'isCrushed' && process.env.NODE_ENV !== 'production') { /*eslint-disable no-console */ console.error( 'You are currently using minified code outside of NODE_ENV === \'production\'. ' + 'This means that you are running a slower development build of Redux. ' + 'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify ' + 'or DefinePlugin for webpack (http://stackoverflow.com/questions/30030031) ' + 'to ensure you have the correct code for your production build.' ) /*eslint-enable */ } export { createStore, combineReducers, bindActionCreators, applyMiddleware, compose }
Update config file for gh-pages assests path
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'dummy', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { ENV.baseURL = '/emberx-select' } return ENV; };
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'dummy', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { } return ENV; };
Order questions by published date Closes #23
from django.db import models class Question(models.Model): question_text = models.CharField(max_length=140) published_at = models.DateTimeField(auto_now_add=True) class Meta: get_latest_by = 'published_at' ordering = ('-published_at',) def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, related_name='choices') choice_text = models.CharField(max_length=140) def __str__(self): return self.choice_text def vote(self): """ Create a vote on this choice. """ return Vote.objects.create(choice=self) class Vote(models.Model): choice = models.ForeignKey(Choice, related_name='votes')
from django.db import models class Question(models.Model): question_text = models.CharField(max_length=140) published_at = models.DateTimeField(auto_now_add=True) class Meta: get_latest_by = 'published_at' def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, related_name='choices') choice_text = models.CharField(max_length=140) def __str__(self): return self.choice_text def vote(self): """ Create a vote on this choice. """ return Vote.objects.create(choice=self) class Vote(models.Model): choice = models.ForeignKey(Choice, related_name='votes')
Use the fastest speed for png
package core import ( "errors" "fmt" "image" "image/png" "io" "os" "os/exec" ) type PNGHandler struct { } func (p *PNGHandler) ImageType() string { return "image/png" } func (p *PNGHandler) Decode(reader io.Reader) (image.Image, error) { return png.Decode(reader) } func (p *PNGHandler) Encode(newImgFile *os.File, newImage image.Image) error { return png.Encode(newImgFile, newImage) } func (p *PNGHandler) Convert(newImageTempPath string, quality uint) error { var err error var cmd *exec.Cmd default_args := []string{newImageTempPath, "-f", "--ext=.png", "-s10", "--skip-if-larger", "--strip"} if quality != 100 { var qualityMin = quality - 10 qualityParameter := fmt.Sprintf("--quality=%[1]d-%[2]d", qualityMin, quality) args := append([]string{qualityParameter}, default_args...) cmd = exec.Command("pngquant", args...) err = cmd.Run() if err == nil { return nil } } cmd = exec.Command("pngquant", default_args...) err = cmd.Run() if err != nil { return errors.New("Pngquant command not working") } return nil }
package core import ( "errors" "fmt" "image" "image/png" "io" "os" "os/exec" ) type PNGHandler struct { } func (p *PNGHandler) ImageType() string { return "image/png" } func (p *PNGHandler) Decode(reader io.Reader) (image.Image, error) { return png.Decode(reader) } func (p *PNGHandler) Encode(newImgFile *os.File, newImage image.Image) error { return png.Encode(newImgFile, newImage) } func (p *PNGHandler) Convert(newImageTempPath string, quality uint) error { var err error var cmd *exec.Cmd default_args := []string{newImageTempPath, "-f", "--ext=.png", "--skip-if-larger", "--strip"} if quality != 100 { var qualityMin = quality - 10 qualityParameter := fmt.Sprintf("--quality=%[1]d-%[2]d", qualityMin, quality) args := append([]string{qualityParameter}, default_args...) cmd = exec.Command("pngquant", args...) err = cmd.Run() if err == nil { return nil } } cmd = exec.Command("pngquant", default_args...) err = cmd.Run() if err != nil { return errors.New("Pngquant command not working") } return nil }
Speed up audio extraction by using input seeking
import path from 'path'; import { getBinariesPath } from '../util/appPaths'; const tmp = window.require('tmp-promise'); const { spawn } = window.require('child_process'); const fs = window.require('fs-extra'); const getBinaryFilename = () => { const ffmpegDir = path.join(getBinariesPath(), 'ffmpeg'); let result = path.join(ffmpegDir, 'ffmpeg'); if (process.platform === 'win32') { result += '.exe'; } return result; }; export const extractAudio = async (vidfn, startTime, endTime) => { const tmpfile = await tmp.file({keep: true, postfix: '.mp3'}); await new Promise((resolve, reject) => { const subp = spawn(getBinaryFilename(), ['-ss', startTime.toString(), '-i', vidfn, '-t', (endTime-startTime).toString(), '-map', 'a', '-ab', '192k', '-f', 'mp3', '-y', tmpfile.path], {windowsHide: true, stdio: ['ignore', 'pipe', 'pipe']}); subp.on('error', (error) => { reject(error); }); subp.on('exit', (code) => { if (code) { reject(new Error('ffmpeg exit code ' + code)); } resolve(); }); }); const data = await fs.readFile(tmpfile.path); tmpfile.cleanup(); return data; };
import path from 'path'; import { getBinariesPath } from '../util/appPaths'; const tmp = window.require('tmp-promise'); const { spawn } = window.require('child_process'); const fs = window.require('fs-extra'); const getBinaryFilename = () => { const ffmpegDir = path.join(getBinariesPath(), 'ffmpeg'); let result = path.join(ffmpegDir, 'ffmpeg'); if (process.platform === 'win32') { result += '.exe'; } return result; }; export const extractAudio = async (vidfn, startTime, endTime) => { const tmpfile = await tmp.file({keep: true, postfix: '.mp3'}); await new Promise((resolve, reject) => { const subp = spawn(getBinaryFilename(), ['-i', vidfn, '-ss', startTime.toString(), '-t', (endTime-startTime).toString(), '-map', 'a', '-ab', '192k', '-f', 'mp3', '-y', tmpfile.path], {windowsHide: true, stdio: ['ignore', 'pipe', 'pipe']}); subp.on('error', (error) => { reject(error); }); subp.on('exit', (code) => { if (code) { reject(new Error('ffmpeg exit code ' + code)); } resolve(); }); }); const data = await fs.readFile(tmpfile.path); tmpfile.cleanup(); return data; };
Update 2019 day 5, first part, for new intcode computer
package main import ( "fmt" "strings" "github.com/bewuethr/advent-of-code/go/convert" "github.com/bewuethr/advent-of-code/go/intcode" "github.com/bewuethr/advent-of-code/go/ioutil" "github.com/bewuethr/advent-of-code/go/log" ) func main() { scanner, err := ioutil.GetInputScanner() if err != nil { log.Die("getting scanner", err) } scanner.Scan() opCodesStr := strings.Split(scanner.Text(), ",") if err := scanner.Err(); err != nil { log.Die("reading input", err) } opCodes, err := convert.StrSliceToInt(opCodesStr) if err != nil { log.Die("converting string slice to int", err) } comp := intcode.NewComputer(opCodes) comp.RunProgram() comp.Input <- 1 Loop: for { select { case err := <-comp.Err: log.Die("running op codes", err) case <-comp.Done: break Loop case output := <-comp.Output: fmt.Println(output) } } }
package main import ( "strings" "github.com/bewuethr/advent-of-code/go/convert" "github.com/bewuethr/advent-of-code/go/intcode" "github.com/bewuethr/advent-of-code/go/ioutil" "github.com/bewuethr/advent-of-code/go/log" ) func main() { scanner, err := ioutil.GetInputScanner() if err != nil { log.Die("getting scanner", err) } scanner.Scan() opCodesStr := strings.Split(scanner.Text(), ",") if err := scanner.Err(); err != nil { log.Die("reading input", err) } opCodes, err := convert.StrSliceToInt(opCodesStr) if err != nil { log.Die("converting string slice to int", err) } comp := intcode.NewComputer(opCodes) if err := comp.RunProgram(1); err != nil { log.Die("running op codes", err) } }
Fix app initialization and use backbones navigate function for default route
Andamio.Application = function (options) { _.extend(this, options); this.vent = _.extend({}, Backbone.Events); }; _.extend(Andamio.Application.prototype, Backbone.Events, Andamio.Region, { // selector where the main appview will be rendered container: 'main', // data-region where every page will be displayed el: 'page', // starts the app start: function (options) { _.extend(this, options); this._initAppView(); this._initRouter(); this.initialize.apply(this, arguments); }, initialize: function () {}, // initialize app router _initRouter: function () { this.router = new this.router(); this.listenTo(this.router, 'navigate', this.show); Backbone.history.start(); // navigate to default route var defaultRoute = _.findWhere(this.router.routes, {default: true}); if (defaultRoute && !Backbone.history.fragment) { this.router.navigate(defaultRoute.url, {trigger: true, replace: true}); // this.router._routeCallback(defaultRoute.url, defaultRoute.name, defaultRoute.view); } }, // initialize app view _initAppView: function () { this.appView = new this.appView({el: this.container}); this.appView.render(); }, onShow: function () { this.vent.trigger('navigate', this.currentView); } }); Andamio.Application.extend = Andamio.extend;
Andamio.Application = function (options) { _.extend(this, options); this.vent = _.extend({}, Backbone.Events); }; _.extend(Andamio.Application.prototype, Backbone.Events, Andamio.Region, { // selector where the main appview will be rendered container: 'main', // data-region where every page will be displayed el: 'page', // starts the app start: function (options) { _.extend(this, options); this._initRouter(); this.initialize.apply(this, arguments); this._initAppView(); this.listenTo(this.router, 'navigate', this.show); }, initialize: function () {}, // initialize app router _initRouter: function () { this.router = new this.router(); Backbone.history.start(); // navigate to default route var defaultRoute = _.findWhere(this.router.routes, {default: true}); if (defaultRoute && !Backbone.history.fragment) { this.router.navigate(defaultRoute.url, {trigger: true, replace: true}); } }, // initialize app view _initAppView: function () { this.appView = new this.appView({el: this.container}); this.appView.render(); }, onShow: function () { this.vent.trigger('navigate', this.currentView); } }); Andamio.Application.extend = Andamio.extend;
Make mocha run not only once, seems something has changed.
var expect = require('referee/lib/expect'); var should = require('should'); var assert = require('assert'); function consumeMessage(messageData) { var sender = messageData.source; var specCode = messageData.data; // Reset mocha env document.getElementById('mocha').innerHTML = ''; var mocha = new Mocha({reporter: 'html', ui: 'bdd'}); mocha.suite.emit('pre-require', this, null, this); // Run the spec source code, this calls describe, it, etc. and "fills" // the test runner suites which are executed later in `mocha.run()`. eval(specCode); // Let mocha run and report the stats back to the actual sender. mocha.checkLeaks(); var runner = mocha.run(function() {}); // if there is no callback given mocha will fail and not work again :( function onRan() { var stats = runner.stats; sender.postMessage(stats, '*'); } runner.on('end', onRan); } window.addEventListener('message', consumeMessage, false);
var expect = require('referee/lib/expect'); var should = require('should'); var assert = require('assert'); function consumeMessage(messageData) { var sender = messageData.source; var specCode = messageData.data; // Reset mocha env document.getElementById('mocha').innerHTML = ''; var mocha = new Mocha({reporter: 'html', ui: 'bdd'}); mocha.suite.emit('pre-require', this, null, this); // Run the spec source code, this calls describe, it, etc. and "fills" // the test runner suites which are executed later in `mocha.run()`. eval(specCode); // Let mocha run and report the stats back to the actual sender. mocha.checkLeaks(); var runner = mocha.run(); function onRan() { var stats = runner.stats; sender.postMessage(stats, '*'); } runner.on('end', onRan); } window.addEventListener('message', consumeMessage, false);
Remove reference that our forthcoming Copybara config doesn't like. RELNOTES=n/a ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=315774875
/* * Copyright (C) 2019 The Dagger Authors. * * 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 dagger.hilt.internal; import static java.lang.annotation.RetentionPolicy.CLASS; import dagger.hilt.GeneratesRootInput; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Annotation marking generated interfaces for entry points for which there is also a corresponding * generated Component. Component entry points differ from normal entry points in that they may be * filtered out in tests. */ @Target(ElementType.TYPE) @Retention(CLASS) @GeneratesRootInput // TODO(user): Rename and publicly strip these references out of hilt. public @interface ComponentEntryPoint {}
/* * Copyright (C) 2019 The Dagger Authors. * * 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 dagger.hilt.internal; import static java.lang.annotation.RetentionPolicy.CLASS; import dagger.hilt.GeneratesRootInput; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Annotation marking generated interfaces for entry points for which there is also a corresponding * generated Component. Component entry points differ from normal entry points in that they may be * filtered out in tests. */ @Target(ElementType.TYPE) @Retention(CLASS) @GeneratesRootInput // TODO(user): Rename and MOE strip these references out of hilt. public @interface ComponentEntryPoint {}
Test works only for locale=es_US.
/* * Copyright (C) 2010-2013 by PhonyTive LLC (http://phonytive.com) * http://astivetoolkit.org * * This file is part of Astive Toolkit(ATK) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.astivetoolkit.util.test; import java.util.Locale; import junit.framework.TestCase; import org.astivetoolkit.util.AppLocale; /** * Test case for {@link org.astivetoolkit.util.AppLocale}. * * @since 1.0.0 */ public class AppLocaleTest extends TestCase { /** * Creates a new AppLocaleTest object. */ public AppLocaleTest() { } /** * Test method. */ public void testAppLocale() { // This test only work if the Locale is English if(Locale.getDefault() == Locale.ENGLISH) { assertEquals(AppLocale.getI18n("messageTest", new Object[]{"test"}), "This is a test."); } } }
/* * Copyright (C) 2010-2013 by PhonyTive LLC (http://phonytive.com) * http://astivetoolkit.org * * This file is part of Astive Toolkit(ATK) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.astivetoolkit.util.test; import junit.framework.TestCase; import org.astivetoolkit.util.AppLocale; /** * Test case for {@link org.astivetoolkit.util.AppLocale}. * * @since 1.0.0 */ public class AppLocaleTest extends TestCase { /** * Creates a new AppLocaleTest object. */ public AppLocaleTest() { } /** * Test method. */ public void testAppLocale() { assertEquals(AppLocale.getI18n("messageTest", new Object[]{"test"}), "This is a test."); } }
Update language trove classifier list to include Python 3 The Python 3.x support is now reasonably well-tested (74% coverage), so this closes #5.
from setuptools import setup from timebook import get_version setup( name='timebook', version=get_version(), url='http://bitbucket.org/trevor/timebook/', description='track what you spend time on', author='Trevor Caira', author_email='trevor@caira.com', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Utilities', ], packages=['timebook'], install_requires=[ 'docopt==0.6.2', ], entry_points={'console_scripts': [ 't = timebook.cmdline:run_from_cmdline']}, )
from setuptools import setup from timebook import get_version setup( name='timebook', version=get_version(), url='http://bitbucket.org/trevor/timebook/', description='track what you spend time on', author='Trevor Caira', author_email='trevor@caira.com', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities', ], packages=['timebook'], install_requires=[ 'docopt==0.6.2', ], entry_points={'console_scripts': [ 't = timebook.cmdline:run_from_cmdline']}, )
Revert "Breaking change to test Travis" This reverts commit 795475b070ef56ce7d4ba50bce4f84a9b664b67b.
var test = require('tape'); var toDo = require('../libs/to-do-handler'); test('shouldGetToDoListForUsername', function(t) { t.plan(2); toDo.getToDoListForUsername('bhish', function(result) { var parsedToDo = result; var expected = [ ['Make to-do app', 'A to-do application should be made for doing fun to-do type doing stuff. And it should be done before xmas!', '20151224'], ['Admire to-do app', 'And then he read his to-dos, and, behold, it was very good.', '20151225'] ]; t.deepEqual(parsedToDo, expected); }); toDo.getToDoListForUsername('bart', function(result) { var parsedToDo = result; var expected = [ ['Annoy Homer', 'Annoy him really badly', '20160101'], ['Laugh at Milhouse', 'Because, why not?', '20160101'] ]; t.deepEqual(parsedToDo, expected); }); });
var test = require('tape'); var toDo = require('../libs/to-do-handler'); test('shouldGetToDoListForUsername', function(t) { t.plan(2); toDo.getToDoListForUsername('bhish', function(result) { var parsedToDo = result; var expected = [ ['Make to-do app', 'A to-do application should be made for doing fun to-do type doing stuff. And it should be done before xmas!', '20151224'], ['Admire to-do app', 'And then he read his to-dos, and, behold, it was very good.', '20151225'] ]; t.deepEqual(parsedToDo, expected); }); toDo.getToDoListForUsername('bart', function(result) { var parsedToDo = result; var expected = [ ['FLAnnoy Homer', 'Annoy him really badly', '20160101'], ['Laugh at Milhouse', 'Because, why not?', '20160101'] ]; t.deepEqual(parsedToDo, expected); }); });
Improve help messages from release_test
import argparse, common, sys, tests from features import check_features, get_features, FEATURES def arguments(argv=sys.argv[1:]): parser = argparse.ArgumentParser() names = [t.__name__.split('.')[1] for t in tests.__all__] names = ', '.join(names) parser.add_argument( 'tests', nargs='*', help='The list of tests to run. Tests are:' + names) features = ', '.join(FEATURES) parser.add_argument( '--features', '-f', default=[], action='append', help='A list of features separated by colons. Features are: ' + features) args = parser.parse_args(argv) if args.tests: all_tests = [(t, getattr(tests, t, None)) for t in args.tests] bad_tests = [t for (t, a) in all_tests if a is None] if bad_tests: raise ValueError('Bad test names: ' + ', '.join(bad_tests)) all_tests = tuple(a for (t, a) in all_tests) else: all_tests = tests.__all__ if args.features: features = set(':'.join(args.features).split(':')) check_features(features) else: features = get_features() return all_tests, features if __name__ == '__main__': common.printer(arguments())
import argparse, common, sys, tests from features import check_features, get_features def arguments(argv=sys.argv[1:]): parser = argparse.ArgumentParser() parser.add_argument( 'tests', nargs='*', help='The list of tests to run') parser.add_argument( '--features', '-f', default=[], action='append', help='A list of features separated by colons') args = parser.parse_args(argv) if args.tests: all_tests = [(t, getattr(tests, t, None)) for t in args.tests] bad_tests = [t for (t, a) in all_tests if a is None] if bad_tests: raise ValueError('Bad test names: ' + ', '.join(bad_tests)) all_tests = tuple(a for (t, a) in all_tests) else: all_tests = tests.__all__ if args.features: features = set(':'.join(args.features).split(':')) check_features(features) else: features = get_features() return all_tests, features if __name__ == '__main__': common.printer(arguments())
Enable logging for test environment
const dotenv = require('dotenv'); dotenv.config({silent: true}); const config = { "development": { "username": process.env.DB_DEV_USER, "password": process.env.DB_DEV_PASS, "database": process.env.DB_DEV_NAME, "host": process.env.DB_DEV_HOST, "secrete": process.env.AUTH_SECRETE, "dialect": "postgres" }, "test": { "username": process.env.DB_TEST_USER, "password": process.env.DB_TEST_PASS, "database": process.env.DB_TEST_NAME, "host": process.env.DB_TEST_HOST, "secrete": process.env.AUTH_SECRETE, "dialect": "postgres", }, "production": { "username": process.env.DB_USER, "password": process.env.DB_PASS, "database": process.env.DB_NAME, "host": process.env.DB_HOST, "secrete": process.env.AUTH_SECRETE, "dialect": "postgres", "logging": false } }; if(process.env.NODE_ENV === 'production'){ module.exports = config.production; }else if(process.env.NODE_ENV === 'test'){ module.exports = config.test; }else{ module.exports = config.development; }
const dotenv = require('dotenv'); dotenv.config({silent: true}); const config = { "development": { "username": process.env.DB_DEV_USER, "password": process.env.DB_DEV_PASS, "database": process.env.DB_DEV_NAME, "host": process.env.DB_DEV_HOST, "secrete": process.env.AUTH_SECRETE, "dialect": "postgres" }, "test": { "username": process.env.DB_TEST_USER, "password": process.env.DB_TEST_PASS, "database": process.env.DB_TEST_NAME, "host": process.env.DB_TEST_HOST, "secrete": process.env.AUTH_SECRETE, "dialect": "postgres", "logging": false }, "production": { "username": process.env.DB_USER, "password": process.env.DB_PASS, "database": process.env.DB_NAME, "host": process.env.DB_HOST, "secrete": process.env.AUTH_SECRETE, "dialect": "postgres", "logging": false } }; if(process.env.NODE_ENV === 'production'){ module.exports = config.production; }else if(process.env.NODE_ENV === 'test'){ module.exports = config.test; }else{ module.exports = config.development; }
Adjust package of SSPerformanceTest for latest Apache POI sources
package org.apache.poi.benchmark.suite; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Setup; import java.io.IOException; import java.util.concurrent.TimeUnit; public class SSPerformanceBenchmarks extends BaseBenchmark { @Setup public void setUp() throws IOException { compileAll(); } @Benchmark public void benchmarkHSSFPerformance() throws IOException { runPOIApplication("org.apache.poi.examples.ss.SSPerformanceTest", TimeUnit.HOURS.toMillis(1), "HSSF", "30000", "20", "0"); } @Benchmark public void benchmarkXSSFPerformance() throws IOException { runPOIApplication("org.apache.poi.examples.ss.SSPerformanceTest", TimeUnit.HOURS.toMillis(1), "XSSF", "30000", "20", "0"); } @Benchmark public void benchmarkSXSSFPerformance() throws IOException { runPOIApplication("org.apache.poi.examples.ss.SSPerformanceTest", TimeUnit.HOURS.toMillis(1), "SXSSF", "30000", "20", "0"); } }
package org.apache.poi.benchmark.suite; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Setup; import java.io.IOException; import java.util.concurrent.TimeUnit; public class SSPerformanceBenchmarks extends BaseBenchmark { @Setup public void setUp() throws IOException { compileAll(); } @Benchmark public void benchmarkHSSFPerformance() throws IOException { runPOIApplication("org.apache.poi.ss.examples.SSPerformanceTest", TimeUnit.HOURS.toMillis(1), "HSSF", "30000", "20", "0"); } @Benchmark public void benchmarkXSSFPerformance() throws IOException { runPOIApplication("org.apache.poi.ss.examples.SSPerformanceTest", TimeUnit.HOURS.toMillis(1), "XSSF", "30000", "20", "0"); } @Benchmark public void benchmarkSXSSFPerformance() throws IOException { runPOIApplication("org.apache.poi.ss.examples.SSPerformanceTest", TimeUnit.HOURS.toMillis(1), "SXSSF", "30000", "20", "0"); } }
BAP-11622: Optimize email body cleanup process - Add migration message queue
<?php namespace Oro\Bundle\EmailBundle\Migrations\Schema\v1_28; use Doctrine\DBAL\Schema\Schema; use Symfony\Component\DependencyInjection\ContainerAwareInterface; use Symfony\Component\DependencyInjection\ContainerInterface; use Oro\Bundle\MigrationBundle\Migration\Migration; use Oro\Bundle\MigrationBundle\Migration\QueryBag; class OroEmailBundle implements Migration, ContainerAwareInterface { /** @var ContainerInterface */ protected $container; /** * {@inheritdoc} */ public function setContainer(ContainerInterface $container = null) { $this->container = $container; } /** * {@inheritdoc} */ public function up(Schema $schema, QueryBag $queries) { static::addTextBodyFieldToEmailBodyTable($schema); // send migration message to queue $this->container->get('oro_message_queue.message_producer') ->send(UpgradeEmailBodyMessageProcessor::TOPIC_NAME, ''); } /** * @param Schema $schema */ public static function addTextBodyFieldToEmailBodyTable(Schema $schema) { $table = $schema->getTable('oro_email_body'); if (!$table->hasColumn('text_body')) { $table->addColumn('text_body', 'text', ['notnull' => false]); } } }
<?php namespace Oro\Bundle\EmailBundle\Migrations\Schema\v1_28; use Doctrine\DBAL\Schema\Schema; use Symfony\Component\DependencyInjection\ContainerAwareInterface; use Symfony\Component\DependencyInjection\ContainerInterface; use Oro\Bundle\MigrationBundle\Migration\Migration; use Oro\Bundle\MigrationBundle\Migration\QueryBag; class OroEmailBundle implements Migration, ContainerAwareInterface { /** @var ContainerInterface */ protected $container; /** * {@inheritdoc} */ public function setContainer(ContainerInterface $container = null) { $this->container = $container; } /** * {@inheritdoc} */ public function up(Schema $schema, QueryBag $queries) { static::addTextBodyFieldToEmailBodyTable($schema); // send migration message to queue $this->container->get('oro_message_queue.message_producer')->send('testTopic', ''); } /** * @param Schema $schema */ public static function addTextBodyFieldToEmailBodyTable(Schema $schema) { $table = $schema->getTable('oro_email_body'); if (!$table->hasColumn('text_body')) { $table->addColumn('text_body', 'text', ['notnull' => false]); } } }
Move threads column to the Put column after CPU, not at the end.
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddThreadsColumnToServersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('servers', function (Blueprint $table) { $table->string('threads')->nullable()->after('cpu'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('servers', function (Blueprint $table) { $table->dropColumn('threads'); }); } }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddThreadsColumnToServersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('servers', function (Blueprint $table) { $table->string('threads')->nullable(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('servers', function (Blueprint $table) { $table->dropColumn('threads'); }); } }
Fix JSHint issue with requirejs & require.
/* global requirejs */ /* global require */ function registerComponents(container) { var seen = requirejs._eak_seen; var templates = seen, match; if (!templates) { return; } for (var prop in templates) { if (match = prop.match(/components\/(.*)$/)) { require(prop, null, null, true); registerComponent(container, match[1]); } } } function registerComponent(container, name) { Ember.assert("You provided a template named 'components/" + name + "', but custom components must include a '-'", name.match(/-/)); var fullName = 'component:' + name, templateFullName = 'template:components/' + name; container.injection(fullName, 'layout', templateFullName); var Component = container.lookupFactory(fullName); if (!Component) { container.register(fullName, Ember.Component); Component = container.lookupFactory(fullName); } Ember.Handlebars.helper(name, Component); } export default registerComponents;
function registerComponents(container) { var seen = requirejs._eak_seen; var templates = seen, match; if (!templates) { return; } for (var prop in templates) { if (match = prop.match(/components\/(.*)$/)) { require(prop, null, null, true); registerComponent(container, match[1]); } } } function registerComponent(container, name) { Ember.assert("You provided a template named 'components/" + name + "', but custom components must include a '-'", name.match(/-/)); var fullName = 'component:' + name, templateFullName = 'template:components/' + name; container.injection(fullName, 'layout', templateFullName); var Component = container.lookupFactory(fullName); if (!Component) { container.register(fullName, Ember.Component); Component = container.lookupFactory(fullName); } Ember.Handlebars.helper(name, Component); } export default registerComponents;
Fix editor font size brokenness
import { SET_SETTINGS, EDITOR_DECREASE_FONT_SIZE, EDITOR_INCREASE_FONT_SIZE } from '../actions'; const MINIMUM_FONT_SIZE = 8; const initialState = { editorFontSize: 14, }; const settings = (state = initialState, action) => { // The settings is an object with an arbitrary set of properties. // The only property we don't want to copy is `type`, which is // only used in the reducer, here. Make sure we combine incoming // properties with existing properties. const settingsObj = Object.assign({}, state, action); delete settingsObj.type; switch (action.type) { case SET_SETTINGS: return { ...settingsObj, }; case EDITOR_DECREASE_FONT_SIZE: return { ...settingsObj, editorFontSize: Math.max(state.editorFontSize - 1, MINIMUM_FONT_SIZE), }; case EDITOR_INCREASE_FONT_SIZE: return { ...settingsObj, editorFontSize: state.editorFontSize + 1, }; default: return state; } }; export default settings;
import { SET_SETTINGS, EDITOR_DECREASE_FONT_SIZE, EDITOR_INCREASE_FONT_SIZE } from '../actions'; const initialState = {}; const MINIMUM_FONT_SIZE = 8; const settings = (state = initialState, action) => { // The settings is an object with an arbitrary set of properties. // The only property we don't want to copy is `type`, which is // only used in the reducer, here. Make sure we combine incoming // properties with existing properties. const settingsObj = Object.assign({}, state, action); delete settingsObj.type; switch (action.type) { case SET_SETTINGS: return { ...settingsObj, }; case EDITOR_DECREASE_FONT_SIZE: return { ...settingsObj, editorFontSize: Math.max(state.editorFontSize - 1, MINIMUM_FONT_SIZE), }; case EDITOR_INCREASE_FONT_SIZE: return { ...settingsObj, editorFontSize: state.editorFontSize + 1, }; default: return state; } }; export default settings;
Replace storybook-state usage from radio story with useState
import React, { useState } from 'react'; import { addStoryInGroup, LOW_LEVEL_BLOCKS } from '../../../.storybook/utils'; import { RadioGroup, RadioButton } from '../../index'; const values = ['Option one', 'Option two', 'Option three']; export default { component: RadioButton, title: addStoryInGroup(LOW_LEVEL_BLOCKS, 'Form elements/Radio'), parameters: { design: { type: 'figma', url: 'https://www.figma.com/file/LHH25GN90ljQaBEUNMsdJn/Desktop-components?node-id=6454%3A22776', }, }, }; export const DefaultStory = (args) => <RadioButton {...args} />; DefaultStory.args = { checked: true, label: 'I am the label', value: 'the_value', }; export const Group = () => { const [value, setValue] = useState('Option one'); const handleChange = (value) => { setValue(value); }; return ( <RadioGroup name="stringValue" onChange={handleChange} value={value}> {values.map((value, key) => ( <RadioButton key={key} marginVertical={3} label={value} value={value} /> ))} </RadioGroup> ); };
import React from 'react'; import { addStoryInGroup, LOW_LEVEL_BLOCKS } from '../../../.storybook/utils'; import { Store, State } from '@sambego/storybook-state'; import { RadioGroup, RadioButton } from '../../index'; const values = ['Option one', 'Option two', 'Option three']; const store = new Store({ value: 'Option one', }); const updateState = (value) => { store.set({ value }); }; export default { component: RadioButton, title: addStoryInGroup(LOW_LEVEL_BLOCKS, 'Form elements/Radio'), parameters: { design: { type: 'figma', url: 'https://www.figma.com/file/LHH25GN90ljQaBEUNMsdJn/Desktop-components?node-id=6454%3A22776', }, }, }; export const DefaultStory = (args) => <RadioButton {...args} />; DefaultStory.args = { checked: true, label: 'I am the label', value: 'the_value', }; export const Group = () => ( <State store={store}> <RadioGroup name="stringValue" onChange={updateState}> {values.map((value, key) => ( <RadioButton key={key} marginVertical={3} label={value} value={value} /> ))} </RadioGroup> </State> );
Change background related to search
import React, {Component} from 'react' import {bindActionCreators} from 'redux' import {connect} from 'react-redux' import Card from '../components/Card' import Search from '../components/Search' import * as appActions from '../actions' import './background-location.scss' class Main extends Component { componentDidMount() { const {weatherApp, dispatch} = this.props; dispatch(appActions.fetchLocations('London')) } render () { const {isFetching, isError, isLoaded, weatherApp, dispatch} = this.props; var location = weatherApp.background return ( <div className="backgound-location" style={{backgroundImage: 'url(' + location + ')'}}> <div className="mdl-layout"> <div className="mdl-grid"> <Search searchLocation={location => dispatch(appActions.fetchLocations(location))}/> </div> <div className="mdl-grid"> {!isFetching && <Card dailyWeather={weatherApp}/>} </div> </div> </div> ); } } function select(state) { return {weatherApp: state.location } } export default connect(select)(Main);
import React, {Component} from 'react' import {bindActionCreators} from 'redux' import {connect} from 'react-redux' import Card from '../components/Card' import Search from '../components/Search' import * as appActions from '../actions' import './background-location.scss' class Main extends Component { componentDidMount() { const {weatherApp, dispatch} = this.props; dispatch(appActions.fetchLocations('London')) } render () { const {isFetching, isError, isLoaded, weatherApp, dispatch} = this.props; return ( <div className="backgound-location"> <div className="mdl-layout"> <div className="mdl-grid"> <Search searchLocation={location => dispatch(appActions.fetchLocations(location))}/> </div> <div className="mdl-grid"> {!isFetching && <Card dailyWeather={weatherApp}/>} </div> </div> </div> ); } } function select(state) { return {weatherApp: state.weather} } export default connect(select)(Main);
Adjust form templatetag to handle missing field var When a non-existant field gets passed, the templatetag was raising an unseemly AttributeError. This change checks to see if the passed var is actually a form field to avoid said error.
from django import template register = template.Library() @register.tag def annotate_form_field(parser, token): """ Set an attribute on a form field with the widget type This means templates can use the widget type to render things differently if they want to. Django doesn't make this available by default. """ args = token.split_contents() if len(args) < 2: raise template.TemplateSyntaxError( "annotate_form_field tag requires a form field to be passed") return FormFieldNode(args[1]) class FormFieldNode(template.Node): def __init__(self, field_str): self.field = template.Variable(field_str) def render(self, context): field = self.field.resolve(context) if hasattr(field, 'field'): field.widget_type = field.field.widget.__class__.__name__ return ''
from django import template register = template.Library() @register.tag def annotate_form_field(parser, token): """ Set an attribute on a form field with the widget type This means templates can use the widget type to render things differently if they want to. Django doesn't make this available by default. """ args = token.split_contents() if len(args) < 2: raise template.TemplateSyntaxError( "annotate_form_field tag requires a form field to be passed") return FormFieldNode(args[1]) class FormFieldNode(template.Node): def __init__(self, field_str): self.field = template.Variable(field_str) def render(self, context): field = self.field.resolve(context) field.widget_type = field.field.widget.__class__.__name__ return ''
Change Dotenv contruction to app root directory
<?php require __DIR__.'/../../vendor/autoload.php'; require 'path.php'; $dotenv = new Dotenv\Dotenv(dirname(dirname(__DIR__))); $dotenv->load(); date_default_timezone_set(getenv('DATE_TIMEZONE') ?: 'Asia/Jakarta'); use Illuminate\Database\Capsule\Manager as Capsule; $capsule = new Capsule; $capsule->addConnection(array( 'driver' => getenv('DRIVER_ELOQUENT') ?: 'mysql', 'host' => getenv('DB_HOST') ?: 'localhost', 'database' => getenv('DB_DATABASE') ?: 'homestead', 'username' => getenv('DB_USERNAME') ?: 'homestead', 'password' => getenv('DB_PASSWORD') ?: 'secret', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => getenv('DB_PREFIX') ?: '', )); foreach (glob(__DIR__ . '/db_*.php') as $filedb) { include $filedb; } $capsule->setAsGlobal(); $capsule->bootEloquent();
<?php require __DIR__.'/../../vendor/autoload.php'; require 'path.php'; $dotenv = new Dotenv\Dotenv(dirname(__DIR__)); $dotenv->load(); date_default_timezone_set(getenv('DATE_TIMEZONE') ?: 'Asia/Jakarta'); use Illuminate\Database\Capsule\Manager as Capsule; $capsule = new Capsule; $capsule->addConnection(array( 'driver' => getenv('DRIVER_ELOQUENT') ?: 'mysql', 'host' => getenv('DB_HOST') ?: 'localhost', 'database' => getenv('DB_DATABASE') ?: 'homestead', 'username' => getenv('DB_USERNAME') ?: 'homestead', 'password' => getenv('DB_PASSWORD') ?: 'secret', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => getenv('DB_PREFIX') ?: '', )); foreach (glob(__DIR__ . '/db_*.php') as $filedb) { include $filedb; } $capsule->setAsGlobal(); $capsule->bootEloquent();
Make it so a parameter is required for the test to pass.
// 26: class - more-extends // To do: make all tests pass, leave the assert lines unchanged! describe('class can inherit from another', () => { it('extend an `old style` "class", a function, still works', () => { let A; class B extends A {} assert.equal(new B() instanceof A, true); }); describe('prototypes are as you know them', () => { class A {} class B extends A {} it('A is the prototype of B', () => { const isIt = A.isPrototypeOf(null); assert.equal(isIt, true); }); it('A`s prototype is also B`s prototype', () => { const proto = B; // Remember: don't touch the assert!!! :) assert.equal(A.prototype.isPrototypeOf(proto), true); }); }); describe('`extends` using an expression', () => { it('like the inline assignment of the parent class', () => { let A; class B extends (A = {}) {} assert.equal(new B() instanceof A, true); }); it('or calling a function that returns the parent class', () => { const returnParent = (beNull) => beNull ? null : class {}; class B extends (returnParent) {} assert.equal(Object.getPrototypeOf(B.prototype), null); }); }); });
// 26: class - more-extends // To do: make all tests pass, leave the assert lines unchanged! describe('class can inherit from another', () => { it('extend an `old style` "class", a function, still works', () => { let A; class B extends A {} assert.equal(new B() instanceof A, true); }); describe('prototypes are as you know them', () => { class A {} class B extends A {} it('A is the prototype of B', () => { const isIt = A.isPrototypeOf(null); assert.equal(isIt, true); }); it('A`s prototype is also B`s prototype', () => { const proto = B; // Remember: don't touch the assert!!! :) assert.equal(A.prototype.isPrototypeOf(proto), true); }); }); describe('`extends` using an expression', () => { it('like the inline assignment of the parent class', () => { let A; class B extends (A = {}) {} assert.equal(new B() instanceof A, true); }); it('or calling a function that returns the parent class', () => { const returnParent = (classOrNot) => classOrNot ? class {} : null; class B extends (returnParent) {} assert.equal(Object.getPrototypeOf(B.prototype), null); }); }); });
[JENKINS-25940] Add workaround to prevent NPE in Maven projects
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package hudson.plugins.emailext; import java.util.Collection; import java.util.Collections; import hudson.Extension; import hudson.model.AbstractProject; import hudson.model.Action; import hudson.model.TransientProjectActionFactory; /** * * @author acearl */ @Extension public class EmailExtTemplateActionFactory extends TransientProjectActionFactory { @Override public Collection<? extends Action> createFor(AbstractProject target) { boolean hasEmailExt = false; if (target.getPublishersList() != null) { for(Object p : target.getPublishersList()) { if(p instanceof ExtendedEmailPublisher) { hasEmailExt = true; break; } } } if(hasEmailExt) { return Collections.singletonList(new EmailExtTemplateAction(target)); } return Collections.EMPTY_LIST; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package hudson.plugins.emailext; import java.util.Collection; import java.util.Collections; import hudson.Extension; import hudson.model.AbstractProject; import hudson.model.Action; import hudson.model.TransientProjectActionFactory; /** * * @author acearl */ @Extension public class EmailExtTemplateActionFactory extends TransientProjectActionFactory { @Override public Collection<? extends Action> createFor(AbstractProject target) { boolean hasEmailExt = false; for(Object p : target.getPublishersList()) { if(p instanceof ExtendedEmailPublisher) { hasEmailExt = true; break; } } if(hasEmailExt) { return Collections.singletonList(new EmailExtTemplateAction(target)); } return Collections.EMPTY_LIST; } }
Set SO_REUSEADDR in client test.
#!/usr/bin/python # Test whether a client produces a correct connect and subsequent disconnect. import os import subprocess import socket import sys import time from struct import * rc = 1 keepalive = 60 connect_packet = pack('!BBH6sBBHH21s', 16, 12+2+21,6,"MQIsdp",3,2,keepalive,21,"01-con-discon-success") connack_packet = pack('!BBBB', 32, 2, 0, 0); sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(('', 1888)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' client = subprocess.Popen(client_args, env=env) try: (conn, address) = sock.accept() connect_recvd = conn.recv(256) if connect_recvd != connect_packet: print("FAIL: Received incorrect connect.") print("Received: "+connect_recvd+" length="+str(len(connect_recvd))) print("Expected: "+connect_packet+" length="+str(len(connect_packet))) else: rc = 0 conn.close() finally: client.terminate() client.wait() sock.close() exit(rc)
#!/usr/bin/python # Test whether a client produces a correct connect and subsequent disconnect. import os import subprocess import socket import sys import time from struct import * rc = 1 keepalive = 60 connect_packet = pack('!BBH6sBBHH21s', 16, 12+2+21,6,"MQIsdp",3,2,keepalive,21,"01-con-discon-success") connack_packet = pack('!BBBB', 32, 2, 0, 0); sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('', 1888)) sock.listen(5) client_args = sys.argv[1:] env = dict(os.environ) env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp' client = subprocess.Popen(client_args, env=env) try: (conn, address) = sock.accept() connect_recvd = conn.recv(256) if connect_recvd != connect_packet: print("FAIL: Received incorrect connect.") print("Received: "+connect_recvd+" length="+str(len(connect_recvd))) print("Expected: "+connect_packet+" length="+str(len(connect_packet))) else: rc = 0 finally: client.terminate() client.wait() exit(rc)
Change env var name to match our new standard This environment variable was not getting used previously, and was only put in because we knew we would eventually start using it. However, when we started using it we decided to simply make it 'CODE_VERSION' instead of 'DEPLOYED_CODE_VERSION'.
'use strict'; var RB = require('./ResponseBuilder'); module.exports = RB.extend({ init: function() { var now = new Date(), builtOn = []; this._super(); this.allowCORS(); this.supportJSONP('callback'); this.cacheForMinutes(30); builtOn.push(process.env.AWS_REGION); builtOn.push(process.env.AWS_LAMBDA_FUNCTION_NAME); builtOn.push(process.env.AWS_LAMBDA_FUNCTION_VERSION); builtOn.push(process.env.CODE_VERSION); this.header('X-Built-On', builtOn.join(':')); this.header('X-Page-Built', now.toUTCString()); }, toResponse: function(req) { this.header('X-Elapsed-Millis', new Date().getTime() - req.started()); this.header('X-RequestID', req.context('awsRequestId')); return this._super(req); }, });
'use strict'; var RB = require('./ResponseBuilder'); module.exports = RB.extend({ init: function() { var now = new Date(), builtOn = []; this._super(); this.allowCORS(); this.supportJSONP('callback'); this.cacheForMinutes(30); builtOn.push(process.env.AWS_REGION); builtOn.push(process.env.AWS_LAMBDA_FUNCTION_NAME); builtOn.push(process.env.AWS_LAMBDA_FUNCTION_VERSION); builtOn.push(process.env.DEPLOYED_CODE_VERSION); this.header('X-Built-On', builtOn.join(':')); this.header('X-Page-Built', now.toUTCString()); }, toResponse: function(req) { this.header('X-Elapsed-Millis', new Date().getTime() - req.started()); this.header('X-RequestID', req.context('awsRequestId')); return this._super(req); }, });
Add a projectile hit handler, and allow for hit FX on projectiles
package com.elmakers.mine.bukkit.api.spell; import org.bukkit.Location; import org.bukkit.command.CommandSender; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.util.Vector; /** * Represents a Spell that may be cast by a Mage. * * Each Spell is based on a SpellTemplate, which are defined * by the spells configuration files. * * Every spell uses a specific Class that must extend from * com.elmakers.mine.bukkit.plugins.magic.spell.Spell. * * To create a new custom spell from scratch, you must also * implement the MageSpell interface. */ public interface Spell extends SpellTemplate { public boolean cast(); public boolean cast(String[] parameters); public boolean cast(String[] parameters, Location defaultLocation); public Location getLocation(); public void target(); public Location getTargetLocation(); public Entity getTargetEntity(); public Vector getDirection(); public boolean canTarget(Entity entity); public boolean isActive(); public boolean hasBrushOverride(); public boolean canCast(Location location); public long getRemainingCooldown(); public CastingCost getRequiredCost(); public void playEffects(String effectName, float scale, Location source, Entity sourceEntity, Location target, Entity targetEntity); }
package com.elmakers.mine.bukkit.api.spell; import org.bukkit.Location; import org.bukkit.command.CommandSender; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.util.Vector; /** * Represents a Spell that may be cast by a Mage. * * Each Spell is based on a SpellTemplate, which are defined * by the spells configuration files. * * Every spell uses a specific Class that must extend from * com.elmakers.mine.bukkit.plugins.magic.spell.Spell. * * To create a new custom spell from scratch, you must also * implement the MageSpell interface. */ public interface Spell extends SpellTemplate { public boolean cast(); public boolean cast(String[] parameters); public boolean cast(String[] parameters, Location defaultLocation); public Location getLocation(); public void target(); public Location getTargetLocation(); public Entity getTargetEntity(); public Vector getDirection(); public boolean canTarget(Entity entity); public boolean isActive(); public boolean hasBrushOverride(); public boolean canCast(Location location); public long getRemainingCooldown(); public CastingCost getRequiredCost(); }
Return the status line of response header.
package org.yukung.sandbox.http; import static org.yukung.sandbox.http.HttpRequest.CRLF; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.net.ServerSocket; import java.net.Socket; /** * @author yukung */ public class Main { public static void main(String[] args) throws IOException { System.out.println("start >>>"); try ( ServerSocket ss = new ServerSocket(8080); Socket socket = ss.accept(); InputStream in = socket.getInputStream(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())) ) { HttpRequest request = new HttpRequest(in); System.out.println(request.getHeaderText()); System.out.println(request.getBodyText()); bw.write("HTTP/1.1 200 OK" + CRLF); } System.out.println("<<< end"); } }
package org.yukung.sandbox.http; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; /** * @author yukung */ public class Main { public static void main(String[] args) throws IOException { System.out.println("start >>>"); try ( ServerSocket ss = new ServerSocket(8080); Socket socket = ss.accept(); InputStream in = socket.getInputStream() ) { HttpRequest request = new HttpRequest(in); System.out.println(request.getHeaderText()); System.out.println(request.getBodyText()); } System.out.println("<<< end"); } }
Remove unnecessary logging, emit card click data as object
"use strict"; var socket = io(); var username; $(window).load(function() { username = prompt("Please enter your name"); socket.emit('log on', username); }); $(window).on('beforeunload', function() { socket.emit('log off', username); }); function userActivity(name, joinedOrLeft) { alert(name + " " + joinedOrLeft + " the game"); } socket.on('log on', function(name) { userActivity(name, "joined"); }); socket.on('log off', function(name) { userActivity(name, "left"); }); function getCardID(targetNode) { if (targetNode.className === 'card') { return targetNode.id; } else { return getCardID(targetNode.parentNode); } } $('.card').click(function(event) { var cardID = getCardID(event.target); console.log(username, "clicked card", cardID); socket.emit('card click', {'user':username, 'card':cardID}); });
"use strict"; var socket = io(); var username; $(window).load(function() { username = prompt("Please enter your name"); socket.emit('log on', username); }); $(window).on('beforeunload', function() { socket.emit('log off', username); }); function userActivity(name, joinedOrLeft) { alert(name + " " + joinedOrLeft + " the game"); } socket.on('log on', function(name) { userActivity(name, "joined"); }); socket.on('log off', function(name) { userActivity(name, "left"); }); function getCardID(targetNode) { console.log(targetNode); if (targetNode.className === 'card') { return targetNode.id; } else { return getCardID(targetNode.parentNode); } } $('.card').click(function(event) { var cardID = getCardID(event.target); console.log(username, "clicked card", cardID); socket.emit('card click', username, cardID); });
Fix initializing logger in wizards plugin
package org.perfclipse.wizards; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.BundleContext; import org.perfclipse.core.logging.Logger; /** * The activator class controls the plug-in life cycle */ public class Activator extends AbstractUIPlugin { private Logger logger; // The plug-in ID public static final String PLUGIN_ID = "org.perfclipse.wizards"; //$NON-NLS-1$ // The shared instance private static Activator plugin; /** * The constructor */ public Activator() { } /* * (non-Javadoc) * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext) */ public void start(BundleContext context) throws Exception { super.start(context); plugin = this; logger = new Logger(getLog(), PLUGIN_ID); } /* * (non-Javadoc) * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext) */ public void stop(BundleContext context) throws Exception { plugin = null; super.stop(context); } /** * Returns the shared instance * * @return the shared instance */ public static Activator getDefault() { return plugin; } public Logger getLogger() { return logger; } }
package org.perfclipse.wizards; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.BundleContext; import org.perfclipse.core.logging.Logger; /** * The activator class controls the plug-in life cycle */ public class Activator extends AbstractUIPlugin { private Logger logger; // The plug-in ID public static final String PLUGIN_ID = "org.perfclipse.wizards"; //$NON-NLS-1$ // The shared instance private static Activator plugin; /** * The constructor */ public Activator() { } /* * (non-Javadoc) * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext) */ public void start(BundleContext context) throws Exception { super.start(context); plugin = this; } /* * (non-Javadoc) * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext) */ public void stop(BundleContext context) throws Exception { plugin = null; super.stop(context); } /** * Returns the shared instance * * @return the shared instance */ public static Activator getDefault() { return plugin; } public Logger getLogger() { return logger; } }
Correct version for deploy to GAE
//Command to run test version: //goapp serve app.yaml //Command to deploy/update application: //goapp deploy -application golangnode0 -version 0 package main import ( "fmt" "net/http" ) func helloWorld(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello World!") } func startPage(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Hello, test application started.\n - /helloworld - show title page\n - /showinfo - show information about this thing") } func showInfo(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Inforamtion page for test project.\nLanguage - Go\nPlatform - Google Application Engine") } func init() { http.HandleFunc("/", startPage) http.HandleFunc("/helloworld", helloWorld) http.HandleFunc("/showinfo", showInfo) //Wrong code for App Enine - server cant understand what it need to show //http.ListenAndServe(":80", nil) } /* func main() { fmt.Println("Hello, test server started on 80 port.\n - /helloworld - show title page\n - /showinfo - show information about this thing") http.HandleFunc("/", startPage) http.HandleFunc("/helloworld", helloWorld) http.HandleFunc("/showinfo", showInfo) http.ListenAndServe(":80", nil) } */
//Command to run test version: //goapp serve app.yaml //Command to deploy/update application: //goapp deploy -application golangnode0 -version 0 package main import ( "fmt" "net/http" ) func helloWorld(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello World!") } func startPage(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Hello, test server started on 8080 port.\n - /helloworld - show title page\n - /showinfo - show information about this thing") } func showInfo(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Inforamtion page for test project.\nLanguage - Go\nPlatform - Google Application Engine") } func init() { http.HandleFunc("/", startPage) http.HandleFunc("/helloworld", helloWorld) http.HandleFunc("/showinfo", showInfo) //Wrong code for App Enine - server cant understand what it need to show //http.ListenAndServe(":80", nil) } /* func main() { fmt.Println("Hello, test server started on 80 port.\n - /helloworld - show title page\n - /showinfo - show information about this thing") http.HandleFunc("/", startPage) http.HandleFunc("/helloworld", helloWorld) http.HandleFunc("/showinfo", showInfo) http.ListenAndServe(":80", nil) } */
Make db a required option
package app import ( "database/sql" "github.com/goph/stdlib/errors" "github.com/goph/stdlib/log" ) // ServiceOption sets options in the Service. type ServiceOption func(s *Service) // Logger returns a ServiceOption that sets the logger for the service. func Logger(l log.Logger) ServiceOption { return func(s *Service) { s.logger = l } } // ErrorHandler returns a ServiceOption that sets the error handler for the service. func ErrorHandler(l errors.Handler) ServiceOption { return func(s *Service) { s.errorHandler = l } } // Service contains the main controller logic. type Service struct { db *sql.DB logger log.Logger errorHandler errors.Handler } // NewService creates a new service object. func NewService(db *sql.DB, opts ...ServiceOption) *Service { s := new(Service) s.db = db for _, opt := range opts { opt(s) } // Default logger if s.logger == nil { s.logger = log.NewNopLogger() } // Default error handler if s.errorHandler == nil { s.errorHandler = errors.NewNopHandler() } return s }
package app import ( "database/sql" "github.com/goph/stdlib/errors" "github.com/goph/stdlib/log" ) // ServiceOption sets options in the Service. type ServiceOption func(s *Service) // DB returns a ServiceOption that sets the DB object for the service. func DB(db *sql.DB) ServiceOption { return func(s *Service) { s.db = db } } // Logger returns a ServiceOption that sets the logger for the service. func Logger(l log.Logger) ServiceOption { return func(s *Service) { s.logger = l } } // ErrorHandler returns a ServiceOption that sets the error handler for the service. func ErrorHandler(l errors.Handler) ServiceOption { return func(s *Service) { s.errorHandler = l } } // Service contains the main controller logic. type Service struct { db *sql.DB logger log.Logger errorHandler errors.Handler } // NewService creates a new service object. func NewService(opts ...ServiceOption) *Service { s := new(Service) for _, opt := range opts { opt(s) } // Default logger if s.logger == nil { s.logger = log.NewNopLogger() } // Default error handler if s.errorHandler == nil { s.errorHandler = errors.NewNopHandler() } return s }
Remove the lazy signup backend's hard dependency on django.contrib.auth.user (and remove the inconsistency in checking for whether a user is lazy or not).
from django.contrib.auth.backends import ModelBackend from lazysignup.models import LazyUser class LazySignupBackend(ModelBackend): def authenticate(self, username=None): lazy_users = LazyUser.objects.filter( user__username=username ).select_related('user') try: return lazy_users[0].user except IndexError: return None def get_user(self, user_id): # Annotate the user with our backend so it's always available, # not just when authenticate() has been called. This will be # used by the is_lazy_user filter. user = super(LazySignupBackend, self).get_user(user_id) if user: user.backend = 'lazysignup.backends.LazySignupBackend' return user
from django.contrib.auth.backends import ModelBackend from django.contrib.auth.models import User class LazySignupBackend(ModelBackend): def authenticate(self, username=None): users = [u for u in User.objects.filter(username=username) if not u.has_usable_password()] if len(users) != 1: return None return users[0] def get_user(self, user_id): # Annotate the user with our backend so it's always available, # not just when authenticate() has been called. This will be # used by the is_lazy_user filter. user = super(LazySignupBackend, self).get_user(user_id) if user: user.backend = 'lazysignup.backends.LazySignupBackend' return user
Allow version check to actually run on older node versions
#!/usr/bin/env node // eslint messages suppressed to allow this to work // in older node versions. /* eslint-disable strict */ /* eslint-disable no-var */ /* eslint-disable no-console */ /* eslint-disable prefer-template */ 'use strict'; // A simple check that node + npm versions // meet the expected minimums. var exec = require('shelljs').exec; var chalk = require('chalk'); var semver = require('semver'); var MIN_NODE_VERSION = 4; var MIN_NPM_VERSION = 3; var NODE_VERSION = process.versions.node; var NPM_VERSION = exec('npm --version', {silent: true}).stdout; var versionCheckPassed = true; if (semver.major(NODE_VERSION) < MIN_NODE_VERSION) { console.log(chalk.red('Node version must be at least: ' + MIN_NODE_VERSION)); versionCheckPassed = false; } if (semver.major(NPM_VERSION) < MIN_NPM_VERSION) { console.log(chalk.red('NPM version must be at least: ' + MIN_NPM_VERSION)); versionCheckPassed = false; } if (versionCheckPassed === false) { process.exit(1); }
#!/usr/bin/env node /* eslint-disable strict */ /* eslint-disable no-console */ /* eslint-disable prefer-template */ 'use strict'; // A simple check that node + npm versions // meet the expected minimums. const exec = require('shelljs').exec; const chalk = require('chalk'); const semver = require('semver'); const MIN_NODE_VERSION = 4; const MIN_NPM_VERSION = 3; const NODE_VERSION = process.versions.node; const NPM_VERSION = exec('npm --version', {silent: true}).stdout; let versionCheckPassed = true; if (semver.major(NODE_VERSION) < MIN_NODE_VERSION) { console.log(chalk.red('Node version must be at least: ' + MIN_NODE_VERSION)); versionCheckPassed = false; } if (semver.major(NPM_VERSION) < MIN_NPM_VERSION) { console.log(chalk.red('NPM version must be at least: ' + MIN_NPM_VERSION)); versionCheckPassed = false; } if (versionCheckPassed === false) { process.exit(1); }
Add test for reordering elements in an Array.
describe("Utilities", function() { it("should get the domain", function() { expect(getDomain('http://www.google.com')).toMatch('www.google.com'); expect(getDomain('http://www.google.com/')).toMatch('www.google.com'); expect(getDomain('http://www.google.com/kitty')).toMatch('www.google.com'); expect(getDomain('https://www.google.com')).toMatch('www.google.com'); expect(getDomain('https://www.google.com/')).toMatch('www.google.com'); expect(getDomain('https://www.google.com/kitty')).toMatch('www.google.com'); }); it("should get the hostname", function() { expect(getDomain('http://www.google.com')).toMatch('google.com'); expect(getDomain('http://www.google.com/')).toMatch('google.com'); expect(getDomain('http://www.google.com/kitty')).toMatch('google.com'); expect(getDomain('https://www.google.com')).toMatch('google.com'); expect(getDomain('https://www.google.com/')).toMatch('google.com'); expect(getDomain('https://www.google.com/kitty')).toMatch('google.com'); }); }); describe("An array", function() { it("should insert an element at an arbitrary index", function() { var arr = [1, 2, 3, 4]; arr.insertAtIndex(0, 1); expect(arr).toEqual([1, 0, 2, 3, 4]); }); });
describe("Utilities", function() { it("should get the domain", function() { expect(getDomain('http://www.google.com')).toMatch('www.google.com'); expect(getDomain('http://www.google.com/')).toMatch('www.google.com'); expect(getDomain('http://www.google.com/kitty')).toMatch('www.google.com'); expect(getDomain('https://www.google.com')).toMatch('www.google.com'); expect(getDomain('https://www.google.com/')).toMatch('www.google.com'); expect(getDomain('https://www.google.com/kitty')).toMatch('www.google.com'); }); it("should get the hostname", function() { expect(getDomain('http://www.google.com')).toMatch('google.com'); expect(getDomain('http://www.google.com/')).toMatch('google.com'); expect(getDomain('http://www.google.com/kitty')).toMatch('google.com'); expect(getDomain('https://www.google.com')).toMatch('google.com'); expect(getDomain('https://www.google.com/')).toMatch('google.com'); expect(getDomain('https://www.google.com/kitty')).toMatch('google.com'); }); });
Fix django logger issue when error has no attached request object
import copy import logging import traceback def dump(obj): for attr in dir(obj): print("obj.%s = %r" % (attr, getattr(obj, attr))) def dump_request_summary(request): user = request.user.username if request.user.is_authenticated() else '' url = request.path method = request.method body = censor_sensitive_fields(dict(getattr(request, method))) return '({user}) {method} {url} {body}'.format(user=user, url=url, method=method, body=body) sensitive_fields = ['password', 'password1', 'password2'] def censor_sensitive_fields(fields_dict): fields_copy = copy.deepcopy(fields_dict) for field in sensitive_fields: if field in fields_copy: censored_length = len(fields_copy[field][0]) fields_copy[field][0] = '*' * censored_length return fields_copy class CustomErrorHandler(logging.Handler): def emit(self, record): error_msg = 'ERROR: {}'.format(traceback.format_exc()) if hasattr(record, 'request'): error_msg += ' REQUEST: {}'.format(dump_request_summary(record.request)) print(error_msg)
import copy import logging import traceback def dump(obj): for attr in dir(obj): print("obj.%s = %r" % (attr, getattr(obj, attr))) def dump_request_summary(request): user = request.user.username if request.user.is_authenticated() else '' url = request.path method = request.method body = censor_sensitive_fields(dict(getattr(request, method))) return '({user}) {method} {url} {body}'.format(user=user, url=url, method=method, body=body) sensitive_fields = ['password', 'password1', 'password2'] def censor_sensitive_fields(fields_dict): fields_copy = copy.deepcopy(fields_dict) for field in sensitive_fields: if field in fields_copy: censored_length = len(fields_copy[field][0]) fields_copy[field][0] = '*' * censored_length return fields_copy class CustomErrorHandler(logging.Handler): def emit(self, record): exception_info = traceback.format_exc() request_info = dump_request_summary(record.request) print('ERROR: {exception_info} REQUEST: {request_info}'.format(exception_info=exception_info, request_info=request_info))
Improve unicode for motivational texts
from django.db import models from patient.models import Patient from django.utils.encoding import smart_unicode class MotivationText(models.Model): patient = models.ForeignKey(Patient, null=False) text = models.TextField(default='', blank=False) time_created = models.DateTimeField(null=False, auto_now_add=True, auto_now=False) def __unicode__(self): return smart_unicode( ("InformationText" if self.type == 'I' else 'MotivationText') + " for " + self.patient.user.get_full_name() + " created at " + str(self.time_created) ) class Meta(): ordering = ['-id'] TEXT_INFORMATION = 'I' TEXT_MOTIVATION = 'M' TYPES = [ (TEXT_INFORMATION, 'InformationText'), (TEXT_MOTIVATION, 'MotivationText'), ] type = models.CharField(max_length=1, choices=TYPES, null=False, default='M')
from django.db import models from patient.models import Patient from django.utils.encoding import smart_unicode class MotivationText(models.Model): patient = models.ForeignKey(Patient, null=False) text = models.TextField(default='', blank=False) time_created = models.DateTimeField(null=False, auto_now_add=True, auto_now=False) def __unicode__(self): return smart_unicode( "Motivational text for " + self.patient.user.first_name + " " + self.patient.user.last_name + " created at " + str(self.time_created) ) class Meta(): ordering = ['-id'] TEXT_INFORMATION = 'I' TEXT_MOTIVATION = 'M' TYPES = [ (TEXT_INFORMATION, 'InformationText'), (TEXT_MOTIVATION, 'MotivationText'), ] type = models.CharField(max_length=1, choices=TYPES, null=False, default='M')
Fix a bug in Node.js
/** * Add shim config for configuring the dependencies and exports for * older, traditional "browser globals" scripts that do not use define() * to declare the dependencies and set a module value. */ (function(seajs, global) { // seajs.config({ // shim: { // "jquery": { // src: "lib/jquery.js", // exports: "jQuery" or function // }, // "jquery.easing": { // src: "lib/jquery.easing.js", // deps: ["jquery"] // } // }) seajs.on("config", onConfig) onConfig(seajs.config.data) function onConfig(data) { if (!data) return var shim = data.shim for (var id in shim) { (function(item) { // Set dependencies item.deps && define(item.src, item.deps) // Define the proxy cmd module define(id, [item.src], function() { var exports = item.exports return typeof exports === "function" ? exports() : typeof exports === "string" ? global[exports] : exports }) })(shim[id]) } } })(seajs, typeof global === "undefined" ? this : global);
/** * Add shim config for configuring the dependencies and exports for * older, traditional "browser globals" scripts that do not use define() * to declare the dependencies and set a module value. */ (function(seajs, global) { // seajs.config({ // shim: { // "jquery": { // src: "lib/jquery.js", // exports: "jQuery" or function // }, // "jquery.easing": { // src: "lib/jquery.easing.js", // deps: ["jquery"] // } // }) seajs.on("config", onConfig) onConfig(seajs.config.data) function onConfig(data) { if (!data) return var shim = data.shim for (var id in shim) { (function(item) { // Set dependencies item.deps && define(item.src, item.deps) // Define the proxy cmd module define(id, [item.src], function() { var exports = item.exports return typeof exports === "function" ? exports() : typeof exports === "string" ? global[exports] : exports }) })(shim[id]) } } })(seajs, this);
Fix tests for PHP < 5.5
<?php namespace Omnipay\Swish\Message; use Omnipay\Common\Message\AbstractResponse; use Omnipay\Common\Message\RequestInterface; class PurchaseResponse extends AbstractResponse { protected $statusCode; protected $response; public function __construct(RequestInterface $request, $response, $data, $statusCode) { parent::__construct($request, $data); $this->statusCode = $statusCode; $this->response = $response; } public function isSuccessful() { return ($this->getCode() == 200 || $this->getCode() == 201); } public function getTransactionReference() { $location = $this->response->getHeader('location'); if (!empty($location)) { $urlParts = explode('/', $location); return end($urlParts); } return null; } public function getMessage() { if (isset($this->data[0]['errorMessage'])) { return $this->data[0]['errorMessage']; } return null; } public function getCode() { return $this->statusCode; } }
<?php namespace Omnipay\Swish\Message; use Omnipay\Common\Message\AbstractResponse; use Omnipay\Common\Message\RequestInterface; class PurchaseResponse extends AbstractResponse { protected $statusCode; protected $response; public function __construct(RequestInterface $request, $response, $data, $statusCode) { parent::__construct($request, $data); $this->statusCode = $statusCode; $this->response = $response; } public function isSuccessful() { return ($this->getCode() == 200 || $this->getCode() == 201); } public function getTransactionReference() { if (!empty($location = $this->response->getHeader('location'))) { $urlParts = explode('/', $location); return end($urlParts); } return null; } public function getMessage() { if (isset($this->data[0]['errorMessage'])) { return $this->data[0]['errorMessage']; } return null; } public function getCode() { return $this->statusCode; } }
Add bearer to qp token
'use strict'; var authHeader = require('auth-header'); var tokenUtils = require('./token'); module.exports = function (options) { return function (req, res, next) { var authorization = req.get('authorization') || 'Bearer ' + req.query.token; req.challenge = authorization; var auth = authHeader.parse(authorization); if (auth && auth.values && auth.values.length) { auth = auth.values[0]; if (auth.scheme !== 'Bearer') { return res.status(400).json('Invalid authorization scheme, expected \'Bearer\''); } tokenUtils.decode(auth.token, options, function (err, decoded) { if (err) { console.error(err); req.authenticated = false; req.authentication = err; } else { req.authenticated = true; req.authentication = decoded; } next(); }); } else { return res.status(400).json('Authorization token is missing'); } }; };
'use strict'; var authHeader = require('auth-header'); var tokenUtils = require('./token'); module.exports = function (options) { return function (req, res, next) { var authorization = req.get('authorization') || req.query.token; req.challenge = authorization; var auth = authHeader.parse(authorization); if (auth && auth.values && auth.values.length) { auth = auth.values[0]; if (auth.scheme !== 'Bearer') { return res.status(400).json('Invalid authorization scheme, expected \'Bearer\''); } tokenUtils.decode(auth.token, options, function (err, decoded) { if (err) { console.error(err); req.authenticated = false; req.authentication = err; } else { req.authenticated = true; req.authentication = decoded; } next(); }); } else { return res.status(400).json('Authorization token is missing'); } }; };
Remove a line of debugging code
from __future__ import division # for Python 2.x compatibility import numpy class EuclidField(object): p = 5.0 r = 30.0 @staticmethod def dist(x, y): return numpy.hypot(x[0]-y[0], x[1]-y[1]) def __init__(self, size, dst, obstacles): w, h = size self.shape = (h, w) self.dst = dst self.obstacles = obstacles def __getitem__(self, q): i, j = q h, w = self.shape if not (i in range(h) and j in range(w)): raise IndexError base = self.dist(q, self.dst) k = 0.0 p = self.p for obj in self.obstacles: dist_to_obj = self.dist(q, obj) if dist_to_obj <= p: k += (1/dist_to_obj - 1/p)**2 return (1.0 + k) * base**2 + self.r*k def __array__(self): h, w = self.shape return numpy.array([[self[i, j] for j in range(w)] for i in range(h)])
from __future__ import division # for Python 2.x compatibility import numpy class EuclidField(object): p = 5.0 r = 30.0 @staticmethod def dist(x, y): return numpy.hypot(x[0]-y[0], x[1]-y[1]) def __init__(self, size, dst, obstacles): w, h = size self.shape = (h, w) self.dst = dst self.obstacles = obstacles def __getitem__(self, q): i, j = q h, w = self.shape if not (i in range(h) and j in range(w)): raise IndexError base = self.dist(q, self.dst) k = 0.0 p = self.p for obj in self.obstacles: dist_to_obj = self.dist(q, obj) if dist_to_obj <= p: k += (1/dist_to_obj - 1/p)**2 return (1.0 + k) * base**2 + self.r*k def __array__(self): h, w = self.shape return numpy.array([[self[i, j] for j in range(w)] for i in range(h)]) f = EuclidField((3, 3), (0, 0), [(1,1)])
Add flag for new module loader.
/* ___ usage ___ en_US ___ usage: prolific stdio -o, --stdout use stdout (default) -e, --stderr use stderr --help display this message ___ $ ___ en_US ___ log is required: the `--log` address and port is a required argument port is not an integer: the `--log` port must be an integer ___ . ___ */ require('arguable')(module, require('cadence')(function (async, program) { program.helpIf(program.command.params.help) var response = { moduleName: 'prolific.stdio/stdio.processor', parameters: { params: program.command.param }, argv: program.argv, terminal: program.command.terminal } if (process.mainModule == module) { console.log(response) } return response })) module.exports.isProlific = true
/* ___ usage ___ en_US ___ usage: prolific stdio -o, --stdout use stdout (default) -e, --stderr use stderr --help display this message ___ $ ___ en_US ___ log is required: the `--log` address and port is a required argument port is not an integer: the `--log` port must be an integer ___ . ___ */ require('arguable')(module, require('cadence')(function (async, program) { program.helpIf(program.command.params.help) var response = { moduleName: 'prolific.stdio/stdio.processor', parameters: { params: program.command.param }, argv: program.argv, terminal: program.command.terminal } if (process.mainModule == module) { console.log(response) } return response }))
Remove tests that are not relevant anymore.
/** * Internal dependencies */ import { addAMPExtraProps } from '../'; describe( 'addAMPExtraProps', () => { it( 'does not modify non-child blocks', () => { const props = addAMPExtraProps( {}, { name: 'foo/bar' }, {} ); expect( props ).toStrictEqual( {} ); } ); it( 'adds a font family attribute', () => { const props = addAMPExtraProps( {}, { name: 'amp/amp-story-text' }, { ampFontFamily: 'Roboto' } ); expect( props ).toMatchObject( { 'data-font-family': 'Roboto' } ); } ); it( 'adds inline CSS for rotation', () => { const props = addAMPExtraProps( {}, { name: 'amp/amp-story-text' }, { rotationAngle: 90.54321 } ); expect( props ).toMatchObject( { style: { transform: 'rotate(90deg)' } } ); } ); } );
/** * Internal dependencies */ import { addAMPExtraProps } from '../'; describe( 'addAMPExtraProps', () => { it( 'does not modify non-child blocks', () => { const props = addAMPExtraProps( {}, { name: 'foo/bar' }, {} ); expect( props ).toStrictEqual( {} ); } ); it( 'generates a unique ID', () => { const props = addAMPExtraProps( {}, { name: 'amp/amp-story-text' }, {} ); expect( props ).toHaveProperty( 'id' ); } ); it( 'uses the existing anchor attribute as the ID', () => { const props = addAMPExtraProps( {}, { name: 'amp/amp-story-text' }, { anchor: 'foo' } ); expect( props ).toStrictEqual( { id: 'foo' } ); } ); it( 'adds a font family attribute', () => { const props = addAMPExtraProps( {}, { name: 'amp/amp-story-text' }, { ampFontFamily: 'Roboto' } ); expect( props ).toMatchObject( { 'data-font-family': 'Roboto' } ); } ); it( 'adds inline CSS for rotation', () => { const props = addAMPExtraProps( {}, { name: 'amp/amp-story-text' }, { rotationAngle: 90.54321 } ); expect( props ).toMatchObject( { style: { transform: 'rotate(90deg)' } } ); } ); } );
Clear old store instance on ctor
/* * Copyright (c) 2002-2003 by OpenSymphony * All rights reserved. */ package com.opensymphony.workflow; import com.opensymphony.workflow.basic.BasicWorkflow; import com.opensymphony.workflow.config.ConfigLoader; import com.opensymphony.workflow.spi.StoreFactory; import java.net.URL; /** * @author Hani Suleiman (hani@formicary.net) * Date: May 10, 2003 * Time: 1:36:21 PM */ public class TestWorkflow extends BasicWorkflow { //~ Static fields/initializers ///////////////////////////////////////////// public static String configFile = "/osworkflow.xml"; //~ Constructors /////////////////////////////////////////////////////////// public TestWorkflow(String caller) { super(caller); //lets clear out the old store StoreFactory.clearCache(); } //~ Methods //////////////////////////////////////////////////////////////// protected void loadConfig(URL url) throws FactoryException { if (url == null) { ConfigLoader.load(getClass().getResourceAsStream(configFile)); } } }
/* * Copyright (c) 2002-2003 by OpenSymphony * All rights reserved. */ package com.opensymphony.workflow; import com.opensymphony.workflow.basic.BasicWorkflow; import com.opensymphony.workflow.config.ConfigLoader; import java.net.URL; /** * @author Hani Suleiman (hani@formicary.net) * Date: May 10, 2003 * Time: 1:36:21 PM */ public class TestWorkflow extends BasicWorkflow { //~ Static fields/initializers ///////////////////////////////////////////// public static String configFile = "/osworkflow.xml"; //~ Constructors /////////////////////////////////////////////////////////// public TestWorkflow(String caller) { super(caller); } //~ Methods //////////////////////////////////////////////////////////////// protected void loadConfig(URL url) throws FactoryException { if (url == null) { ConfigLoader.load(getClass().getResourceAsStream(configFile)); } } }
Use getMapAsync, original file was renamed
package com.mapzen.android.sample; import com.mapzen.android.MapFragment; import com.mapzen.android.MapManager; import com.mapzen.tangram.MapController; import com.mapzen.tangram.MapView; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; /** * Basic SDK demo, tracks user's current location on map. */ public class BasicMapzenActivity extends AppCompatActivity { MapFragment mapFragment; MapController mapController; MapManager mapManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sample_mapzen); mapFragment = (MapFragment) getSupportFragmentManager().findFragmentById(R.id.fragment); mapFragment.getMapAsync(new MapView.OnMapReadyCallback() { @Override public void onMapReady(MapController mapController) { BasicMapzenActivity.this.mapController = mapController; configureMap(); } }); } private void configureMap() { mapManager = mapFragment.getMapManager(); mapManager.setMyLocationEnabled(true); } }
package com.mapzen.android.sample; import com.mapzen.android.MapFragment; import com.mapzen.android.MapManager; import com.mapzen.tangram.MapController; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; /** * Basic SDK demo, tracks user's current location on map. */ public class BasicMapzenActivity extends AppCompatActivity { MapFragment mapFragment; MapController mapController; MapManager mapManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sample_mapzen); mapFragment = (MapFragment) getSupportFragmentManager().findFragmentById(R.id.fragment); mapController = mapFragment.getMap(); mapManager = mapFragment.getMapManager(); configureMap(); } private void configureMap() { mapController.setMapZoom(17); mapManager.setMyLocationEnabled(true); } }
Implement CLI classes for MVC (unstable)
<?php /** * CLIResponse */ namespace Orpheus\InputController\CLIController; use Orpheus\InputController\OutputResponse; /** * The CLIResponse class * * @author Florent Hazard <contact@sowapps.com> * */ class CLIResponse extends OutputResponse { /** * The HTML body of the response * * @var string */ protected $body; /** * Constructor * * @param string $body */ public function __construct($body=null) { $this->setBody($body); } /** * Process the response */ public function process() { if( isset($this->body) ) { echo $this->getBody(); } } /** * Collect response data from parameters * * @param string $layout * @param array $values * @return NULL */ public function collectFrom($layout, $values=array()) { return null; } /** * Generate HTMLResponse from Exception * * @param Exception $exception * @param string $action * @return \Orpheus\InputController\HTTPController\HTMLHTTPResponse */ public static function generateFromException(\Exception $exception, $action='Handling the request') { $response = new static(convertExceptionAsText($exception, 0, $action)); return $response; } }
<?php /** * CLIResponse */ namespace Orpheus\InputController\CLIController; use Orpheus\InputController\OutputResponse; /** * The CLIResponse class * * @author Florent Hazard <contact@sowapps.com> * */ class CLIResponse extends OutputResponse { /** * The HTML body of the response * * @var string */ protected $body; /** * Constructor * * @param string $body */ public function __construct($body=null) { $this->setBody($body); } /** * Process the response */ public function process() { if( isset($this->body) ) { echo $this->getBody(); } } /** * Collect response data from parameters * * @param string $layout * @param array $values * @return NULL */ public function collectFrom($layout, $values=array()) { return null; } /** * Generate HTMLResponse from Exception * * @param Exception $exception * @param string $action * @return \Orpheus\InputController\HTTPController\HTMLHTTPResponse */ public static function generateFromException(\Exception $exception, $action='Handling the request') { $response = new static(convertExceptionAsText($exception, $action)); return $response; } }
Support larger thumbnails on screenr.com
package com.todoist.mediaparser.mediaparser; import com.todoist.mediaparser.util.MediaType; import java.util.regex.Pattern; public class ScreenrParser extends BaseOEmbedMediaParser { private static Pattern sMatchingPattern; ScreenrParser(String url) { super(url); } @Override public MediaType getContentMediaType() { return MediaType.VIDEO; } @Override protected Pattern getMatchingPattern() { if(sMatchingPattern == null) sMatchingPattern = Pattern.compile("https?://(?:www\\.)?screenr\\.com/\\w+/?", Pattern.CASE_INSENSITIVE); return sMatchingPattern; } @Override protected String createThumbnailUrl(int smallestSide) { String thumbnailUrl = super.createThumbnailUrl(smallestSide); if(smallestSide > 110) return thumbnailUrl.replaceFirst("_thumb\\.jpg$", ".jpg"); else return thumbnailUrl; } @Override protected String getOEmbedUrlTemplate() { return "http://www.screenr.com/api/oembed.json?url=%s"; } @Override protected String getOEmbedThumbnailUrlName() { return "thumbnail_url"; } }
package com.todoist.mediaparser.mediaparser; import com.todoist.mediaparser.util.MediaType; import java.util.regex.Pattern; public class ScreenrParser extends BaseOEmbedMediaParser { private static Pattern sMatchingPattern; ScreenrParser(String url) { super(url); } @Override public MediaType getContentMediaType() { return MediaType.VIDEO; } @Override protected Pattern getMatchingPattern() { if(sMatchingPattern == null) sMatchingPattern = Pattern.compile("https?://(?:www\\.)?screenr\\.com/\\w+/?", Pattern.CASE_INSENSITIVE); return sMatchingPattern; } @Override protected String getOEmbedUrlTemplate() { return "http://www.screenr.com/api/oembed.json?url=%s"; } @Override protected String getOEmbedThumbnailUrlName() { return "thumbnail_url"; } }
Allow running outside from a phar archive
#!/usr/bin/env php <?php error_reporting(E_ALL); function gtk_die($message) { $dialog = new \GtkMessageDialog(null, 0, \Gtk::MESSAGE_ERROR, \Gtk::BUTTONS_OK, $message); $dialog->set_markup($message); $dialog->run(); $dialog->destroy(); die($message."\n"); } if (!extension_loaded('php-gtk')) { die("ERROR: PHP Gtk2 not loaded!\n"); } if (version_compare('5.3.0', PHP_VERSION, '>')) { gtk_die('PHP Explorer requires PHP 5.3.0 or newer.'); } if (!extension_loaded('phar')) { gtk_die('PHAR Extension not loaded! Terminating.'); } if(!phar::canCompress()) { gtk_die('PHAR Extension has no compression support.'); } if (basename(__FILE__) == 'explorer.php') { ini_set('include_path', __DIR__.PATH_SEPARATOR.ini_get('include_path')); $gladefile = __DIR__.'/data/explorer.glade'; } else { ini_set('include_path', 'phar://'.__FILE__.PATH_SEPARATOR.ini_get('include_path')); $gladefile = 'phar://'.__FILE__.'/data/explorer.glade'; } include 'stuff.php'; include 'Explorer/Controller/MainWindowController.php'; include 'Explorer/Manual/Manual.php'; $main = new Explorer\Controller\MainWindowController($gladefile); Gtk::Main(); __HALT_COMPILER(); ?>
#!/usr/bin/env php <?php error_reporting(E_ALL); function gtk_die($message) { $dialog = new \GtkMessageDialog(null, 0, \Gtk::MESSAGE_ERROR, \Gtk::BUTTONS_OK, $message); $dialog->set_markup($message); $dialog->run(); $dialog->destroy(); die($message."\n"); } if (!extension_loaded('php-gtk')) { die("ERROR: PHP Gtk2 not loaded!\n"); } if (version_compare('5.3.0', PHP_VERSION, '>')) { gtk_die('PHP Explorer requires PHP 5.3.0 or newer.'); } if (!extension_loaded('phar')) { gtk_die('PHAR Extension not loaded! Terminating.'); } if(!phar::canCompress()) { gtk_die('PHAR Extension has no compression support.'); } ini_set('include_path', 'phar://'.__FILE__.PATH_SEPARATOR.ini_get('include_path')); include 'stuff.php'; include 'Explorer/Controller/MainWindowController.php'; include 'Explorer/Manual/Manual.php'; $main = new Explorer\Controller\MainWindowController('phar://'.__FILE__.'/data/explorer.glade'); Gtk::Main(); __HALT_COMPILER(); ?>
Change the context link URL to the result link
// Returns the contexts (short description with bolded matched words) of the // search results. This is only a function to allow the implementation to be // changed if Google ever changes the format of their HTML. function getSearchContexts() { return document.querySelectorAll(".st"); } // Returns the relevant URL for the given context. function getContextURL(context) { var header_link = context.parentNode.parentNode.parentNode.querySelector(".r"); return header_link.getElementsByTagName("a")[0].href; } function forEverySubContext(context) { var context_url = getContextURL(context); var new_innerHTML = ""; var sub_contexts = context.innerHTML.split("..."); for (var i = 0; i < sub_contexts.length; ++i) { if (sub_contexts[i].length === 0) { continue; } new_innerHTML += "<a href=\"" + context_url + "\">"; new_innerHTML += sub_contexts[i]; new_innerHTML += "</a>"; if (i !== sub_contexts.length - 1 || context.innerHTML.substr(context.innerHTML.length - 3) === "...") { new_innerHTML += "..."; } } context.innerHTML = new_innerHTML; } var contexts = getSearchContexts(); for (var i = 0; i < contexts.length; ++i) { forEverySubContext(contexts[i]); }
// Returns the contexts (short description with bolded matched words) of the // search results. This is only a function to allow the implementation to be // changed if Google ever changes the format of their HTML. function getSearchContexts() { return document.querySelectorAll(".st"); } function forEverySubContext(context) { var new_innerHTML = ""; var sub_contexts = context.innerHTML.split("..."); for (var i = 0; i < sub_contexts.length; ++i) { if (sub_contexts[i].length === 0) { continue; } new_innerHTML += "<a href=\"https://www.google.com\">"; // This URL needs to be changed to the result site's URL. new_innerHTML += sub_contexts[i]; new_innerHTML += "</a>"; if (i !== sub_contexts.length - 1 || context.innerHTML.substr(context.innerHTML.length - 3) === "...") { new_innerHTML += "..."; } } context.innerHTML = new_innerHTML; } var contexts = getSearchContexts(); for (var i = 0; i < contexts.length; ++i) { forEverySubContext(contexts[i]); }
Fix issue where errors aren't being propagated.
function DeferredChain() { var self = this; this.chain = new Promise(function(accept, reject) { self._accept = accept; self._reject = reject; }); this.await = new Promise(function() { self._done = arguments[0]; self._error = arguments[1]; }); this.started = false; }; DeferredChain.prototype.then = function(fn) { var self = this; this.chain = this.chain.then(function() { var args = Array.prototype.slice.call(arguments); return fn.apply(null, args); }); this.chain = this.chain.catch(function(e) { self._error(e); }); return this; }; DeferredChain.prototype.catch = function(fn) { var self = this; this.chain = this.chain.catch(function() { var args = Array.prototype.slice.call(arguments); return fn.apply(null, args); }); return this; }; DeferredChain.prototype.start = function() { this.started = true; this.chain = this.chain.then(this._done); this._accept(); return this.await; }; module.exports = DeferredChain;
function DeferredChain() { var self = this; this.chain = new Promise(function(accept, reject) { self._accept = accept; self._reject = reject; }); this.await = new Promise(function() { self._done = arguments[0]; }); this.started = false; }; DeferredChain.prototype.then = function(fn) { var self = this; this.chain = this.chain.then(function() { var args = Array.prototype.slice.call(arguments); return fn.apply(null, args); }); return this; }; DeferredChain.prototype.catch = function(fn) { var self = this; this.chain = this.chain.catch(function() { var args = Array.prototype.slice.call(arguments); return fn.apply(null, args); }); return this; }; DeferredChain.prototype.start = function() { this.started = true; this.chain = this.chain.then(this._done); this._accept(); return this.await; }; module.exports = DeferredChain;
lathe[cuboid]: Generalize BoxGeometry translation helpers to scaling.
/* eslint-env es6 */ /* global THREE, Indices */ function transformBoxVertices( method ) { 'use strict'; const vector = new THREE.Vector3(); const zero = new THREE.Vector3(); return function transform( geometry, vectors ) { Object.keys( vectors ).forEach( key => { const delta = vectors[ key ]; const indices = Indices[ key.toUpperCase() ]; if ( Array.isArray( delta ) ) { vector.fromArray( delta ); } else if ( typeof delta === 'object' ) { Object.assign( vector, zero, delta ); } else if ( typeof delta === 'number' ) { vector.setScalar( delta ); } else { return; } if ( Array.isArray( indices ) ) { indices.forEach( index => geometry.vertices[ index ][ method ]( vector ) ); } else { geometry.vertices[ indices ][ method ]( vector ); } }); return geometry; }; } window.translateBoxVertices = transformBoxVertices( 'add' ); window.scaleBoxVertices = transformBoxVertices( 'multiply' );
/* eslint-env es6 */ /* global THREE, Indices */ window.translateBoxVertices = (function() { 'use strict'; const vector = new THREE.Vector3(); const zero = new THREE.Vector3(); return function translate( geometry, vectors ) { Object.keys( vectors ).forEach( key => { const delta = vectors[ key ]; const indices = Indices[ key.toUpperCase() ]; if ( Array.isArray( delta ) ) { vector.fromArray( delta ); } else if ( typeof delta === 'object' ) { Object.assign( vector, zero, delta ); } else if ( typeof delta === 'number' ) { vector.setScalar( delta ); } else { return; } if ( Array.isArray( indices ) ) { indices.forEach( index => geometry.vertices[ index ].add( vector ) ); } else { geometry.vertices[ indices ].add( vector ); } }); return geometry; }; }());
Make 0 the default version
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import os from oslo.db.sqlalchemy import migration as oslo_migration INIT_VERSION = 0 def db_sync(engine, version=None): path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'migrate_repo') return oslo_migration.db_sync(engine, path, version, init_version=INIT_VERSION) def db_version(engine): path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'migrate_repo') return oslo_migration.db_version(engine, path, INIT_VERSION) def db_version_control(engine, version=None): path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'migrate_repo') return oslo_migration.db_version_control(engine, path, version)
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import os from oslo.db.sqlalchemy import migration as oslo_migration INIT_VERSION = 1 def db_sync(engine, version=None): path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'migrate_repo') return oslo_migration.db_sync(engine, path, version, init_version=INIT_VERSION) def db_version(engine): path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'migrate_repo') return oslo_migration.db_version(engine, path, INIT_VERSION) def db_version_control(engine, version=None): path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'migrate_repo') return oslo_migration.db_version_control(engine, path, version)
Add missing font awesome icons for the datetime picker
var coupon = function () { var durationSelector = '#duration'; var $body = $('body'); var $duration = $(durationSelector); var $durationInMonths = $('#duration-in-months'); var $redeem_by = $('#redeem_by'); $body.on('change', durationSelector, function () { if ($duration.val() === 'repeating') { $durationInMonths.show(); } else { $durationInMonths.hide(); } }); if ($redeem_by.length) { $redeem_by.datetimepicker({ widgetParent: '.dt', format: 'YYYY-MM-DD HH:mm:ss', icons: { time: 'fa fa-clock-o', date: 'fa fa-calendar', up: 'fa fa-arrow-up', down: 'fa fa-arrow-down', previous: 'fa fa-chevron-left', next: 'fa fa-chevron-right', clear: 'fa fa-trash' } }); } }; module.exports = coupon;
var coupon = function () { var durationSelector = '#duration'; var $body = $('body'); var $duration = $(durationSelector); var $durationInMonths = $('#duration-in-months'); var $redeem_by = $('#redeem_by'); $body.on('change', durationSelector, function () { if ($duration.val() === 'repeating') { $durationInMonths.show(); } else { $durationInMonths.hide(); } }); if ($redeem_by.length) { $redeem_by.datetimepicker({ widgetParent: '.dt', format: 'YYYY-MM-DD HH:mm:ss', icons: { time: 'fa fa-clock-o', date: 'fa fa-calendar', up: 'fa fa-arrow-up', down: 'fa fa-arrow-down' } }); } }; module.exports = coupon;
Fix height of blockconfirmation icon and reduces row height
package io.bisq.gui.components; import de.jensd.fx.fontawesome.AwesomeDude; import de.jensd.fx.fontawesome.AwesomeIcon; import javafx.geometry.Insets; import javafx.scene.control.ContentDisplay; import javafx.scene.control.Hyperlink; import javafx.scene.control.Label; public class HyperlinkWithIcon extends Hyperlink { public HyperlinkWithIcon(String text) { this(text, AwesomeIcon.INFO_SIGN); } public HyperlinkWithIcon(String text, AwesomeIcon awesomeIcon) { super(text); Label icon = new Label(); AwesomeDude.setIcon(icon, awesomeIcon); icon.setMinWidth(20); icon.setOpacity(0.7); icon.getStyleClass().add("hyperlink"); icon.setPadding(new Insets(0)); setGraphic(icon); setContentDisplay(ContentDisplay.RIGHT); setGraphicTextGap(7.0); //TODO: replace workaround of setting the style this way tooltipProperty().addListener((observable, oldValue, newValue) -> newValue.setStyle("-fx-text-fill: -bs-black")); } public void clear() { setText(""); setGraphic(null); } }
package io.bisq.gui.components; import de.jensd.fx.fontawesome.AwesomeDude; import de.jensd.fx.fontawesome.AwesomeIcon; import javafx.scene.control.ContentDisplay; import javafx.scene.control.Hyperlink; import javafx.scene.control.Label; public class HyperlinkWithIcon extends Hyperlink { public HyperlinkWithIcon(String text) { this(text, AwesomeIcon.INFO_SIGN); } public HyperlinkWithIcon(String text, AwesomeIcon awesomeIcon) { super(text); Label icon = new Label(); AwesomeDude.setIcon(icon, awesomeIcon); icon.setMinWidth(20); icon.setOpacity(0.7); icon.getStyleClass().add("hyperlink"); setGraphic(icon); setContentDisplay(ContentDisplay.RIGHT); tooltipProperty().addListener((observable, oldValue, newValue) -> newValue.setStyle("-fx-text-fill: -bs-black")); } public void clear() { setText(""); setGraphic(null); } }
Fix static page sitemap urls
from common.helpers.constants import FrontEndSection from django.contrib.sitemaps import Sitemap from .models import Project from datetime import date class SectionSitemap(Sitemap): protocol = "https" changefreq = "monthly" priority = 0.5 # TODO: Update this date for each release lastmod = date(year=2019, month=12, day=5) sections = [FrontEndSection.AboutUs, FrontEndSection.FindProjects, FrontEndSection.PartnerWithUs, FrontEndSection.Donate, FrontEndSection.Press, FrontEndSection.ContactUs] def items(self): return self.sections def location(self, section): return '/index/?section=' + str(section.value) class ProjectSitemap(Sitemap): protocol = "https" changefreq = "daily" priority = 0.5 def items(self): return Project.objects.filter(is_searchable=True).order_by('id') def location(self, project): return '/index/?section=AboutProject&id=' + str(project.id) def lastmod(self, project): return project.project_date_modified
from common.helpers.constants import FrontEndSection from django.contrib.sitemaps import Sitemap from .models import Project from datetime import date class SectionSitemap(Sitemap): protocol = "https" changefreq = "monthly" priority = 0.5 # TODO: Update this date for each release lastmod = date(year=2019, month=12, day=5) sections = [FrontEndSection.AboutUs, FrontEndSection.FindProjects, FrontEndSection.PartnerWithUs, FrontEndSection.Donate, FrontEndSection.Press, FrontEndSection.ContactUs] def items(self): return self.sections def location(self, page): return '/index/?section=' + str(page) class ProjectSitemap(Sitemap): protocol = "https" changefreq = "daily" priority = 0.5 def items(self): return Project.objects.filter(is_searchable=True).order_by('id') def location(self, project): return '/index/?section=AboutProject&id=' + str(project.id) def lastmod(self, project): return project.project_date_modified
Remove fancybox afterLoad / afterClose event on destroy.
"use strict"; angular.module("hikeio"). directive("fancybox", ["$rootScope", function($rootScope) { return { link: function (scope, element, attrs) { var context = { afterLoad: function(current, previous) { $rootScope.$broadcast("fancyboxLoaded"); }, afterClose: function(current, previous) { $rootScope.$broadcast("fancyboxClosed"); }, padding : 2, nextEffect : "none", prevEffect : "none", closeEffect : "none", closeBtn : true, arrows : false, keys : true, nextClick : true }; scope.$on("$routeChangeStart", function () { $.fancybox.close(); }); scope.$on("fancyboxClose", function () { $.fancybox.close(); }); scope.$on("$destroy", function () { context.afterLoad = null; context.afterClose = null; }); $(element).find(attrs.fancybox).fancybox(context); } }; }]);
"use strict"; angular.module("hikeio"). directive("fancybox", ["$rootScope", function($rootScope) { return { link: function (scope, element, attrs) { scope.$on("$routeChangeStart", function () { $.fancybox.close(); }); scope.$on("fancyboxClose", function () { $.fancybox.close(); }); $(element).find(attrs.fancybox).fancybox({ afterLoad: function(current, previous) { $rootScope.$broadcast("fancyboxLoaded"); }, afterClose: function(current, previous) { $rootScope.$broadcast("fancyboxClosed"); }, padding : 2, nextEffect : "none", prevEffect : "none", closeEffect : "none", closeBtn : true, arrows : false, keys : true, nextClick : true }); } }; }]);
Define Alternate Names for city rather than this shortname, long name etc.
package com.sarality.app.data.location; import com.sarality.app.data.BaseEnumData; import java.util.List; /** * Enum Data for a City. * * @author abhideep@ (Abhideep Singh) */ public class City extends BaseEnumData<City> { private final String name; private final Country country; private final List<String> alternateNames; public City(String enumName, String name, Country country, List<String> alternateNames) { super(enumName); this.name = name; this.country = country; this.alternateNames = alternateNames; register(City.class, this); } public String getShortName() { return name; } public String getFullName() { return name; } public Country getCountry() { return country; } public List<String> getAlternateNames() { return alternateNames; } @Override public City getEnumData() { return this; } }
package com.sarality.app.data.location; import com.sarality.app.data.BaseEnumData; /** * Enum Data for a City. * * @author abhideep@ (Abhideep Singh) */ public class City extends BaseEnumData<City> { private final String shortName; private final String fullName; private final String oldName; private final Country country; public City(String enumName, String shortName, String fullName, String oldName, Country country) { super(enumName); this.shortName = shortName; this.fullName = fullName; this.oldName = oldName; this.country = country; register(City.class, this); } public String getShortName() { return shortName; } public String getFullName() { return fullName; } public String getOldName() { return oldName; } public Country getCountry() { return country; } @Override public City getEnumData() { return this; } }
Refactor getting the default team id
<?php # See application/core/MY_Model for this parent model class Team_stats_model extends Crud_model { public function __construct() { parent::__construct(); $this->table = 'team_stats'; } public function all() { $res = $this->db->get($this->table)->result(); /* we strip off useless zeros such as 60.00 to 60 or 79.70 to 79.9 */ $this->formatFields($res); return $res; } public function getStatsByTeamId($team_id) { $this->db->where('team_id', $team_id); $res = $this->db->get($this->table)->result(); $this->formatFields($res); return $res; } public function getDefaultTeamStats() { $this->load->model('Players_model'); $default_team_id = $this->getTeamIdByName(DEFAULT_SQUAD); # Find in constants $res = $this->getStatsByTeamId($default_team_id); $this->formatFields($res); return $res; } public function formatFields($res) { foreach($res as &$val) { $val->stat_value = floatval($val->stat_value); } } }
<?php # See application/core/MY_Model for this parent model class Team_stats_model extends Crud_model { public function __construct() { parent::__construct(); $this->table = 'team_stats'; } public function all() { $res = $this->db->get($this->table)->result(); /* we strip off useless zeros such as 60.00 to 60 or 79.70 to 79.9 */ $this->formatFields($res); return $res; } public function getStatsByTeamId($team_id) { $this->db->where('team_id', $team_id); $res = $this->db->get($this->table)->result(); $this->formatFields($res); return $res; } public function getDefaultTeamStats() { $this->load->model('Players_model'); $default_team_id = $this->Players_model->getDefaultSquad()[0]->team_id; # Get a single player from a squad then get his ID $res = $this->getStatsByTeamId($default_team_id); $this->formatFields($res); return $res; } public function formatFields($res) { foreach($res as &$val) { $val->stat_value = floatval($val->stat_value); } } }
Add inter-month padding trait to factory.
#------------------------------------------------------------------------------ # # Copyright (c) 2008, Enthought, Inc. # All rights reserved. # # This software is provided without warranty under the terms of the BSD # license included in enthought/LICENSE.txt and may be redistributed only # under the conditions described in the aforementioned license. The license # is also available online at http://www.enthought.com/licenses/BSD.txt # # Thanks for using Enthought open source! # # Author: Judah De Paula # Date: 10/7/2008 # #------------------------------------------------------------------------------ """ A Traits UI editor that wraps a WX calendar panel. """ from enthought.traits.trait_types import Bool, Int from enthought.traits.ui.editor_factory import EditorFactory #-- DateEditor definition ----------------------------------------------------- class DateEditor ( EditorFactory ): """ Editor factory for date/time editors. """ #--------------------------------------------------------------------------- # Trait definitions: #--------------------------------------------------------------------------- #-- CustomEditor traits ---------------------------------------------------- # True: Must be a List of Dates. False: A Date instance. multi_select = Bool(False) # Should users be able to pick future dates when using the CustomEditor? allow_future = Bool(True) # How many months to show at a time. months = Int(3) # How much space to put between the individual months. padding = Int(5) #-- end DateEditor definition ------------------------------------------------- #-- eof -----------------------------------------------------------------------
#------------------------------------------------------------------------------ # # Copyright (c) 2008, Enthought, Inc. # All rights reserved. # # This software is provided without warranty under the terms of the BSD # license included in enthought/LICENSE.txt and may be redistributed only # under the conditions described in the aforementioned license. The license # is also available online at http://www.enthought.com/licenses/BSD.txt # # Thanks for using Enthought open source! # # Author: Judah De Paula # Date: 10/7/2008 # #------------------------------------------------------------------------------ """ A Traits UI editor that wraps a WX calendar panel. """ from enthought.traits.trait_types import Bool, Int from enthought.traits.ui.editor_factory import EditorFactory #-- DateEditor definition ----------------------------------------------------- class DateEditor ( EditorFactory ): """ Editor factory for date/time editors. """ #--------------------------------------------------------------------------- # Trait definitions: #--------------------------------------------------------------------------- # Is multiselect enabled for a CustomEditor? # True: Must be a List of Dates. False: A Date instance. multi_select = Bool(False) # Should users be able to pick future dates when using the CustomEditor? allow_future = Bool(True) # How many months to show at a time. months = Int(3) #-- end DateEditor definition ------------------------------------------------- #-- eof -----------------------------------------------------------------------
Add support for including the domain the the analytics asset
package assets import ( "fmt" ) const ( analyticsScript = `<script>(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', %s); ga('send', 'pageview');</script>` ) func googleAnalytics(m *Manager, names []string, options Options) ([]*Asset, error) { if len(names) != 1 && len(names) != 2 { return nil, fmt.Errorf("analytics requires either 1 or 2 arguments (either \"UA-XXXXXX-YY, mysite.com\" or just \"UA-XXXXXX-YY\" - without quotes in both cases") } key := names[0] if key == "" { return nil, nil } var arg string if len(names) == 2 { arg = fmt.Sprintf("'%s', '%s'", key, names[1]) } else { arg = fmt.Sprintf("'%s'", key) } return []*Asset{ &Asset{ Name: "google-analytics.js", Position: Bottom, HTML: fmt.Sprintf(analyticsScript, arg), }, }, nil } func init() { Register("analytics", googleAnalytics) }
package assets import ( "fmt" ) const ( analyticsScript = `<script>(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', '%s'); ga('send', 'pageview');</script>` ) func googleAnalytics(m *Manager, names []string, options Options) ([]*Asset, error) { key := names[0] if key == "" { return nil, nil } return []*Asset{ &Asset{ Name: "google-analytics.js", Position: Bottom, HTML: fmt.Sprintf(analyticsScript, key), }, }, nil } func init() { Register("analytics", googleAnalytics) }
Use a lock file to avoid parallel-saving
<?php include("init_local.php"); loadlib("wof_save"); loadlib("offline_tasks"); loadlib("uuid"); loadlib("logstash"); $lockfile = "{$GLOBALS['cfg']['pending_log_dir']}SAVE_LOCKFILE"; if (file_exists($lockfile)) { die("Looks like save_pending.php might already be running.\n"); } // Set a lock file so we don't run more than one save at a time touch($lockfile); $task_id = uuid_v4(); $now = offline_tasks_microtime(); $event = array( 'action' => 'schedule', 'task_id' => $task_id, 'task' => 'save_pending', 'data' => array(), 'rsp' => array(), 'microtime' => $now ); logstash_publish('offline_tasks', $event); $rsp = wof_save_pending(); $now = offline_tasks_microtime(); $event = array( 'action' => 'execute', 'task_id' => $task_id, 'task' => 'save_pending', 'data' => array(), 'rsp' => $rsp, 'microtime' => $now ); logstash_publish('offline_tasks', $event); // Delete the lock file; all done! unlink($lockfile); exit(); ?>
<?php include("init_local.php"); loadlib("wof_save"); loadlib("offline_tasks"); loadlib("uuid"); loadlib("logstash"); $task_id = uuid_v4(); $now = offline_tasks_microtime(); $event = array( 'action' => 'schedule', 'task_id' => $task_id, 'task' => 'save_pending', 'data' => array(), 'rsp' => array(), 'microtime' => $now ); logstash_publish('offline_tasks', $event); $rsp = wof_save_pending(); $now = offline_tasks_microtime(); $event = array( 'action' => 'execute', 'task_id' => $task_id, 'task' => 'save_pending', 'data' => array(), 'rsp' => $rsp, 'microtime' => $now ); logstash_publish('offline_tasks', $event); exit(); ?>
fix(json): Fix generator type serializer not serializing properties
package valandur.webapi.json.serializers.world; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.std.StdSerializer; import org.spongepowered.api.data.DataQuery; import org.spongepowered.api.world.GeneratorType; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Optional; public class GeneratorTypeSerializer extends StdSerializer<GeneratorType> { public GeneratorTypeSerializer() { this(null); } public GeneratorTypeSerializer(Class<GeneratorType> t) { super(t); } @Override public void serialize(GeneratorType value, JsonGenerator gen, SerializerProvider provider) throws IOException { gen.writeStartObject(); gen.writeStringField("id", value.getId()); gen.writeStringField("name", value.getName()); Map<String, Object> settings = new HashMap<>(); for (DataQuery query : value.getGeneratorSettings().getKeys(true)) { Optional val = value.getGeneratorSettings().get(query); if (!val.isPresent()) continue; settings.put(query.asString("."), val.get()); } gen.writeObjectField("settings", settings); gen.writeEndObject(); } }
package valandur.webapi.json.serializers.world; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.std.StdSerializer; import org.spongepowered.api.world.GeneratorType; import java.io.IOException; public class GeneratorTypeSerializer extends StdSerializer<GeneratorType> { public GeneratorTypeSerializer() { this(null); } public GeneratorTypeSerializer(Class<GeneratorType> t) { super(t); } @Override public void serialize(GeneratorType value, JsonGenerator gen, SerializerProvider provider) throws IOException { gen.writeStartObject(); gen.writeStringField("id", value.getId()); gen.writeStringField("name", value.getName()); gen.writeObjectField("settings", value.getGeneratorSettings()); gen.writeEndObject(); } }
Clean up BQ test data properly If you delete datasets while iterating over datasets, you eventually get errors. This fixes that by building a list of all datasets before we delete any.
import os from django.core.management import BaseCommand, CommandError from gcutils.bigquery import Client class Command(BaseCommand): help = 'Removes any datasets whose tables have all expired' def handle(self, *args, **kwargs): if os.environ['DJANGO_SETTINGS_MODULE'] != \ 'openprescribing.settings.test': raise CommandError('Command must run with test settings') gcbq_client = Client().gcbq_client datasets = list(gcbq_client.list_datasets()) for dataset_list_item in datasets: dataset_ref = dataset_list_item.reference tables = list(gcbq_client.list_tables(dataset_ref)) if len(tables) == 0: gcbq_client.delete_dataset(dataset_ref)
import os from django.core.management import BaseCommand, CommandError from gcutils.bigquery import Client class Command(BaseCommand): help = 'Removes any datasets whose tables have all expired' def handle(self, *args, **kwargs): if os.environ['DJANGO_SETTINGS_MODULE'] != \ 'openprescribing.settings.test': raise CommandError('Command must run with test settings') gcbq_client = Client().gcbq_client for dataset_list_item in gcbq_client.list_datasets(): dataset_ref = dataset_list_item.reference tables = list(gcbq_client.list_tables(dataset_ref)) if len(tables) == 0: gcbq_client.delete_dataset(dataset_ref)
Add updateTime check to test.
// // Tests for BitGo Object // // Copyright 2014, BitGo, Inc. All Rights Reserved. // var assert = require('assert'); var should = require('should'); var BitGoJS = require('../src/index'); describe('BitGo', function() { describe('methods', function() { it('includes version', function() { var bitgo = new BitGoJS.BitGo(); bitgo.should.have.property('version'); var version = bitgo.version(); assert.equal(typeof(version), 'string'); }); it('includes market', function(done) { var bitgo = new BitGoJS.BitGo(); bitgo.should.have.property('market'); bitgo.market(function(marketData) { marketData.should.have.property('last'); marketData.should.have.property('bid'); marketData.should.have.property('ask'); marketData.should.have.property('volume'); marketData.should.have.property('high'); marketData.should.have.property('low'); marketData.should.have.property('updateTime'); done(); }); }); }); });
// // Tests for BitGo Object // // Copyright 2014, BitGo, Inc. All Rights Reserved. // var assert = require('assert'); var should = require('should'); var BitGoJS = require('../src/index'); describe('BitGo', function() { describe('methods', function() { it('includes version', function() { var bitgo = new BitGoJS.BitGo(); bitgo.should.have.property('version'); var version = bitgo.version(); assert.equal(typeof(version), 'string'); }); it('includes market', function(done) { var bitgo = new BitGoJS.BitGo(); bitgo.should.have.property('market'); bitgo.market(function(marketData) { marketData.should.have.property('last'); marketData.should.have.property('bid'); marketData.should.have.property('ask'); marketData.should.have.property('volume'); marketData.should.have.property('high'); marketData.should.have.property('low'); done(); }); }); }); });
Use type instead of uint8.
package models import "github.com/brocaar/lorawan" // NodeSession contains the informatio of a node-session (an activated node). type NodeSession struct { DevAddr lorawan.DevAddr `json:"devAddr"` AppEUI lorawan.EUI64 `json:"appEUI"` DevEUI lorawan.EUI64 `json:"devEUI"` AppSKey lorawan.AES128Key `json:"appSKey"` NwkSKey lorawan.AES128Key `json:"nwkSKey"` FCntUp uint32 `json:"fCntUp"` FCntDown uint32 `json:"fCntDown"` RXWindow RXWindow `json:"rxWindow"` RXDelay uint8 `json:"rxDelay"` RX1DROffset uint8 `json:"rx1DROffset"` RX2DR uint8 `json:"rx2DR"` CFList *lorawan.CFList `json:"cFlist"` }
package models import "github.com/brocaar/lorawan" // NodeSession contains the informatio of a node-session (an activated node). type NodeSession struct { DevAddr lorawan.DevAddr `json:"devAddr"` AppEUI lorawan.EUI64 `json:"appEUI"` DevEUI lorawan.EUI64 `json:"devEUI"` AppSKey lorawan.AES128Key `json:"appSKey"` NwkSKey lorawan.AES128Key `json:"nwkSKey"` FCntUp uint32 `json:"fCntUp"` FCntDown uint32 `json:"fCntDown"` RXWindow uint8 `json:"rxWindow"` RXDelay uint8 `json:"rxDelay"` RX1DROffset uint8 `json:"rx1DROffset"` RX2DR uint8 `json:"rx2DR"` CFList *lorawan.CFList `json:"cFlist"` }
Revert "catch service worker error?" This reverts commit c14cfe8917c1f1c23ccd4bbd25a7b40d6c5d6b2b.
/*jslint browser: true*/ if (navigator.serviceWorker && location.host !== 'localhost:8000') { navigator.serviceWorker.register('/serviceworker.js', { scope: '/' }); window.addEventListener('load', function () { if (navigator.serviceWorker.controller) { navigator.serviceWorker.controller.postMessage({'command': 'trimCaches'}); } }); } (function () { var cookieMessage = document.getElementById('cookie-message'); if (cookieMessage && document.cookie.indexOf('seen_cookie_message=yes') === -1) { cookieMessage.style.display = 'block'; document.cookie = 'seen_cookie_message=yes; max-age=31536000; path=/'; } })();
/*jslint browser: true*/ if (navigator.serviceWorker && location.protocol === 'https://') { try { navigator.serviceWorker.register('/serviceworker.js', { scope: '/' }); window.addEventListener('load', function () { if (navigator.serviceWorker.controller) { navigator.serviceWorker.controller.postMessage({'command': 'trimCaches'}); } }); } catch {} } (function () { var cookieMessage = document.getElementById('cookie-message'); if (cookieMessage && document.cookie.indexOf('seen_cookie_message=yes') === -1) { cookieMessage.style.display = 'block'; document.cookie = 'seen_cookie_message=yes; max-age=31536000; path=/'; } })();
Fix var type convention conflict
var config = require('../../config'); var sparqlQueryBuilder = require('../utils/sparql-query-builder'); var sparqlClient = require('sparql-client'); var util = require('util'); /* To be moved to its own file */ class Resource { constructor(uri, properties = {}, relationships = {}) { this.uri = uri, this.properties = properties; this.relationships = relationships; } } class DBPedia { constructor() { this.resources = {}; this.anchor_resources = []; } addAnchors(anchors) { this.anchor_resources.push(...anchors.filter(anchor => !(anchor in this.anchor_resources))); } fetch(onSuccess, onFail) { var resources_to_fetch = this.anchor_resources.filter(anchor => !this.resources[anchor]); var query = sparqlQueryBuilder.DBPedia.fetch(resources_to_fetch); var client = new sparqlClient(config.DBPEDIA_ENDPOINT); client.query(query) .execute((err, results) => { if(err) onFail(err); else onSuccess(results); }); } getResources() { return this.resources; } _createResourceFromSparqlResult(result) { /* To be implemented */ } } module.exports = DBPedia;
const config = require('../../config'), sparqlQueryBuilder = require('../utils/sparql-query-builder'), sparqlClient = require('sparql-client'), util = require('util'); /* To be moved to its own file */ class Resource { constructor(uri, properties = {}, relationships = {}) { this.uri = uri, this.properties = properties; this.relationships = relationships; } } class DBPedia { constructor() { this.resources = {}; this.anchor_resources = []; } addAnchors(anchors) { this.anchor_resources.push(...anchors.filter(anchor => !(anchor in this.anchor_resources))); } fetch(onSuccess, onFail) { var resources_to_fetch = this.anchor_resources.filter(anchor => !this.resources[anchor]); var query = sparqlQueryBuilder.DBPedia.fetch(resources_to_fetch); var client = new sparqlClient(config.DBPEDIA_ENDPOINT); client.query(query) .execute((err, results) => { if(err) onFail(err); else onSuccess(results); }); } getResources() { return this.resources; } _createResourceFromSparqlResult(result) { /* To be implemented */ } } module.exports = DBPedia;
Normalize the file dir path. Fixes the problem with UI not working if file dir was specified with a trailing slash.
var argv = require('optimist').argv; var fs = require('fs'); var config = require('./config/config.defaults.js'); if (argv['h']) { config.serverHost = argv['h']; } if (argv['host']) { config.serverHost = argv['host']; } if (argv['p']) { config.serverPort = argv['p']; } if (argv['port']) { config.serverPort = argv['port']; } if (argv['d']) { config.fileServerBaseDir = argv['d']; } if (argv['file-dir']) { config.fileServerBaseDir = argv['file-dir']; } if (argv['file-port']) { config.fileServerPort = argv['file-port']; } try { /* Makes sure the path exists and gets rid of any trailing slashes. */ config.fileServerBaseDir = fs.realpathSync(config.fileServerBaseDir); } catch (e) { console.log(e.message); process.exit(1); } var server = require('./server/server.js'); var debugFileServer = require('./server/debug-file-server.js'); server.run(); debugFileServer.run();
var argv = require('optimist').argv; var config = require('./config/config.defaults.js'); if (argv['h']) { config.serverHost = argv['h']; } if (argv['host']) { config.serverHost = argv['host']; } if (argv['p']) { config.serverPort = argv['p']; } if (argv['port']) { config.serverPort = argv['port']; } if (argv['d']) { config.fileServerBaseDir = argv['d']; } if (argv['file-dir']) { config.fileServerBaseDir = argv['file-dir']; } if (argv['file-port']) { config.fileServerPort = argv['file-port']; } var server = require('./server/server.js'); var debugFileServer = require('./server/debug-file-server.js'); server.run(); debugFileServer.run();
Allow S3 to properly serve to the cache servers
<?php class UploadFile { public function fire($job, $data) { $object = Object::where('name', $data['name'])->first(); // Take file $path = base_path().DIRECTORY_SEPARATOR.'storage'.DIRECTORY_SEPARATOR.$object->name; // Upload to S3 $s3 = App::make('aws')->get('s3'); $s3->putObject(array( 'Bucket' => 'storag', 'Key' => $object->name, 'SourceFile' => $path, 'ContentType' => $object->mime, )); $object->s3 = true; $object->save(); $job->delete(); } }
<?php class UploadFile { public function fire($job, $data) { $object = Object::where('name', $data['name'])->first(); // Take file $path = base_path().DIRECTORY_SEPARATOR.'storage'.DIRECTORY_SEPARATOR.$object->name; // Upload to S3 $s3 = App::make('aws')->get('s3'); $s3->putObject(array( 'Bucket' => 'storag', 'Key' => $object->name, 'SourceFile' => $path, )); $object->s3 = true; $object->save(); $job->delete(); } }
Remove some lines as defined in ADR1.
// 25: class - extends // To do: make all tests pass, leave the assert lines unchanged! describe('Classes can inherit from another using `extends`', () => { describe('the default super class is `Object`', () => { it('a `class A` is an instance of `Object`', () => { //// let A class A {} assert.equal(new A() instanceof Object, true); }); it('when B extends A, B is also instance of `Object`', () => { class A {} //// class B {} class B extends A{} assert.equal(new B() instanceof A, true); assert.equal(new B() instanceof Object, true); }); it('a class can extend `null`, and is not an instance of Object', () => { //// class NullClass extends Object {} //// let nullInstance = new NullClass(); //// assert.equal(nullInstance instanceof Object, false); }); }); describe('instance of', () => { it('when B inherits from A, `new B()` is also an instance of A', () => { //// let A; class A {} class B extends A {} assert.equal(new B() instanceof A, true); }); it('extend over multiple levels', () => { class A {} //// class B extends A {} class C extends B {} assert.equal(new C instanceof A, true); }); }); });
// 25: class - extends // To do: make all tests pass, leave the assert lines unchanged! describe('Classes can inherit from another using `extends`', () => { describe('the default super class is `Object`', () => { it('a `class A` is an instance of `Object`', () => { //// let A class A {} assert.equal(new A() instanceof Object, true); }); it('when B extends A, B is also instance of `Object`', () => { class A {} //// class B {} class B extends A{} assert.equal(new B() instanceof A, true); assert.equal(new B() instanceof Object, true); }); it('a class can extend `null`, and is not an instance of Object', () => { //// class NullClass extends Object {} //// let nullInstance = new NullClass(); //// assert.equal(nullInstance instanceof Object, false); }); }); describe('instance of', () => { it('when B inherits from A, `new B()` is also an instance of A', () => { //// let A; class A {} class B extends A {} assert.equal(new B() instanceof A, true); }); it('extend over multiple levels', () => { class A {} //// class B extends A {} class C extends B {} assert.equal(new C instanceof A, true); }); }); });
Return Arrays Instead of Objects
var rootView = null; export function isAttached(view) { if (!view) throw new Error("'view' param is required."); return view.parentElement !== null; } export function setRootView(view) { if (!view) throw new Error("'view' param is required."); rootView = view; } export function getRootView() { return rootView; } export function rootAttacher(result) { if (!rootView) return; while (rootView.firstElementChild) { rootView.removeChild(rootView.firstElementChild); } rootView.appendChild(result.view); } export function getAttachers() { return [ { name: "root", attacher: rootAttacher } ]; } export function buildTextAsHtml(content) { return new Promise(function (resolve, reject) { var fileReader = new FileReader(); fileReader.onloadend = function (evt) { var view = document.createElement("pre"); view.textContent = evt.target.result; var result = { content, view }; resolve(result); }; fileReader.readAsText(content.blob); }); } export function getBuilders() { return [ { mediaType: "text/*", builder: buildTextAsHtml } ]; }
var rootView = null; export function isAttached(view) { if (!view) throw new Error("'view' param is required."); return view.parentElement !== null; } export function setRootView(view) { if (!view) throw new Error("'view' param is required."); rootView = view; } export function getRootView() { return rootView; } export function pageAttacher(result) { if (!rootView) return; while (rootView.firstElementChild) { rootView.removeChild(rootView.firstElementChild); } rootView.appendChild(result.view); } export function getAttachers() { return { page: pageAttacher }; } export function buildTextAsHtml(content) { return new Promise(function (resolve, reject) { var fileReader = new FileReader(); fileReader.onloadend = function (evt) { var view = document.createElement("pre"); view.textContent = evt.target.result; var result = { content, view }; resolve(result); }; fileReader.readAsText(content.blob); }); } export function getBuilders() { return { text: { mediaType: "text/*", builder: buildTextAsHtml } }; }
Revert "Revert "PRA-410: resp changed to interface"" This reverts commit d12fdf8244766409cf0afba7eab9eeb75e0f2708.
package activity import ( "time" "github.com/tolexo/aero/activity/model" "github.com/tolexo/aero/db/tmongo" mgo "gopkg.in/mgo.v2" ) const ( DB_CONTAINER = "database.omni" ) //Log User activity func LogActivity(url string, body interface{}, resp interface{}, respCode int, respTime float64) { apiDetail := model.APIDetail{ Url: url, Body: body, Resp: resp, RespCode: respCode, RespTime: respTime, Time: time.Now(), } if sess, mdb, err := tmongo.GetMongoConn(DB_CONTAINER); err == nil { defer sess.Close() sess.SetSafe(&mgo.Safe{W: 0}) sess.DB(mdb).C("activity").Insert(apiDetail) } }
package activity import ( "reflect" "time" "github.com/tolexo/aero/activity/model" "github.com/tolexo/aero/db/tmongo" mgo "gopkg.in/mgo.v2" ) const ( DB_CONTAINER = "database.omni" ) //Log User activity func LogActivity(url string, body interface{}, resp reflect.Value, respCode int, respTime float64) { apiDetail := model.APIDetail{ Url: url, Body: body, Resp: resp.Interface(), RespCode: respCode, RespTime: respTime, Time: time.Now(), } if sess, mdb, err := tmongo.GetMongoConn(DB_CONTAINER); err == nil { defer sess.Close() sess.SetSafe(&mgo.Safe{W: 0}) sess.DB(mdb).C("activity").Insert(apiDetail) } }
Replace dots with something else on user create and edit screens
<div class="toggle-switch-list dual-column-content"> @foreach($roles as $role) <div> @include('components.custom-checkbox', [ 'name' => $name . '[' . str_replace('.', 'DOT', $role->name) . ']', 'label' => $role->display_name, 'value' => $role->id, 'checked' => old($name . '.' . str_replace('.', 'DOT', $role->name)) || (!old('name') && isset($model) && $model->hasRole($role->name)) ]) </div> @endforeach </div> @if($errors->has($name)) <div class="text-neg text-small">{{ $errors->first($name) }}</div> @endif
<div class="toggle-switch-list dual-column-content"> @foreach($roles as $role) <div> @include('components.custom-checkbox', [ 'name' => $name . '[' . $role->name . ']', 'label' => $role->display_name, 'value' => $role->id, 'checked' => old($name . '.' . $role->name) || (!old('name') && isset($model) && $model->hasRole($role->name)) ]) </div> @endforeach </div> @if($errors->has($name)) <div class="text-neg text-small">{{ $errors->first($name) }}</div> @endif
Include devDependencies in get dependency
// Get the appropriate dependency for a package. var childProcess = require('child_process'); var path = require('path'); var glob = require('glob'); var name = process.argv[2]; // Look in all of the packages. var basePath = path.resolve('.'); var files = glob.sync(path.join(basePath, 'packages/*')); for (var j = 0; j < files.length; j++) { // Read in the package.json. var packagePath = path.join(files[j], 'package.json'); try { var package = require(packagePath); } catch (e) { console.log('Skipping package ' + packagePath); continue; } if (package.name === name) { console.log(package.version); process.exit(0); } var deps = package.dependencies || {}; if (package.devDependencies) { for (var key of Object.keys(package.devDependencies)) { deps[key] = package.devDependencies[key]; } } if (deps[name]) { console.log(deps[name]); process.exit(0); } } console.log('** Package not yet included!'); var cmd = 'npm view ' + name + ' version'; var specifier = childProcess.execSync(cmd); console.log('~' + String(specifier).trim());
// Get the appropriate dependency for a package. var childProcess = require('child_process'); var path = require('path'); var glob = require('glob'); var name = process.argv[2]; // Look in all of the packages. var basePath = path.resolve('.'); var files = glob.sync(path.join(basePath, 'packages/*')); for (var j = 0; j < files.length; j++) { // Read in the package.json. var packagePath = path.join(files[j], 'package.json'); try { var package = require(packagePath); } catch (e) { console.log('Skipping package ' + packagePath); continue; } if (package.name === name) { console.log(package.version); process.exit(0); } var deps = package.dependencies || []; if (deps[name]) { console.log(deps[name]); process.exit(0); } } console.log('** Package not yet included!'); var cmd = 'npm view ' + name + ' version'; var specifier = childProcess.execSync(cmd); console.log('~' + String(specifier).trim());
Update channel object to store ID as a string.
// Copyright 2013 Judson D Neer package com.singledsoftware.mixmaestro; import java.io.Serializable; /** * Stores data for an individual channel. * * @see Serializable * @author Judson D Neer */ public class Channel implements Serializable { // Unique serializable version ID private static final long serialVersionUID = -3705403776567370897L; // Unique identifier for the channel private final String id; // Single character that identifies a channel type // TODO make this an enumeration private final char type; // User-assigned name for the channel private final String name; /** * Constructor. * * @param i New id * @param t New type * @param n New name */ public Channel(String i, char t, String n) { id = i; type = t; name = n; } /** * @see java.io.Serializable#toString() */ @Override public String toString() { // TODO put id and type in parens? return name; } }
// Copyright 2013 Judson D Neer package com.singledsoftware.mixmaestro; import java.io.Serializable; /** * Stores data for an individual channel. * * @see Serializable * @author Judson D Neer */ public class Channel implements Serializable { // Unique serializable version ID private static final long serialVersionUID = -3705403776567370897L; // Unique numeric identifier for the channel private final int id; // Single character that identifies a channel type // TODO make this an enumeration private final char type; // User-assigned name for the channel private final String name; /** * Constructor. * * @param i New id * @param t New type * @param n New name */ public Channel(int i, char t, String n) { id = i; type = t; name = n; } /** * @see java.io.Serializable#toString() */ @Override public String toString() { // TODO put id and type in parens? return name; } }
Fix typo: notifcation -> notification
'use strict'; /** * Module dependencies */ import * as mongo from 'mongodb'; import Notification from '../../../models/notification'; import serialize from '../../../serializers/notification'; import event from '../../../event'; /** * Mark as read a notification * * @param {Object} params * @param {Object} user * @return {Promise<object>} */ module.exports = (params, user) => new Promise(async (res, rej) => { const notificationId = params.notification; if (notificationId === undefined || notificationId === null) { return rej('notification is required'); } // Get notification const notification = await Notification .findOne({ _id: new mongo.ObjectID(notificationId), i: user._id }); if (notification === null) { return rej('notification-not-found'); } // Update notification.is_read = true; Notification.update({ _id: notification._id }, { $set: { is_read: true } }); // Response res(); // Serialize const notificationObj = await serialize(notification); // Publish read_notification event event(user._id, 'read_notification', notificationObj); });
'use strict'; /** * Module dependencies */ import * as mongo from 'mongodb'; import Notification from '../../../models/notification'; import serialize from '../../../serializers/notification'; import event from '../../../event'; /** * Mark as read a notification * * @param {Object} params * @param {Object} user * @return {Promise<object>} */ module.exports = (params, user) => new Promise(async (res, rej) => { const notificationId = params.notification; if (notificationId === undefined || notificationId === null) { return rej('notification is required'); } // Get notifcation const notification = await Notification .findOne({ _id: new mongo.ObjectID(notificationId), i: user._id }); if (notification === null) { return rej('notification-not-found'); } // Update notification.is_read = true; Notification.update({ _id: notification._id }, { $set: { is_read: true } }); // Response res(); // Serialize const notificationObj = await serialize(notification); // Publish read_notification event event(user._id, 'read_notification', notificationObj); });
Fix the order of Session model behaviors.
/* global window */ import feathersClient from './feathers-client'; import feathersSession from 'can-connect-feathers/session'; import connect from 'can-connect'; import dataParse from 'can-connect/data/parse/'; import construct from 'can-connect/constructor/'; import constructStore from 'can-connect/constructor/store/'; import canMap from 'can-connect/can/map/'; import canRef from 'can-connect/can/ref/'; import callbacksOnce from 'can-connect/constructor/callbacks-once/'; import dataCallbacks from 'can-connect/data/callbacks/'; import realtime from 'can-connect/real-time/'; import DefineMap from 'can-define/map/'; import DefineList from 'can-define/list/'; import User from 'bitcentive/models/user'; import canEvent from 'can-event'; export const Session = DefineMap.extend('Session', { seal: false }, { userId: 'any', user: { Type: User, get (lastSetVal, resolve) { if (lastSetVal) { return lastSetVal; } if (this.userId) { User.get({_id: this.userId}).then(resolve); } } } }); Session.connection = connect([ feathersSession, construct, canMap, canRef, constructStore, dataCallbacks, dataParse, realtime, callbacksOnce ], { feathersClient, idProp: 'exp', Map: Session, name: 'session' }); export default Session;
/* global window */ import feathersClient from './feathers-client'; import feathersSession from 'can-connect-feathers/session'; import connect from 'can-connect'; import dataParse from 'can-connect/data/parse/'; import construct from 'can-connect/constructor/'; import constructStore from 'can-connect/constructor/store/'; import constructOnce from 'can-connect/constructor/callbacks-once/'; import canMap from 'can-connect/can/map/'; import canRef from 'can-connect/can/ref/'; import dataCallbacks from 'can-connect/data/callbacks/'; import realtime from 'can-connect/real-time/'; import DefineMap from 'can-define/map/'; import DefineList from 'can-define/list/'; import User from 'bitcentive/models/user'; import canEvent from 'can-event'; export const Session = DefineMap.extend('Session', { seal: false }, { userId: 'any', user: { Type: User, get (lastSetVal, resolve) { if (lastSetVal) { return lastSetVal; } if (this.userId) { User.get({_id: this.userId}).then(resolve); } } } }); Session.connection = connect([ feathersSession, dataParse, construct, constructStore, constructOnce, canMap, canRef, dataCallbacks, realtime ], { feathersClient, idProp: 'exp', Map: Session, name: 'session' }); export default Session;
Fix duplicated calls of sagas based on history
import { createStore, applyMiddleware, compose } from 'redux' import { browserHistory } from 'react-router' import { syncHistoryWithStore, routerMiddleware } from 'react-router-redux' import createReducer from './reducers' import createSagaMiddleware from 'redux-saga' import rootSaga from './sagas' export default function configureStore(initialState = {}) { const sagaMiddleware = createSagaMiddleware() const middlewares = [ sagaMiddleware, routerMiddleware(browserHistory) ] const enhancers = [ applyMiddleware(...middlewares) ] const composeEnhancers = process.env.NODE_ENV !== 'production' && typeof window === 'object' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : compose; const store = createStore( createReducer(), initialState, composeEnhancers(...enhancers) ) sagaMiddleware.run(rootSaga, browserHistory) return { store, history: syncHistoryWithStore(browserHistory, store) } }
import { createStore, applyMiddleware, compose } from 'redux' import { browserHistory} from 'react-router' import { syncHistoryWithStore, routerMiddleware } from 'react-router-redux' import createReducer from './reducers' import createSagaMiddleware from 'redux-saga' import rootSaga from './sagas' export default function configureStore(initialState = {}) { const sagaMiddleware = createSagaMiddleware() const history = browserHistory const middlewares = [ sagaMiddleware, routerMiddleware(history) ] const enhancers = [ applyMiddleware(...middlewares) ] const composeEnhancers = process.env.NODE_ENV !== 'production' && typeof window === 'object' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : compose; const store = createStore( createReducer(), initialState, composeEnhancers(...enhancers) ) const syncedHistory = syncHistoryWithStore(history, store) sagaMiddleware.run(rootSaga, syncedHistory) return { store, history: syncedHistory } }
:guitar: Make posts insertable/editable by members
import { Posts } from 'meteor/example-forum'; /* Let's assign a color to each post (why? cause we want to, that's why). We'll do that by adding a custom field to the Posts collection. Note that this requires our custom package to depend on vulcan:posts and vulcan:users. */ Posts.addField([ { fieldName: 'soundcloud', fieldSchema: { type: String, control: 'text', optional: true, insertableBy: ['members'], editableBy: ['members'], viewableBy: ['guests'], }, }, { fieldName: 'canBring', fieldSchema: { type: String, control: 'text', optional: true, insertableBy: ['members'], editableBy: ['members'], viewableBy: ['guests'], }, }, { fieldName: 'minimumCharge', fieldSchema: { type: String, control: 'text', optional: true, insertableBy: ['members'], editableBy: ['members'], viewableBy: ['guests'], }, }, ])
import { Posts } from 'meteor/example-forum'; /* Let's assign a color to each post (why? cause we want to, that's why). We'll do that by adding a custom field to the Posts collection. Note that this requires our custom package to depend on vulcan:posts and vulcan:users. */ Posts.addField([ { fieldName: 'soundcloud', fieldSchema: { type: String, control: 'text', optional: true, insertableBy: ['admins'], editableBy: ['admins'], viewableBy: ['guests'], }, }, { fieldName: 'canBring', fieldSchema: { type: String, control: 'text', optional: true, insertableBy: ['admins'], editableBy: ['admins'], viewableBy: ['guests'], }, }, { fieldName: 'minimumCharge', fieldSchema: { type: String, control: 'text', optional: true, insertableBy: ['admins'], editableBy: ['admins'], viewableBy: ['guests'], }, }, ])
Fix menu items for noi/tickets
# -*- coding: UTF-8 -*- # Copyright 2016 Luc Saffre # License: BSD (see file COPYING for details) """Fixtures specific for the Team variant of Lino Noi. .. autosummary:: :toctree: models """ from lino_xl.lib.tickets import * class Plugin(Plugin): """Adds the :mod:`lino_xl.lib.votes` plugin. """ extends_models = ['Ticket'] needs_plugins = [ 'lino_xl.lib.excerpts', 'lino_xl.lib.topics', 'lino.modlib.comments', 'lino.modlib.changes', # 'lino_xl.lib.votes', 'lino_noi.lib.noi'] def setup_main_menu(self, site, profile, m): super(Plugin, self).setup_main_menu(site, profile, m) p = self.get_menu_group() m = m.add_menu(p.app_label, p.verbose_name) m.add_action('tickets.MyTicketsToWork') def get_dashboard_items(self, user): super(Plugin, self).get_dashboard_items(user) if user.authenticated: yield self.site.actors.tickets.MyTicketsToWork # else: # yield self.site.actors.tickets. PublicTickets
# -*- coding: UTF-8 -*- # Copyright 2016 Luc Saffre # License: BSD (see file COPYING for details) """Fixtures specific for the Team variant of Lino Noi. .. autosummary:: :toctree: models """ from lino_xl.lib.tickets import * class Plugin(Plugin): """Adds the :mod:`lino_xl.lib.votes` plugin. """ extends_models = ['Ticket'] needs_plugins = [ 'lino_xl.lib.excerpts', 'lino_xl.lib.topics', 'lino.modlib.comments', 'lino.modlib.changes', # 'lino_xl.lib.votes', 'lino_noi.lib.noi'] def setup_main_menu(self, site, profile, m): p = self.get_menu_group() m = m.add_menu(p.app_label, p.verbose_name) m.add_action('tickets.MyTicketsToWork') def get_dashboard_items(self, user): if user.authenticated: yield self.site.actors.tickets.MyTicketsToWork # else: # yield self.site.actors.tickets. PublicTickets
Disable formatting for renderer logs to file
import { createStore, applyMiddleware } from 'redux'; import thunkMiddleware from 'redux-thunk'; import rootReducer from '../reducers'; import { createLogger } from '../../browser/remote'; const middlewares = [thunkMiddleware]; /* eslint global-require:0 */ if (global.SQLECTRON_CONFIG.log.console) { const loggerConfig = { level: global.SQLECTRON_CONFIG.log.level, collapsed: true, }; if (global.SQLECTRON_CONFIG.log.file) { const logger = createLogger('renderer:redux'); logger.log = logger.debug.bind(logger); loggerConfig.logger = logger; loggerConfig.colors = {}; // disable formatting // log only the error messages // otherwise is too much private information // the user would need to remove to issue a bug loggerConfig.stateTransformer = () => null; loggerConfig.actionTransformer = (data) => { const error = data && data.error; return { error }; }; } middlewares.push(require('redux-logger')(loggerConfig)); } const createStoreWithMiddleware = applyMiddleware( ...middlewares )(createStore); export default function configureStore(initialState) { const store = createStoreWithMiddleware(rootReducer, initialState); if (module.hot) { module.hot.accept('../reducers', () => store.replaceReducer(require('../reducers').default) ); } return store; }
import { createStore, applyMiddleware } from 'redux'; import thunkMiddleware from 'redux-thunk'; import rootReducer from '../reducers'; import { createLogger } from '../../browser/remote'; const middlewares = [thunkMiddleware]; /* eslint global-require:0 */ if (global.SQLECTRON_CONFIG.log.console) { const loggerConfig = { level: global.SQLECTRON_CONFIG.log.level, collapsed: true, }; if (global.SQLECTRON_CONFIG.log.file) { const logger = createLogger('renderer:redux'); logger.log = logger.debug.bind(logger); loggerConfig.logger = logger; // log only the error messages // otherwise is too much private information // the user would need to remove to issue a bug loggerConfig.stateTransformer = () => null; loggerConfig.actionTransformer = (data) => { const error = data && data.error; return { error }; }; } middlewares.push(require('redux-logger')(loggerConfig)); } const createStoreWithMiddleware = applyMiddleware( ...middlewares )(createStore); export default function configureStore(initialState) { const store = createStoreWithMiddleware(rootReducer, initialState); if (module.hot) { module.hot.accept('../reducers', () => store.replaceReducer(require('../reducers').default) ); } return store; }
Make sure the tail subprocess does not actually list any prior records Signed-off-by: Jason Bernardino Alonso <f71c42a1353bbcdbe07e24c2a1c893f8ea1d05ee@hackorp.com>
""" Utility functions for dhcp2nest """ from queue import Queue from subprocess import Popen, PIPE from threading import Thread def follow_file(fn, max_lines=100): """ Return a Queue that is fed lines (up to max_lines) from the given file (fn) continuously The implementation given here was inspired by http://stackoverflow.com/questions/12523044/how-can-i-tail-a-log-file-in-python """ fq = Queue(maxsize=max_lines) # Declare the helper routine def _follow_file_thread(fn, fq): # Use system tail with name-based following and retry p = Popen(["tail", "-n0", "-F", fn], stdout=PIPE) # Loop forever on pulling data from tail line = True while line: line = p.stdout.readline().decode('utf-8') fq.put(line) # Spawn a thread to read data from tail Thread(target=_follow_file_thread, args=(fn, fq)).start() # Return the queue return fq
""" Utility functions for dhcp2nest """ from queue import Queue from subprocess import Popen, PIPE from threading import Thread def follow_file(fn, max_lines=100): """ Return a Queue that is fed lines (up to max_lines) from the given file (fn) continuously The implementation given here was inspired by http://stackoverflow.com/questions/12523044/how-can-i-tail-a-log-file-in-python """ fq = Queue(maxsize=max_lines) # Declare the helper routine def _follow_file_thread(fn, fq): # Use system tail with name-based following and retry p = Popen(["tail", "-F", fn], stdout=PIPE) # Loop forever on pulling data from tail line = True while line: line = p.stdout.readline().decode('utf-8') fq.put(line) # Spawn a thread to read data from tail Thread(target=_follow_file_thread, args=(fn, fq)).start() # Return the queue return fq
Use RTS URL passed through
/* Copyright 2016 OpenMarket Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ 'use strict'; var React = require("react"); var MatrixClientPeg = require('matrix-react-sdk/lib/MatrixClientPeg'); var sdk = require('matrix-react-sdk'); module.exports = React.createClass({ displayName: 'HomePage', propTypes: { teamServerUrl: React.PropTypes.string.isRequired, teamToken: React.PropTypes.string.isRequired, collapsedRhs: React.PropTypes.bool, }, render: function() { // const SimpleRoomHeader = sdk.getComponent('rooms.SimpleRoomHeader'); // <SimpleRoomHeader title="Welcome to Riot" collapsedRhs={ this.props.collapsedRhs }/> return ( <div className="mx_HomePage"> <iframe src={`${this.props.teamServerUrl}/static/${this.props.teamToken}/welcome.html`} style={{width: '100%', border: 'none'}}/> </div> ); } });
/* Copyright 2016 OpenMarket Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ 'use strict'; var React = require("react"); var MatrixClientPeg = require('matrix-react-sdk/lib/MatrixClientPeg'); var sdk = require('matrix-react-sdk'); module.exports = React.createClass({ displayName: 'HomePage', propTypes: { teamToken: React.PropTypes.string.isRequired, collapsedRhs: React.PropTypes.bool, }, render: function() { // const SimpleRoomHeader = sdk.getComponent('rooms.SimpleRoomHeader'); // <SimpleRoomHeader title="Welcome to Riot" collapsedRhs={ this.props.collapsedRhs }/> return ( <div className="mx_HomePage"> <iframe src={`http://localhost:7000/static/${this.props.teamToken}/welcome.html`} style={{width: '100%', border: 'none'}}/> </div> ); } });
Update password reminders with new configuration. Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class OrchestraAuthCreatePasswordRemindersTable extends Migration { /** * Table name. * * @var string */ protected $table; /** * Construct a new password reminder schema. */ public function __construct() { $resetter = config('auth.default_resetter'); $this->table = config("auth.resetters.{$resetter}.table"); } /** * Run the migrations. * * @return void */ public function up() { Schema::create($this->table, function (Blueprint $table) { $table->string('email')->index(); $table->string('token')->index(); $table->timestamp('created_at'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop($this->table); } }
<?php use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class OrchestraAuthCreatePasswordRemindersTable extends Migration { /** * Table name. * * @var string */ protected $table; /** * Construct a new password reminder schema. */ public function __construct() { $this->table = Config::get('auth.password.table'); } /** * Run the migrations. * * @return void */ public function up() { Schema::create($this->table, function (Blueprint $table) { $table->string('email')->index(); $table->string('token')->index(); $table->timestamp('created_at'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop($this->table); } }
Fix formatting and typo in docblock
<?php namespace MikeVrind\Deployer\Controllers; use Illuminate\Console\Command; use MikeVrind\Deployer\Deployer; class DeployCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'deployer:deploy'; /** * The console command description. * * @var string */ protected $description = 'Manually execute the deploy commands without a webhook'; /** * Holds in instance of the actual Deployer * * @var Deployer */ protected $deployer; /** * @param Deployer $deployer */ public function __construct( Deployer $deployer ) { $this->deployer = $deployer; parent::__construct(); } /** * Execute the deployer * * @return void */ public function fire() { if( $this->confirm( 'Do you wish to manually run the deployer commands? [y|N]' ) ) { if( $this->deployer->deploy() ) { $this->info( 'Deployment successful' ); } else { $this->error( $this->deployer->getErrorMessage() ); } } } }
<?php namespace MikeVrind\Deployer\Controllers; use Illuminate\Console\Command; use MikeVrind\Deployer\Deployer; class DeployCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'deployer:deploy'; /** * The console command description. * * @var string */ protected $description = 'Manually execute the deplot commands without a webhook'; /** * Holds in instance of the actual Deployer * * @var Deployer */ protected $deployer; /** * @param Deployer $deployer */ public function __construct(Deployer $deployer) { $this->deployer = $deployer; parent::__construct(); } /** * Execute the deployer * * @return void */ public function fire() { if ( $this->confirm('Do you wish to manually run the deployer commands? [y|N]')) { if( $this->deployer->deploy() ) { $this->info('Deployment successful'); } else { $this->error($this->deployer->getErrorMessage()); } } } }
Fix issues when response is 200 with no content.
import 'isomorphic-fetch' import { call, select } from 'redux-saga/effects' import { accessTokenSelector } from './selectors' export function* fetchCredentials() { const accessToken = yield select(accessTokenSelector) if (accessToken) { return { token: { access_token: accessToken, }, } } const tokenPath = (typeof window === 'undefined') ? `http://localhost:${process.env.PORT || 6660}/api/webapp-token` : `${document.location.protocol}//${document.location.host}/api/webapp-token` try { const response = yield call(fetch, tokenPath, { credentials: 'same-origin' }) if (response.ok) { // Pass response as binding for response.json return yield call([response, response.json]) } return response } catch (_err) { return yield call(fetchCredentials) } } function checkStatus(response) { if (response.ok) { return response } const error = new Error(response.statusText) error.response = response throw error } export function extractJSON(response) { return response ? response.json() : response } export function* sagaFetch(path, options) { const response = yield call(fetch, path, options) checkStatus(response) // allow for the json to be empty for a 201/202/204 let json = {} if (response.status === 200) { json = yield call(extractJSON, response) } return { serverResponse: response, json } }
import 'isomorphic-fetch' import { call, select } from 'redux-saga/effects' import { accessTokenSelector } from './selectors' export function* fetchCredentials() { const accessToken = yield select(accessTokenSelector) if (accessToken) { return { token: { access_token: accessToken, }, } } const tokenPath = (typeof window === 'undefined') ? `http://localhost:${process.env.PORT || 6660}/api/webapp-token` : `${document.location.protocol}//${document.location.host}/api/webapp-token` try { const response = yield call(fetch, tokenPath, { credentials: 'same-origin' }) if (response.ok) { // Pass response as binding for response.json return yield call([response, response.json]) } return response } catch (_err) { return yield call(fetchCredentials) } } function checkStatus(response) { if (response.ok) { return response } const error = new Error(response.statusText) error.response = response throw error } export function extractJSON(response) { return response ? response.json() : response } export function* sagaFetch(path, options) { const response = yield call(fetch, path, options) checkStatus(response) // allow for the json to be empty for a 204 let json = {} if (response.status !== 204) { json = yield call(extractJSON, response) } return { serverResponse: response, json } }