text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Set default timezone based on config.
<?php /** * Bitcoin Status Page * * @category File * @package BitcoinStatus * @author Craig Watson <craig@cwatson.org> * @license https://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0 * @link https://github.com/craigwatson/bitcoind-status */ if (!is_file('./php/config.php')) { die("Configuration file not found. To continue, please create a config.php file."); } require_once './php/config.php'; require_once './php/functions.php'; if ($config['timezone'] !== null) { date_default_timezone_set($config['timezone']); } // If we're good to clear cache, remove cache file if (isset($_GET['clearcache']) & in_array($_SERVER['REMOTE_ADDR'], $config['nocache_whitelist']) & is_file($config['cache_file'])) { unlink($config['cache_file']); $cache_message = 'Cache has been cleared!'; } // Check if we need to use the cache if ($config['use_cache'] === false) { $use_cache = false; } elseif (isset($_GET['nocache']) & in_array($_SERVER['REMOTE_ADDR'], $config['nocache_whitelist'])) { $use_cache = false; $cache_message = 'Cache has been bypassed!'; } else { $use_cache = true; } // Get the data $data = getData($use_cache); // Add the IP of the server, and include template require_once './html/template.html';
<?php /** * Bitcoin Status Page * * @category File * @package BitcoinStatus * @author Craig Watson <craig@cwatson.org> * @license https://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0 * @link https://github.com/craigwatson/bitcoind-status */ if (!is_file('./php/config.php')) { die("Configuration file not found. To continue, please create a config.php file."); } require_once './php/config.php'; require_once './php/functions.php'; // If we're good to clear cache, remove cache file if (isset($_GET['clearcache']) & in_array($_SERVER['REMOTE_ADDR'], $config['nocache_whitelist']) & is_file($config['cache_file'])) { unlink($config['cache_file']); $cache_message = 'Cache has been cleared!'; } // Check if we need to use the cache if ($config['use_cache'] === false) { $use_cache = false; } elseif (isset($_GET['nocache']) & in_array($_SERVER['REMOTE_ADDR'], $config['nocache_whitelist'])) { $use_cache = false; $cache_message = 'Cache has been bypassed!'; } else { $use_cache = true; } // Get the data $data = getData($use_cache); // Add the IP of the server, and include template require_once './html/template.html';
Fix null insertion in data context
import { EJSON } from 'meteor/ejson'; /* eslint-disable no-undef, import/no-extraneous-dependencies, import/no-unresolved, import/extensions, max-len */ import serialize from 'serialize-javascript'; /* eslint-enable */ import { valueSet } from '../../shared/actions/utils'; // Impure function /* eslint-disable no-param-reassign */ const fixedEncodeURIComponent = str => ( encodeURIComponent(str) .replace(/[!'()*]/g, c => `%${c.charCodeAt(0).toString(16)}`) ); const createDataContext = (stepResults) => { if (stepResults.isFromCache) return; stepResults.store.dispatch(valueSet('buildDate', (new Date()).valueOf())); const serialized = EJSON.stringify(stepResults.store.getState()); const encoded = fixedEncodeURIComponent(serialized); let i18n = ''; if (stepResults.i18nOptions) { i18n = `;window.__i18n='${serialize(stepResults.i18nOptions.client)}'`; } stepResults.contextMarkup = `<script>window.__PRELOADED_STATE__='${encoded}'${i18n}</script>`; }; export default createDataContext;
import { EJSON } from 'meteor/ejson'; /* eslint-disable no-undef, import/no-extraneous-dependencies, import/no-unresolved, import/extensions, max-len */ import serialize from 'serialize-javascript'; /* eslint-enable */ import { valueSet } from '../../shared/actions/utils'; // Impure function /* eslint-disable no-param-reassign */ const fixedEncodeURIComponent = str => ( encodeURIComponent(str) .replace(/[!'()*]/g, c => `%${c.charCodeAt(0).toString(16)}`) ); const createDataContext = (stepResults) => { if (stepResults.isFromCache) { return; } stepResults.store.dispatch(valueSet('buildDate', (new Date()).valueOf())); const serialized = EJSON.stringify(stepResults.store.getState()); const encoded = fixedEncodeURIComponent(serialized); let i18n = null; if (stepResults.i18nOptions) { i18n = `window.__i18n='${serialize(stepResults.i18nOptions.client)}';`; } stepResults.contextMarkup = ` <script>window.__PRELOADED_STATE__='${encoded}'; ${i18n}</script>`; }; export default createDataContext;
Fix comments count in topic detail
package org.mazhuang.guanggoo.data.entity; import java.util.Map; /** * * @author mazhuang * @date 2017/9/17 */ public class TopicDetail { private Favorite favorite; private Topic topic; private String content; private Map<Integer, Comment> comments; public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Map<Integer, Comment> getComments() { return comments; } public void setComments(Map<Integer, Comment> comments) { this.comments = comments; } public Topic getTopic() { return topic; } public void setTopic(Topic topic) { this.topic = topic; } public Favorite getFavorite() { return favorite; } public void setFavorite(Favorite favorite) { this.favorite = favorite; } public int getCommentsCount() { if (comments == null || comments.isEmpty()) { return 0; } Integer max = 0; for (Integer i : comments.keySet()) { max = Math.max(i, max); } return max; } }
package org.mazhuang.guanggoo.data.entity; import java.util.Map; /** * * @author mazhuang * @date 2017/9/17 */ public class TopicDetail { private Favorite favorite; private Topic topic; private String content; private Map<Integer, Comment> comments; public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Map<Integer, Comment> getComments() { return comments; } public void setComments(Map<Integer, Comment> comments) { this.comments = comments; } public Topic getTopic() { return topic; } public void setTopic(Topic topic) { this.topic = topic; } public Favorite getFavorite() { return favorite; } public void setFavorite(Favorite favorite) { this.favorite = favorite; } public int getCommentsCount() { if (comments == null || comments.isEmpty()) { return 0; } Integer max = 0; for (Integer i : comments.keySet()) { max = Math.max(i, 0); } return max; } }
Add newlines after class bracket
package com.kevinsimard.lambda.function; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; @SuppressWarnings("unused") public class Example implements RequestHandler<Example.Request, Example.Response> { public Response handleRequest(Request request, Context context) { return new Response(request.message); } static class Request { private String message; public void setMessage(String message) { this.message = message; } private Request() {} } static class Response { private String message; public String getMessage() { return this.message; } private Response(String message) { this.message = message; } } }
package com.kevinsimard.lambda.function; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; @SuppressWarnings("unused") public class Example implements RequestHandler<Example.Request, Example.Response> { public Response handleRequest(Request request, Context context) { return new Response(request.message); } static class Request { public String message; public void setMessage(String message) { this.message = message; } private Request() { // } } static class Response { public String message; public String getMessage() { return this.message; } private Response(String message) { this.message = message; } } }
Allow function to be provided args
import { nextCoord } from './utils'; export function tile(coord) { coord = coord || { x: this.x, y: this.y }; return pixelToTile({ x: coord.x, y: coord.y, }); } export function nextTile(tile, faceDirection) { tile = tile || this.tile; faceDirection = faceDirection || this.faceDirection; return nextCoord(tile, faceDirection, 1); } export function pixelToTile(pixelCoord) { return { x: Math.floor(pixelCoord.x / 32), y: Math.floor(pixelCoord.y / 32), }; } export function tileToPixel(tileCoord) { return { x: (tileCoord.x * 32) + 16, y: (tileCoord.y * 32) + 16, }; } export function alignToGrid(pixelCoord) { if (pixelCoord.x % 16 === 0 && pixelCoord.y % 16 === 0) return pixelCoord; // perhaps not the most efficient way to do this return tileToPixel(pixelToTile(pixelCoord)); }
import { nextCoord } from './utils'; export function tile() { return pixelToTile({ x: this.x, y: this.y, }); } export function nextTile(tile, faceDirection) { tile = tile || this.tile; faceDirection = faceDirection || this.faceDirection; return nextCoord(tile, faceDirection, 1); } export function pixelToTile(pixelCoord) { return { x: Math.floor(pixelCoord.x / 32), y: Math.floor(pixelCoord.y / 32), }; } export function tileToPixel(tileCoord) { return { x: (tileCoord.x * 32) + 16, y: (tileCoord.y * 32) + 16, }; } export function alignToGrid(pixelCoord) { if (pixelCoord.x % 16 === 0 && pixelCoord.y % 16 === 0) return pixelCoord; // perhaps not the most efficient way to do this return tileToPixel(pixelToTile(pixelCoord)); }
Allow latest targets, map to '*'-
var semver = require('semver'); var createError = require('./createError'); function decompose(endpoint) { var regExp = /^(?:([\w\-]|(?:[\w\.\-]+[\w\-])?)=)?([^\|#]+)(?:#(.*))?$/; var matches = endpoint.match(regExp); var target; if (!matches) { throw createError('Invalid endpoint: ' + endpoint, 'EINVEND'); } target = matches[3]; return { name: matches[1] || '', source: matches[2], target: !target || target === 'latest' ? '*' : target }; } function compose(decEndpoint) { var composed = ''; if (decEndpoint.name) { composed += decEndpoint.name + '='; } composed += decEndpoint.source; if (decEndpoint.target) { composed += '#' + decEndpoint.target; } return composed; } function json2decomposed(key, value) { var endpoint = key + '='; if (value === 'latest' || semver.valid(value) != null || semver.validRange(value) != null) { endpoint += key + '#' + value; } else { endpoint += value; } return decompose(endpoint); } module.exports.decompose = decompose; module.exports.compose = compose; module.exports.json2decomposed = json2decomposed;
var semver = require('semver'); var createError = require('./createError'); function decompose(endpoint) { var regExp = /^(?:([\w\-]|(?:[\w\.\-]+[\w\-])?)=)?([^\|#]+)(?:#(.*))?$/; var matches = endpoint.match(regExp); if (!matches) { throw createError('Invalid endpoint: ' + endpoint, 'EINVEND'); } return { name: matches[1] || '', source: matches[2], target: matches[3] || '*' }; } function compose(decEndpoint) { var composed = ''; if (decEndpoint.name) { composed += decEndpoint.name + '='; } composed += decEndpoint.source; if (decEndpoint.target) { composed += '#' + decEndpoint.target; } return composed; } function json2decomposed(key, value) { var endpoint = key + '='; if (semver.valid(value) != null || semver.validRange(value) != null) { endpoint += key + '#' + value; } else { endpoint += value; } return decompose(endpoint); } module.exports.decompose = decompose; module.exports.compose = compose; module.exports.json2decomposed = json2decomposed;
[MIG] Migrate l10n_br_data_base to version 10
# -*- coding: utf-8 -*- # Copyright (C) 2009 - TODAY Renato Lima - Akretion # # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html { 'name': 'Brazilian Localisation Data Extension for Base', 'license': 'AGPL-3', 'author': 'Akretion, Odoo Community Association (OCA)', 'version': '10.0.0.0.0', 'depends': [ 'l10n_br_base', ], 'data': [ 'data/res.bank.csv', ], 'demo': [], 'category': 'Localisation', 'installable': True, 'auto_install': True, }
# -*- coding: utf-8 -*- # Copyright (C) 2009 - TODAY Renato Lima - Akretion # # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html { 'name': 'Brazilian Localisation Data Extension for Base', 'license': 'AGPL-3', 'author': 'Akretion, Odoo Community Association (OCA)', 'version': '8.0.1.0.1', 'depends': [ 'l10n_br_base', ], 'data': [ 'data/res.bank.csv', ], 'demo': [], 'category': 'Localisation', 'installable': True, 'auto_install': True, }
Enable using : to indicate . namespacing for mongo.
module.exports = { events: { 'submit': 'filter' }, attach: function() { var _view = this; _view.regex = []; this.$('input[data-regex]').each(function() { _view.regex.push({ el: this, namespace: this.name.split('.').map(function(value) { return value.split(':').join('.'); }), flags: $(this).data('flags') || '' }); }); }, filter: function(e) { var _view = this; e.preventDefault(); var filter = $(e.currentTarget).JSONify(); _view.regex.forEach(function(obj) { if(!obj.el.value) return; for(var i = 0, ref = filter; i < obj.namespace.length - 1; i++) { ref = ref[obj.namespace[i]]; } ref[obj.namespace[i]] = '/' + obj.el.value + '/' + obj.flags; }); _view.collection.setFilter(filter); _view.collection.fetch({ reset: true }); } };
module.exports = { events: { 'submit': 'filter' }, attach: function() { var _view = this; _view.regex = []; this.$('input[data-regex]').each(function() { _view.regex.push({ el: this, namespace: this.name.split('.'), flags: $(this).data('flags') || '' }); }); }, filter: function(e) { var _view = this; e.preventDefault(); var filter = $(e.currentTarget).JSONify(); _view.regex.forEach(function(obj) { if(!obj.el.value) return; for(var i = 0, ref = filter; i < obj.namespace.length - 1; i++) { ref = ref[obj.namespace[i]]; } ref[obj.namespace[i]] = '/' + obj.el.value + '/' + obj.flags; }); _view.collection.setFilter(filter); _view.collection.fetch({ reset: true }); } };
Change type to shipment in dispatching.
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class EcontDispatching extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::setConnection(DB::connection(Config::get('econt.connection')))->create('econt_dispatching', function (Blueprint $table) { $table->unsignedInteger('settlement_id'); $table->enum('direction', ['from', 'to'])->index('idx_direction'); $table->enum('shipment', ['courier', 'cargo_pallet', 'cargo_express', 'post'])->index('idx_shipment'); $table->unsignedInteger('office_code'); $table->primary(['settlement_id', 'direction', 'type', 'office_code']); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::setConnection(DB::connection(Config::get('econt.connection')))->dropIfExists('econt_dispatching'); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class EcontDispatching extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::setConnection(DB::connection(Config::get('econt.connection')))->create('econt_dispatching', function (Blueprint $table) { $table->unsignedInteger('settlement_id'); $table->enum('direction', ['from', 'to'])->index('idx_direction'); $table->enum('shipment', ['courier', 'cargo_pallet', 'cargo_express', 'post'])->index('idx_type'); $table->unsignedInteger('office_code'); $table->primary(['settlement_id', 'direction', 'type', 'office_code']); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::setConnection(DB::connection(Config::get('econt.connection')))->dropIfExists('econt_dispatching'); } }
Add a limit in ls command. AcceptMore middleware now works correctly. Signed-off-by: François de Metz <5187da0b934cc25eb2201a3ec9206c24b13cb23b@2metz.fr>
var intervals = require('./intervals') , Table = require('cli-table') , utils = require('./utils') ; module.exports = function(conf, opts) { var dates = utils.parseDate(opts.date); var start = dates[0]; var end = dates[dates.length - 1]; console.log("Show timesheet from %s to %s", start, end); var client = intervals.createClient(conf.token); client.me(function(err, res) { if (err) throw err; client.time({personid: res.body.personid, datebegin: start, dateend: end, limit: 10}, function(err, response) { showTime(response.body); }); }); } function showTime(body) { // instantiate var table = new Table({ head: ['Project', 'date', 'hours', 'billable'] , colWidths: [42, 12, 7, 10] }); body.time.forEach(function(time) { table.push([time.project, time.dateiso, time.time, (time.billable == 'f' ? 'no' : 'yes')]) }); console.log(table.toString()); }
var intervals = require('./intervals') , Table = require('cli-table') , utils = require('./utils') ; module.exports = function(conf, opts) { var dates = utils.parseDate(opts.date); var start = dates[0]; var end = dates[dates.length - 1]; console.log("Show timesheet from %s to %s", start, end); var client = intervals.createClient(conf.token); client.me(function(err, res) { if (err) throw err; client.time({personid: res.body.personid, datebegin: start, dateend: end}, function(err, response) { showTime(response.body); }); }); } function showTime(body) { // instantiate var table = new Table({ head: ['Project', 'date', 'hours', 'billable'] , colWidths: [42, 12, 7, 10] }); body.time.forEach(function(time) { table.push([time.project, time.dateiso, time.time, (time.billable == 'f' ? 'no' : 'yes')]) }); console.log(table.toString()); }
Support for multiple storage names
// Returns primitive { ownerId: sortIndexValue } map for provided sortKeyPath 'use strict'; var ensureString = require('es5-ext/object/validate-stringifiable-value') , ee = require('event-emitter') , memoize = require('memoizee') , dbDriver = require('mano').dbDriver , isArray = Array.isArray; module.exports = memoize(function (storageName, sortKeyPath) { var itemsMap = ee(), storages; if (isArray(storageName)) { storages = storageName.map(function (storageName) { return dbDriver.getStorage(storageName); }); } else { storages = [dbDriver.getStorage(storageName)]; } storages.forEach(function (storage) { storage.on('key:' + (sortKeyPath + '&'), function (event) { if (!itemsMap[event.ownerId]) { itemsMap[event.ownerId] = { id: event.ownerId, stamp: event.data.stamp }; } else { itemsMap[event.ownerId].stamp = event.data.stamp; } itemsMap.emit('update', event); }); }); return itemsMap; }, { primitive: true, resolvers: [function (storageName) { if (isArray(storageName)) return storageName.map(ensureString).sort(); return ensureString(storageName); }, function (sortKeyPath) { return (sortKeyPath == null) ? '' : String(sortKeyPath); }] });
// Returns primitive { ownerId: sortIndexValue } map for provided sortKeyPath 'use strict'; var ensureString = require('es5-ext/object/validate-stringifiable-value') , ee = require('event-emitter') , memoize = require('memoizee') , dbDriver = require('mano').dbDriver; module.exports = memoize(function (storageName, sortKeyPath) { var itemsMap = ee(); dbDriver.getStorage(storageName).on('key:' + (sortKeyPath + '&'), function (event) { if (!itemsMap[event.ownerId]) { itemsMap[event.ownerId] = { id: event.ownerId, stamp: event.data.stamp }; } else { itemsMap[event.ownerId].stamp = event.data.stamp; } itemsMap.emit('update', event); }); return itemsMap; }, { primitive: true, resolvers: [ensureString, function (sortKeyPath) { return (sortKeyPath == null) ? '' : String(sortKeyPath); }] });
Revert "changes in locator_50 file (current and old versions)" This reverts commit 819dfa4ed2033c1f82973edb09215b96d3c4b188.
from locators_51 import * import copy npsp_lex_locators = copy.deepcopy(npsp_lex_locators) npsp_lex_locators['delete_icon']='//span[contains(text() ,"{}")]/following::span[. = "{}"]/following-sibling::a/child::span[@class = "deleteIcon"]' npsp_lex_locators['object']['field']= "//div[contains(@class, 'uiInput')][.//label[contains(@class, 'uiLabel')][.//span[text()='{}']]]//*[self::input or self::textarea]" npsp_lex_locators["record"]["related"]["dd-link"]='//div[contains(@class,"actionMenu")]//a[@title="{}"]' npsp_lex_locators["record"]["related"]["button"]="//article[contains(@class, 'slds-card slds-card_boundary')][.//img][.//span[@title='{}']]//a[@title='{}']"
from locators_51 import * import copy npsp_lex_locators = copy.deepcopy(npsp_lex_locators) # current version (Sravani's ) npsp_lex_locators['delete_icon']='//span[contains(text() ,"{}")]/following::span[. = "{}"]/following-sibling::a/child::span[@class = "deleteIcon"]' npsp_lex_locators['object']['field']= "//div[contains(@class, 'uiInput')][.//label[contains(@class, 'uiLabel')][.//span[text()='{}']]]//*[self::input or self::textarea]" npsp_lex_locators["record"]["related"]["dd-link"]='//div[contains(@class,"actionMenu")]//a[@title="{}"]' npsp_lex_locators["record"]["related"]["button"]="//article[contains(@class, 'slds-card slds-card_boundary')][.//img][.//span[@title='{}']]//a[@title='{}']" # stashed (Noah's version) # npsp_lex_locators["delete_icon"]= "//span[contains(text(),'{}')]/../following::div//span[text() = '{}']/following-sibling::a/child::span[@class = 'deleteIcon']" # npsp_lex_locators['object']['field']= "//div[contains(@class, 'uiInput')][.//label[contains(@class, 'uiLabel')][.//span[text()='{}']]]//*[self::input or self::textarea]" # npsp_lex_locators["record"]["related"]["dd-link"]='//div[contains(@class,"actionMenu")]//a[@title="{}"]'
Update file to exclude User Stories.
##PSEUDOCODE input: An array of numbers output: 1) the sum of all the numbers inside the array, 2) the "mean" average of the numbers inside the array, 3) the median number from the array # Create an array of single-digit numbers # Iterate through the array of numbers to calculate and return its sum (non-destructively) # Define a method that accepts the array as an argument and returns the "mean" average # Divide the sum of the array by the amount of numbers inside the array # Return the "mean average" number # Define a method that accepts the array as an argument and returns the "median" number # Sort the array in ascending order # IF array length odd?, # Subtract the array(by length) by 1, and divide by 2 # return median value # ELSE if array length even?, # Take array(by length) and divide by 2, # add this value to the value of # The array(by length), subtracted by 1, divided by 2 # Take the sum of these index values and divide by 2 # return median value
##USER STORIES // /As a user i’d like to do three things to a list of numbers. // Using “sum” and the list I want to add together all the numbers whether the list is even or odd in length. // I’d like to use “mean” to return the average of all the numbers in the list. // Finally I’d like to use “median” to return the median number of the list./ ##PSEUDOCODE input: An array of numbers output: 1) the sum of all the numbers inside the array, 2) the "mean" average of the numbers inside the array, 3) the median number from the array # Create an array of single-digit numbers # Iterate through the array of numbers to calculate and return its sum (non-destructively) # Define a method that accepts the array as an argument and returns the "mean" average # Divide the sum of the array by the amount of numbers inside the array # Return the "mean average" number # Define a method that accepts the array as an argument and returns the "median" number # Sort the array in ascending order # IF array length odd?, # Subtract the array(by length) by 1, and divide by 2 # return median value # ELSE if array length even?, # Take array(by length) and divide by 2, # add this value to the value of # The array(by length), subtracted by 1, divided by 2 # Take the sum of these index values and divide by 2 # return median value
Verify if any file was choosen inside of the iframe load handler.
var Bind = require("github/jillix/bind"); var Events = require("github/jillix/events"); module.exports = function(config) { var self = this; Events.call(self, config); var $iframe = $("iframe", self.dom); $("form", self.dom).on("submit", function () { var $form = $(this); $iframe.off("load"); $iframe.on("load", function () { var result = $(this.contentWindow.document).text(); if (!result) { return; } var $inputFile = $form.find("input[type='file']"); if (!$inputFile.val()) { return; } try { result = JSON.parse(result); } catch (e) { // nothing to do } self.emit("fileUploaded", result); var $iframeClone = $iframe.clone(); $iframe.attr("src", ""); $inputFile.replaceWith($inputFile.clone(true)); }); }); self.emit("ready", config); };
var Bind = require("github/jillix/bind"); var Events = require("github/jillix/events"); module.exports = function(config) { var self = this; Events.call(self, config); var $iframe = $("iframe", self.dom); $("form", self.dom).on("submit", function () { if (!$(this).find("input[type='file']").val()) { return; } $iframe.off("load"); $iframe.on("load", function () { var result = $(this.contentWindow.document).text(); if (!result) { return; } try { result = JSON.parse(result); } catch (e) { // nothing to do } self.emit("fileUploaded", result); var $iframeClone = $iframe.clone(); $iframe.attr("src", ""); var $inputTypeFile = $("input[type=file]", self.dom); $inputTypeFile.replaceWith($inputTypeFile.clone(true)); }); }); self.emit("ready", config); };
Improve UX of deck upload button
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery3 //= require popper //= require bootstrap-sprockets //= require turbolinks //= require select2 //= require_tree . $(function () { $(document).on("mouseover", ".previewable_card_name", function() { var preview_link = $(this).data("preview-link"); $(this).closest(".decklist").find(".card_picture_cell").hide(); $(this).closest(".decklist").find(".card_picture_cell[data-preview='"+preview_link+"']").show(); }) $(".pack_selection select").select2(); if (!('ontouchstart' in document.documentElement) && (document.location.hash === "")) { document.getElementById("q").focus(); } $('#deck_upload').on('change', function(){ var fileName = $(this).val().split("\\").pop(); $(this).next('.custom-file-label').html(fileName); $(this).closest("form").submit(); }) })
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery3 //= require popper //= require bootstrap-sprockets //= require turbolinks //= require select2 //= require_tree . $(function () { $(document).on("mouseover", ".previewable_card_name", function() { var preview_link = $(this).data("preview-link"); $(this).closest(".decklist").find(".card_picture_cell").hide(); $(this).closest(".decklist").find(".card_picture_cell[data-preview='"+preview_link+"']").show(); }) $(".pack_selection select").select2(); if (!('ontouchstart' in document.documentElement) && (document.location.hash === "")) { document.getElementById("q").focus(); } })
Add save table row action
const ADD_TABLE_ROW = "ADD_TABLE_ROW" const EDIT_TABLE_ROW = "EDIT_TABLE_ROW" const SAVE_TABLE_ROW = "SAVE_TABLE_ROW" let nextTableRowId = 0 const addTableRow = (tableRow) => { return { type: ADD_TABLE_ROW, tableRow, id: nextTableRowId++ } } //Remove editing state from TableRow, use this passed down as prop const editTableRow = (id) => { return { type: EDIT_TABLE_ROW, id } } const saveTableRow = (cells) => { return { type: SAVE_TABLE_ROW, cells } } /* tableRow object: { id: Integer, tableName: String, editing: bool, readOnly: bool, cells: [{ tableRowId: Integer, index: Integer, value: String or Number, type: String }] } make Table map the tableRow state it's passed and create TableRow components from it */
const ADD_TABLE_ROW = "ADD_TABLE_ROW" const EDIT_TABLE_ROW = "EDIT_TABLE_ROW" const UPDATE_TABLE_CELL = "UPDATE_TABLE_CELL" let nextTableRowId = 0 const addTableRow = (tableRow) => { return { type: ADD_TABLE_ROW, tableRow, id: nextTableRowId++ } } const editTableRow = (id) => { return { type: EDIT_TABLE_ROW, id } } /* tableRow object: { id: Integer, tableName: String, editing: bool, readOnly: bool, cells: [{ tableRowId: Integer, index: Integer, value: String or Number, type: String }] } make Table map the tableRow state it's passed and create TableRow components from it */
Fix frontpage webhook to deploy from main
#!/usr/bin/env node /* eslint-disable no-console */ const fetch = require('node-fetch'); const { execSync } = require('child_process'); const { FRONTPAGE_WEBHOOK, FRONTPAGE_WEBHOOK_NEXT } = process.env; const branch = execSync('git rev-parse --abbrev-ref HEAD').toString().trim(); const branchToHook = { main: FRONTPAGE_WEBHOOK, next: FRONTPAGE_WEBHOOK_NEXT, }; console.log('build-frontpage'); const hook = branchToHook[branch]; if (hook) { console.log('triggering frontpage build'); const url = `https://api.netlify.com/build_hooks/${hook}`; fetch(url, { method: 'post' }).then((res) => console.log('result', res.status)); } else { console.log('skipping branch', branch); }
#!/usr/bin/env node /* eslint-disable no-console */ const fetch = require('node-fetch'); const { execSync } = require('child_process'); const { FRONTPAGE_WEBHOOK, FRONTPAGE_WEBHOOK_NEXT } = process.env; const branch = execSync('git rev-parse --abbrev-ref HEAD').toString().trim(); const branchToHook = { master: FRONTPAGE_WEBHOOK, next: FRONTPAGE_WEBHOOK_NEXT, }; console.log('build-frontpage'); const hook = branchToHook[branch]; if (hook) { console.log('triggering frontpage build'); const url = `https://api.netlify.com/build_hooks/${hook}`; fetch(url, { method: 'post' }).then((res) => console.log('result', res.status)); } else { console.log('skipping branch', branch); }
Set min donation to 1
const config = { logLevel: process.env.LOG_LEVEL || 'info', couchDb: { url: process.env.COUCHDB_URL, dbName: 'q' }, http: { port: 3000 }, business: { adminFee: 0.15, maxDonation: 500, minDonation: 1 }, obp: { active: process.env.OBP_ACTIVE, userId: 'ccaec25d-214f-4ec3-a561-b3e0ee87e8a7', bankId: 'rbs', token: process.env.OBP_TOKEN, money: { source: 'moneymaker', targets: ['q-customer-1', 'q-customer-2', 'q-customer-3', 'q-organisation', 'q-retail-1', 'q-retail-2'] } } } module.exports = config
const config = { logLevel: process.env.LOG_LEVEL || 'info', couchDb: { url: process.env.COUCHDB_URL, dbName: 'q' }, http: { port: 3000 }, business: { adminFee: 0.15, maxDonation: 500, minDonation: 0 }, obp: { active: process.env.OBP_ACTIVE, userId: 'ccaec25d-214f-4ec3-a561-b3e0ee87e8a7', bankId: 'rbs', token: process.env.OBP_TOKEN, money: { source: 'moneymaker', targets: ['q-customer-1', 'q-customer-2', 'q-customer-3', 'q-organisation', 'q-retail-1', 'q-retail-2'] } } } module.exports = config
Fix data collector function unimplemented
<?php namespace JDecool\Bundle\TwigConstantAccessorBundle\DataCollector; use JDecool\Bundle\TwigConstantAccessorBundle\Accessor\ConstantCollection; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\DataCollector\DataCollector; class ConstantCollector extends DataCollector { /** @var ConstantCollection */ private $accessors; /** * Constructor * * @param ConstantCollection $accessors */ public function __construct(ConstantCollection $accessors) { $this->accessors = $accessors; } /** * {@inheritdoc} */ public function collect(Request $request, Response $response, \Exception $exception = null) { $this->data = [ 'accessors' => $this->accessors->toArray(), ]; } /** * Get all constants accessors declared * * @return ConstantCollection */ public function getAccessors() { return $this->data['accessors']; } /** * {@inheritdoc} */ public function getName() { return 'constant_accessor.constant_collector'; } /** * {@inheritdoc} */ public function reset() { } }
<?php namespace JDecool\Bundle\TwigConstantAccessorBundle\DataCollector; use JDecool\Bundle\TwigConstantAccessorBundle\Accessor\ConstantCollection; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\DataCollector\DataCollector; class ConstantCollector extends DataCollector { /** @var ConstantCollection */ private $accessors; /** * Constructor * * @param ConstantCollection $accessors */ public function __construct(ConstantCollection $accessors) { $this->accessors = $accessors; } /** * {@inheritdoc} */ public function collect(Request $request, Response $response, \Exception $exception = null) { $this->data = [ 'accessors' => $this->accessors->toArray(), ]; } /** * Get all constants accessors declared * * @return ConstantCollection */ public function getAccessors() { return $this->data['accessors']; } /** * {@inheritdoc} */ public function getName() { return 'constant_accessor.constant_collector'; } }
Add Userscript variable to ESLint settings
module.exports = { "env": { "browser": true, "es2021": true }, "globals": { "module": "readonly", "Game": "writable", "l": "readonly", "b64_to_utf8": "readonly", "utf8_to_b64": "readonly", "Beautify": "writable", "realAudio": "readonly", "JSColor": "readonly", "jscolor": "readonly", "BeautifyAll": "readonly", "CM": "writable", "unsafeWindow": "readonly", }, "extends": "eslint:recommended", "parserOptions": { "ecmaVersion": 12 }, "rules": { } };
module.exports = { "env": { "browser": true, "es2021": true }, "globals": { "module": "readonly", "Game": "writable", "l": "readonly", "b64_to_utf8": "readonly", "utf8_to_b64": "readonly", "Beautify": "writable", "realAudio": "readonly", "JSColor": "readonly", "jscolor": "readonly", "BeautifyAll": "readonly", "CM": "writable", }, "extends": "eslint:recommended", "parserOptions": { "ecmaVersion": 12 }, "rules": { } };
Change distribution script to support python 3.5
import subprocess def load_configuration(environment): configuration = { "project": "nimp", "project_version": { "identifier": "0.9.6" }, "distribution": "nimp-cli", } configuration["project_version"]["revision"] = subprocess.check_output([ environment["git_executable"], "rev-parse", "--short=10", "HEAD" ]).decode("utf-8").strip() configuration["project_version"]["branch"] = subprocess.check_output([ environment["git_executable"], "rev-parse", "--abbrev-ref", "HEAD" ]).decode("utf-8").strip() configuration["project_version"]["numeric"] = "{identifier}".format(**configuration["project_version"]) configuration["project_version"]["full"] = "{identifier}+{revision}".format(**configuration["project_version"]) return configuration
import subprocess def load_configuration(environment): configuration = { "project": "nimp", "project_version": { "identifier": "0.9.6" }, "distribution": "nimp-cli", } revision = subprocess.run([ environment["git_executable"], "rev-parse", "--short=10", "HEAD" ], check = True, capture_output = True).stdout.decode("utf-8").strip() branch = subprocess.run([ environment["git_executable"], "rev-parse", "--abbrev-ref", "HEAD" ], check = True, capture_output = True).stdout.decode("utf-8").strip() configuration["project_version"]["revision"] = revision configuration["project_version"]["branch"] = branch configuration["project_version"]["numeric"] = "{identifier}".format(**configuration["project_version"]) configuration["project_version"]["full"] = "{identifier}+{revision}".format(**configuration["project_version"]) return configuration
Remove async/await from example to comply with lts/boron lang support
const { expectRedux, storeSpy } = require("expect-redux"); const { configureStore } = require("./store"); const storeForTest = () => configureStore([storeSpy]); const effect = dispatch => { dispatch({ type: "REQUEST_STARTED" }); return fetch("/api/count").then(result => { if (result.ok) { return result.json().then(jsonBody => { dispatch({ type: "REQUEST_SUCCESS", payload: jsonBody.count }); }); } }); }; describe("service", () => { it("retrieves the current count", () => { const store = storeForTest(); global.fetch = jest.fn().mockResolvedValue({ ok: true, json: jest.fn().mockResolvedValue({ count: 42 }) }); store.dispatch(effect); return expectRedux(store) .toDispatchAnAction() .matching({ type: "REQUEST_SUCCESS", payload: 42 }); }); });
const { expectRedux, storeSpy } = require("expect-redux"); const { configureStore } = require("./store"); const storeForTest = () => configureStore([storeSpy]); const effect = async dispatch => { dispatch({ type: "REQUEST_STARTED" }); const result = await fetch("/api/count"); if (result.ok) { dispatch({ type: "REQUEST_SUCCESS", payload: (await result.json()).count }); } }; describe("service", () => { it("retrieves the current count", () => { const store = storeForTest(); global.fetch = jest.fn().mockResolvedValue({ ok: true, json: jest.fn().mockResolvedValue({ count: 42 }) }); store.dispatch(effect); return expectRedux(store) .toDispatchAnAction() .matching({ type: "REQUEST_SUCCESS", payload: 42 }); }); });
Add extra check in keyExtractor to prevent dublicate keys
import React from 'react' import { Text } from 'react-native' import { withNavigation } from 'react-navigation' import ShuttleOverview from './ShuttleOverview' import ScrollCard from '../common/ScrollCard' import Touchable from '../common/Touchable' import css from '../../styles/css' export const ShuttleCard = ({ navigation, stopsData, savedStops, gotoRoutesList, gotoSavedList, updateScroll, lastScroll, }) => { const extraActions = [ { name: 'Manage Stops', action: gotoSavedList } ] console.log(savedStops) return ( <ScrollCard id="shuttle" title="Shuttle" scrollData={savedStops} renderItem={ ({ item: rowData }) => ( <ShuttleOverview onPress={() => navigation.navigate('ShuttleStop', { stopID: rowData.id })} stopData={stopsData[rowData.id]} closest={Object.prototype.hasOwnProperty.call(rowData, 'savedIndex')} /> ) } actionButton={ <Touchable style={css.shuttlecard_addButton} onPress={() => gotoRoutesList()} > <Text style={css.shuttlecard_addText}>Add a Stop</Text> </Touchable> } extraActions={extraActions} updateScroll={updateScroll} lastScroll={lastScroll} /> ) } export default withNavigation(ShuttleCard)
import React from 'react' import { Text } from 'react-native' import { withNavigation } from 'react-navigation' import ShuttleOverview from './ShuttleOverview' import ScrollCard from '../common/ScrollCard' import Touchable from '../common/Touchable' import css from '../../styles/css' export const ShuttleCard = ({ navigation, stopsData, savedStops, gotoRoutesList, gotoSavedList, updateScroll, lastScroll, }) => { const extraActions = [ { name: 'Manage Stops', action: gotoSavedList } ] return ( <ScrollCard id="shuttle" title="Shuttle" scrollData={savedStops} renderItem={ ({ item: rowData }) => ( <ShuttleOverview onPress={() => navigation.navigate('ShuttleStop', { stopID: rowData.id })} stopData={stopsData[rowData.id]} closest={Object.prototype.hasOwnProperty.call(rowData, 'savedIndex')} /> ) } actionButton={ <Touchable style={css.shuttlecard_addButton} onPress={() => gotoRoutesList()} > <Text style={css.shuttlecard_addText}>Add a Stop</Text> </Touchable> } extraActions={extraActions} updateScroll={updateScroll} lastScroll={lastScroll} /> ) } export default withNavigation(ShuttleCard)
Fix in 'modules' project for module class name to module base namespace for setting up routing.
<?php $router = $di->getRouter(); foreach ($application->getModules() as $key => $module) { $namespace = preg_replace('/Module$/', 'Controllers', $module["className"]); $router->add('/'.$key.'/:params', [ 'namespace' => $namespace, 'module' => $key, 'controller' => 'index', 'action' => 'index', 'params' => 1 ])->setName($key); $router->add('/'.$key.'/:controller/:params', [ 'namespace' => $namespace, 'module' => $key, 'controller' => 1, 'action' => 'index', 'params' => 2 ]); $router->add('/'.$key.'/:controller/:action/:params', [ 'namespace' => $namespace, 'module' => $key, 'controller' => 1, 'action' => 2, 'params' => 3 ]); }
<?php $router = $di->get("router"); foreach ($application->getModules() as $key => $module) { $namespace = str_replace('Module','Controllers', $module["className"]); $router->add('/'.$key.'/:params', [ 'namespace' => $namespace, 'module' => $key, 'controller' => 'index', 'action' => 'index', 'params' => 1 ])->setName($key); $router->add('/'.$key.'/:controller/:params', [ 'namespace' => $namespace, 'module' => $key, 'controller' => 1, 'action' => 'index', 'params' => 2 ]); $router->add('/'.$key.'/:controller/:action/:params', [ 'namespace' => $namespace, 'module' => $key, 'controller' => 1, 'action' => 2, 'params' => 3 ]); } $di->set("router", $router);
Make script run and fix all typos
import requests url = "https://ua.api.yle.fi/graphql?app_id=8d7303fe&app_key=105875199ef3a1f7e0fbf7e2834b2dc&query={uutisetMostRecentNews:articleList(publisher:YLE_UUTISET,limit:100,offset:0,coverage:NATIONAL){meta{count,total,remaining},items{fullUrl,properties}}}" i = 0 while True: url = "https://ua.api.yle.fi/graphql?app_id=8d7303fe&app_key=105875199ef3a1f7e0fbf7e2834b2dc&query={uutisetMostRecentNews:articleList(publisher:YLE_UUTISET,limit:100,offset:" + str( i * 100 ) + ",coverage:NATIONAL){meta{count,total,remaining},items{fullUrl,properties}}}" r = requests.get( url ) r = r.json() d = r['data']['uutisetMostRecentNews'] items = d['items'] for item in items: print item['fullUrl'] if d['meta']['remaining'] < 100: break i += 1
import requests url = "https://ua.api.yle.fi/graphql?app_id=8d7303fe&app_key=105875199ef3a1f7e0fbf7e2834b2dc&query={uutisetMostRecentNews:articleList(publisher:YLE_UUTISET,limit:100,offset:0,coverage:NATIONAL){meta{count,total,remaining},items{fullUrl,properties}}}" i = 0 while True: url = "https://ua.api.yle.fi/graphql?app_id=8d7303fe&app_key=105875199ef3a1f7e0fbf7e2834b2dc&query={uutisetMostRecentNews:articleList(publisher:YLE_UUTISET,limit:100,offset:" + str( i * 100 ) + ",coverage:NATIONAL){meta{count,total,remaining},items{fullUrl,properties}}}" r = requests.get( url ) r = r.json() d = r['data'] items = d['uutisetMostRecentNews']['items'] for item in items: print item['fullUrl'] if d['meta']['remaining'] < 100: return i += 1
Add rootCollection option to SkinGridStore.exist
var GridStore = require('mongodb').GridStore; /** * @param filename: filename or ObjectId */ var SkinGridStore = exports.SkinGridStore = function(skinDb) { this.skinDb = skinDb; } /** * @param filename: filename or ObjectId * callback(err, gridStoreObject) */ SkinGridStore.prototype.open = function(filename, mode, options, callback){ if(!callback){ callback = options; options = undefined; } this.skinDb.open(function(err, db) { new GridStore(db, filename, mode, options).open(callback); }); } /** * @param filename: filename or ObjectId */ SkinGridStore.prototype.unlink = SkinGridStore.prototype.remove = function(filename, callback){ this.skinDb.open(function(err, db) { GridStore.unlink(db, filename, callback); }); } SkinGridStore.prototype.exist = function(filename, rootCollection, callback){ this.skinDb.open(function(err, db) { GridStore.exist(db, filename, rootCollection, callback); }); } exports.SkinGridStore = SkinGridStore;
var GridStore = require('mongodb').GridStore; /** * @param filename: filename or ObjectId */ var SkinGridStore = exports.SkinGridStore = function(skinDb) { this.skinDb = skinDb; } /** * @param filename: filename or ObjectId * callback(err, gridStoreObject) */ SkinGridStore.prototype.open = function(filename, mode, options, callback){ if(!callback){ callback = options; options = undefined; } this.skinDb.open(function(err, db) { new GridStore(db, filename, mode, options).open(callback); }); } /** * @param filename: filename or ObjectId */ SkinGridStore.prototype.unlink = SkinGridStore.prototype.remove = function(filename, callback){ this.skinDb.open(function(err, db) { GridStore.unlink(db, filename, callback); }); } SkinGridStore.prototype.exist = function(filename, callback){ this.skinDb.open(function(err, db) { GridStore.exist(db, filename, callback); }); } exports.SkinGridStore = SkinGridStore;
Rename the WebView manifest key name Rename SET_DATA_DIRECTORY_SUFFIX:DEV to STARTUP_FEATURE_SET_DATA_DIRECTORY_SUFFIX Change-Id: Id2a0a29a3cbc6972bbf285836cd13e8d2af7fd3d Test: ./gradlew webkit:integration-tests:testapp:connectedAndroidTest Bug: 250553687
/* * Copyright 2022 The Android Open Source Project * * 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 androidx.webkit.internal; /** * Class containing all the startup features the AndroidX library can support. * The constants defined in this file should not be modified as their value is used in the * WebView manifest. */ public class StartupFeatures { private StartupFeatures() { // This class shouldn't be instantiated. } // ProcessGlobalConfig#setDataDirectorySuffix(String) public static final String STARTUP_FEATURE_SET_DATA_DIRECTORY_SUFFIX = "STARTUP_FEATURE_SET_DATA_DIRECTORY_SUFFIX"; }
/* * Copyright 2022 The Android Open Source Project * * 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 androidx.webkit.internal; /** * Class containing all the startup features the AndroidX library can support. * The constants defined in this file should not be modified as their value is used in the * WebView manifest. */ public class StartupFeatures { private StartupFeatures() { // This class shouldn't be instantiated. } // ProcessGlobalConfig#setDataDirectorySuffix(String) public static final String STARTUP_FEATURE_SET_DATA_DIRECTORY_SUFFIX = "SET_DATA_DIRECTORY_SUFFIX:DEV"; }
Update gulp export support pretty
const gulp = require('gulp'), rename = require('gulp-rename'), less = require('gulp-less'), pug = require('gulp-pug') argv = require('yargs').argv /** * Compile less to css and minify */ gulp.task('less', function () { gulp.src('./src/less/**/*.less') .pipe(less({ compress:true })) .pipe(gulp.dest('./src/css/')); }); // Build and export template gulp.task('export', function () { // Get argument if (!argv.template && !argv.t) return console.log("Please enter template name \"gulp export --template <templatename>\" "); // Set template name and file path const templateName = argv.template || argv.t; const mainFile = './templates/' + templateName + '/index.pug'; const minify = (argv.minify)? false : true; console.log("Get main file : " + mainFile); // Start gulp return gulp.src(mainFile) .pipe(pug({ pretty: minify })) .pipe(rename( templateName + '.xml')) .pipe(gulp.dest('./build')) }) // Auto compile gulp.task('autocompile', function () { gulp.watch('./src/less/**/*.less', ['less']); });
const gulp = require('gulp'), rename = require('gulp-rename'), less = require('gulp-less'), pug = require('gulp-pug') argv = require('yargs').argv /** * Compile less to css and minify */ gulp.task('less', function () { gulp.src('./src/less/**/*.less') .pipe(less({ compress:true })) .pipe(gulp.dest('./src/css/')); }); // Build template gulp.task('export', function () { if (!argv.template) return console.log("Please enter template name --template <templatename>"); const templateName = argv.template; return gulp.src('./templates/' + templateName + '/index.pug') .pipe(pug( )) .pipe(rename( templateName + '.xml')) .pipe(gulp.dest('./build')) }) // Auto compile gulp.task('autocompile', function () { gulp.watch('./src/less/**/*.less', ['less']); });
Update master version to 0.3-dev
#from distutils.core import setup from setuptools import setup descr = """Tree representations and algorithms for Python. Viridis is named after the green tree python, Morelia viridis. """ DISTNAME = 'viridis' DESCRIPTION = 'Tree data structures and algorithms' LONG_DESCRIPTION = descr MAINTAINER = 'Juan Nunez-Iglesias' MAINTAINER_EMAIL = 'juan.n@unimelb.edu.au' URL = 'https://github.com/jni/viridis' LICENSE = 'BSD 3-clause' DOWNLOAD_URL = 'https://github.com/jni/viridis' VERSION = '0.3-dev' PYTHON_VERSION = (2, 7) INST_DEPENDENCIES = {} if __name__ == '__main__': setup(name=DISTNAME, version=VERSION, url=URL, description=DESCRIPTION, long_description=LONG_DESCRIPTION, author=MAINTAINER, author_email=MAINTAINER_EMAIL, license=LICENSE, packages=['viridis'], package_data={}, install_requires=INST_DEPENDENCIES, scripts=[] )
#from distutils.core import setup from setuptools import setup descr = """Tree representations and algorithms for Python. Viridis is named after the green tree python, Morelia viridis. """ DISTNAME = 'viridis' DESCRIPTION = 'Tree data structures and algorithms' LONG_DESCRIPTION = descr MAINTAINER = 'Juan Nunez-Iglesias' MAINTAINER_EMAIL = 'juan.n@unimelb.edu.au' URL = 'https://github.com/jni/viridis' LICENSE = 'BSD 3-clause' DOWNLOAD_URL = 'https://github.com/jni/viridis' VERSION = '0.2-dev' PYTHON_VERSION = (2, 7) INST_DEPENDENCIES = {} if __name__ == '__main__': setup(name=DISTNAME, version=VERSION, url=URL, description=DESCRIPTION, long_description=LONG_DESCRIPTION, author=MAINTAINER, author_email=MAINTAINER_EMAIL, license=LICENSE, packages=['viridis'], package_data={}, install_requires=INST_DEPENDENCIES, scripts=[] )
Make flatten more portable again
import bisect def binary_search(a, x): i = bisect.bisect_left(a, x) return i != len(a) and a[i] == x def flatten(lst): res = [] def dfs(l): try: for i in l: dfs(i) except: res.append(l) dfs(lst) return res def choose(l, k): cur = [] def gen(at, left): if left == 0: yield list(cur) elif at < l: cur.append(at) for res in gen(at + 1, left - 1): yield res cur.pop() for res in gen(at + 1, left): yield res return gen(0, k) def subsets(elems): def bt(at, cur): if at == len(elems): yield cur else: for x in bt(at+1, cur): yield x for x in bt(at+1, cur + [elems[at]]): yield x for x in bt(0, []): yield x
import bisect def binary_search(a, x): i = bisect.bisect_left(a, x) return i != len(a) and a[i] == x def flatten(lst): res = [] def dfs(l): try: for i in l: dfs(i) except: res.append(i) dfs(lst) return res def choose(l, k): cur = [] def gen(at, left): if left == 0: yield list(cur) elif at < l: cur.append(at) for res in gen(at + 1, left - 1): yield res cur.pop() for res in gen(at + 1, left): yield res return gen(0, k) def subsets(elems): def bt(at, cur): if at == len(elems): yield cur else: for x in bt(at+1, cur): yield x for x in bt(at+1, cur + [elems[at]]): yield x for x in bt(0, []): yield x
Change function name of getServer
package org.sipc.se.plugin; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public abstract class PluginImpl implements Plugin , Comparable<PluginImpl> { private Map<String, PluginImpl> map ; public Logger log = LogManager.getLogger() ; public abstract String getUrl() ; public abstract boolean onEnable() ; public abstract void getResponse(HttpServletRequest request, HttpServletResponse response) ; public Map<String, PluginImpl> getServerPluginList() { return this.map; } public void setMap(Map<String, PluginImpl> map){ this.map = map ; } public String toString(){ return getUrl() ; } @Override public int compareTo(PluginImpl o) { return this.getUrl().compareTo(o.getUrl()); } }
package org.sipc.se.plugin; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public abstract class PluginImpl implements Plugin , Comparable<PluginImpl> { private Map<String, PluginImpl> map ; public Logger log = LogManager.getLogger() ; public abstract String getUrl() ; public abstract boolean onEnable() ; public abstract void getResponse(HttpServletRequest request, HttpServletResponse response) ; public Map<String, PluginImpl> getServer() { return this.map; } public void setMap(Map<String, PluginImpl> map){ this.map = map ; } public String toString(){ return getUrl() ; } @Override public int compareTo(PluginImpl o) { return this.getUrl().compareTo(o.getUrl()); } }
Fix bug where pressing v to change view mode resulted in unstoppable constant viewmode changing
s.Controls.Keyboard = function() { this.keyboard = new s.Keyboard(); }; s.Controls.Keyboard.prototype.update = function() { this.pitch = 0; this.roll = 0; this.yaw = 0; this.thrust = 0; this.fire = false; this.changeViewMode = false; if (this.keyboard.pressed('left')) { this.yaw = 1; } else if (this.keyboard.pressed('right')) { this.yaw = -1; } if (this.keyboard.pressed('down')) { // Pitch down this.pitch = -1; } else if (this.keyboard.pressed('up')) { // Pitch up this.pitch = 1; } if (this.keyboard.pressed('w')) { this.thrust = 1; } else if (this.keyboard.pressed('s')) { this.thrust = -1; } if (this.keyboard.pressed('d')) { this.roll = 1; } else if (this.keyboard.pressed('a')) { this.roll = -1; } if (this.keyboard.pressed('space')) { this.fire = true; } if (this.keyboard.pressed('v')) { this.changeViewMode = true; } };
s.Controls.Keyboard = function() { this.keyboard = new s.Keyboard(); }; s.Controls.Keyboard.prototype.update = function() { this.pitch = 0; this.roll = 0; this.yaw = 0; this.thrust = 0; this.fire = false; if (this.keyboard.pressed('left')) { this.yaw = 1; } else if (this.keyboard.pressed('right')) { this.yaw = -1; } if (this.keyboard.pressed('down')) { // Pitch down this.pitch = -1; } else if (this.keyboard.pressed('up')) { // Pitch up this.pitch = 1; } if (this.keyboard.pressed('w')) { this.thrust = 1; } else if (this.keyboard.pressed('s')) { this.thrust = -1; } if (this.keyboard.pressed('d')) { this.roll = 1; } else if (this.keyboard.pressed('a')) { this.roll = -1; } if (this.keyboard.pressed('space')) { this.fire = true; } if (this.keyboard.pressed('v')) { this.changeViewMode = true; } };
Fix the benchmark so it's not throwing exceptions every time a message is written
""" Benchmark of message serialization. The goal here is to mostly focus on performance of serialization, in a vaguely realistic manner. That is, mesages are logged in context of a message with a small number of fields. """ from __future__ import unicode_literals import time from eliot import Message, start_action, to_file # Ensure JSON serialization is part of benchmark: to_file(open("/dev/null", "w")) N = 10000 def run(): start = time.time() for i in range(N): with start_action(action_type="my_action"): with start_action(action_type="my_action2"): Message.log( message_type="my_message", integer=3, string=b"abcdeft", string2="dgsjdlkgjdsl", list=[1, 2, 3, 4]) end = time.time() # Each iteration has 5 messages: start/end of my_action, start/end of # my_action2, and my_message. print("%.6f per message" % ((end - start) / (N * 5),)) print("%s messages/sec" % (int(N / (end-start)),)) if __name__ == '__main__': run()
""" Benchmark of message serialization. The goal here is to mostly focus on performance of serialization, in a vaguely realistic manner. That is, mesages are logged in context of a message with a small number of fields. """ from __future__ import unicode_literals import time from eliot import Message, start_action, to_file # Ensure JSON serialization is part of benchmark: to_file(open("/dev/null")) N = 10000 def run(): start = time.time() for i in range(N): with start_action(action_type="my_action"): with start_action(action_type="my_action2"): Message.log( message_type="my_message", integer=3, string=b"abcdeft", string2="dgsjdlkgjdsl", list=[1, 2, 3, 4]) end = time.time() # Each iteration has 5 messages: start/end of my_action, start/end of # my_action2, and my_message. print("%.6f per message" % ((end - start) / (N * 5),)) print("%s messages/sec" % (int(N / (end-start)),)) if __name__ == '__main__': run()
Set root name in constructor of TreeBuilder
<?php namespace Spraed\PDFGeneratorBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder('spraed_pdf_generator'); $treeBuilder->getRootNode() ->children() ->arrayNode('java') ->children() ->scalarNode('full_pathname')->defaultValue('')->end() ->end() ->end() // java ->end(); return $treeBuilder; } }
<?php namespace Spraed\PDFGeneratorBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('spraed_pdf_generator'); $rootNode->children() ->arrayNode('java') ->children() ->scalarNode('full_pathname')->defaultValue('')->end() ->end() ->end() // java ->end(); return $treeBuilder; } }
Adjust import to fix build with PyInstaller.
from grow.pods import pods from grow.pods import storage from grow.conversion import content_locale_split import click import os @click.command() @click.argument('pod_path', default='.') @click.option('--type', type=click.Choice(['content_locale_split'])) def convert(pod_path, type): """Converts pod files from an earlier version of Grow.""" root = os.path.abspath(os.path.join(os.getcwd(), pod_path)) pod = pods.Pod(root, storage=storage.FileStorage) if type == 'content_locale_split': content_locale_split.Converter.convert(pod) else: raise click.UsageError( 'Unable to convert files without a --type option.\n' 'Run `grow convert --help` to see valid --type values.')
from grow.pods import pods from grow.pods import storage from grow.conversion import * import click import os @click.command() @click.argument('pod_path', default='.') @click.option('--type', type=click.Choice(['content_locale_split'])) def convert(pod_path, type): """Converts pod files from an earlier version of Grow.""" root = os.path.abspath(os.path.join(os.getcwd(), pod_path)) pod = pods.Pod(root, storage=storage.FileStorage) if type == 'content_locale_split': content_locale_split.Converter.convert(pod) else: raise click.UsageError( 'Unable to convert files without a --type option.\n' 'Run `grow convert --help` to see valid --type values.')
Add caret to signify dropdown menu Sorry, don't know how to merge commits! :P
@inject('user', 'Illuminate\Contracts\Auth\Authenticatable') @if(get_meta('navigation::usernav', true)) <ul class="nav navbar-nav navbar-right"> <li class="dropdown" id="user-menu"> <a href="#user-menu" rel="user-menu" class="dropdown-toggle" data-toggle="dropdown"> <i class="icon-user"></i> {{ ! is_null($user) ? $user->fullname : trans('orchestra/foundation::title.login') }} <span class="caret"></span> </a> @unless(is_null($user)) <ul class="dropdown-menu"> <li> <a href="{!! handles('orchestra::account') !!}"> {{ trans('orchestra/foundation::title.account.profile') }} </a> </li> <li> <a href="{!! handles('orchestra::account/password') !!}"> {{ trans('orchestra/foundation::title.account.password') }} </a> </li> <li class="divider"></li> <li> <a href="{!! handles('orchestra::logout') !!}"> {{ trans('orchestra/foundation::title.logout') }} </a> </li> </ul> @endunless </li> </ul> @endif
@inject('user', 'Illuminate\Contracts\Auth\Authenticatable') @if(get_meta('navigation::usernav', true)) <ul class="nav navbar-nav navbar-right"> <li class="dropdown" id="user-menu"> <a href="#user-menu" rel="user-menu" class="dropdown-toggle" data-toggle="dropdown"> <i class="icon-user"></i> {{ ! is_null($user) ? $user->fullname : trans('orchestra/foundation::title.login') }} </a> @unless(is_null($user)) <ul class="dropdown-menu"> <li> <a href="{!! handles('orchestra::account') !!}"> {{ trans('orchestra/foundation::title.account.profile') }} </a> </li> <li> <a href="{!! handles('orchestra::account/password') !!}"> {{ trans('orchestra/foundation::title.account.password') }} </a> </li> <li class="divider"></li> <li> <a href="{!! handles('orchestra::logout') !!}"> {{ trans('orchestra/foundation::title.logout') }} </a> </li> </ul> @endunless </li> </ul> @endif
Replace deprecated "getName()" method from Twig extensions.
<?php /** * @author Igor Nikolaev <igor.sv.n@gmail.com> * @copyright Copyright (c) 2015, Darvin Studio * @link https://www.darvin-studio.ru * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Darvin\ContentBundle\Twig\Extension; use Darvin\ContentBundle\Widget\WidgetEmbedderInterface; /** * Widget Twig extension */ class WidgetExtension extends \Twig_Extension { /** * @var \Darvin\ContentBundle\Widget\WidgetEmbedderInterface */ private $widgetEmbedder; /** * @param \Darvin\ContentBundle\Widget\WidgetEmbedderInterface $widgetEmbedder Widget embedder */ public function __construct(WidgetEmbedderInterface $widgetEmbedder) { $this->widgetEmbedder = $widgetEmbedder; } /** * {@inheritdoc} */ public function getFilters() { return [ new \Twig_SimpleFilter('content_embed_widgets', [$this->widgetEmbedder, 'embed'], ['is_safe' => ['html']]), ]; } }
<?php /** * @author Igor Nikolaev <igor.sv.n@gmail.com> * @copyright Copyright (c) 2015, Darvin Studio * @link https://www.darvin-studio.ru * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Darvin\ContentBundle\Twig\Extension; use Darvin\ContentBundle\Widget\WidgetEmbedderInterface; /** * Widget Twig extension */ class WidgetExtension extends \Twig_Extension { /** * @var \Darvin\ContentBundle\Widget\WidgetEmbedderInterface */ private $widgetEmbedder; /** * @param \Darvin\ContentBundle\Widget\WidgetEmbedderInterface $widgetEmbedder Widget embedder */ public function __construct(WidgetEmbedderInterface $widgetEmbedder) { $this->widgetEmbedder = $widgetEmbedder; } /** * {@inheritdoc} */ public function getFilters() { return [ new \Twig_SimpleFilter('content_embed_widgets', [$this->widgetEmbedder, 'embed'], ['is_safe' => ['html']]), ]; } /** * {@inheritdoc} */ public function getName() { return 'darvin_content_widget_extension'; } }
Refactor <Checkbox> tests to reduce duplication
import React from 'react'; import ReactDOM from 'react-dom'; import { Simulate } from 'react-addons-test-utils'; import Checkbox from '../../../../src/components/checkbox.jsx'; import toggleableTests from '../toggleable/base.spec.js'; import { render } from '../../../helpers/rendering.js'; import $ from 'jquery'; describe('Checkbox', function() { toggleableTests( props => render(<Checkbox {...props} />), $component => Simulate.change($component.find(':checkbox')[0]) ); function renderCheckbox(props) { const component = render(<Checkbox onToggle={() => { }} {...props} />); return $(':checkbox', ReactDOM.findDOMNode(component)); } it('should mark the checkbox when checked', function() { const $checkbox = renderCheckbox({ checked: true }); expect($checkbox.is(':checked')).to.be.true; }); it('should not mark the checkbox when unchecked', function() { const $checkbox = renderCheckbox({ checked: false }); expect($checkbox.is(':checked')).to.be.false; }); });
import React from 'react'; import ReactDOM from 'react-dom'; import { Simulate } from 'react-addons-test-utils'; import Checkbox from '../../../../src/components/checkbox.jsx'; import toggleableTests from '../toggleable/base.spec.js'; import { render } from '../../../helpers/rendering.js'; import $ from 'jquery'; describe('Checkbox', function() { toggleableTests( props => render(<Checkbox {...props} />), $component => Simulate.change($component.find(':checkbox')[0]) ); let $checkbox; const onToggle = () => { }; describe('checked', function() { beforeEach(function() { const component = render(<Checkbox onToggle={onToggle} checked />); $checkbox = $(':checkbox', ReactDOM.findDOMNode(component)); }); it('should be checked', function() { expect($checkbox.is(':checked')).to.be.true; }); }); describe('unchecked', function() { beforeEach(function() { const component = render(<Checkbox onToggle={onToggle} />); $checkbox = $(':checkbox', ReactDOM.findDOMNode(component)); }); it('should be unchecked', function() { expect($checkbox.is(':checked')).to.be.false; }); }); });
Remove incorrect usage of softdeletable annotation at property level The trait was not usable before this
<?php namespace Gedmo\SoftDeleteable\Traits; /** * SoftDeletable Trait, usable with PHP >= 5.4 * * @author Wesley van Opdorp <wesley.van.opdorp@freshheads.com> * @link http://www.gediminasm.org * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ trait SoftDeleteableEntity { /** * @ORM\Column(type="datetime") */ protected $deletedAt; /** * Sets deletedAt. * * @param \Datetime|null $deletedAt * @return $this */ public function setDeletedAt(\DateTime $deletedAt = null) { $this->deletedAt = $deletedAt; return $this; } /** * Returns deletedAt. * * @return DateTime */ public function getDeletedAt() { return $this->deletedAt; } }
<?php namespace Gedmo\SoftDeleteable\Traits; /** * SoftDeletable Trait, usable with PHP >= 5.4 * * @author Wesley van Opdorp <wesley.van.opdorp@freshheads.com> * @link http://www.gediminasm.org * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ trait SoftDeleteableEntity { /** * @Gedmo\SoftDeleteable(on="delete") * @ORM\Column(type="datetime") */ protected $deletedAt; /** * Sets deletedAt. * * @param \Datetime|null $deletedAt * @return $this */ public function setDeletedAt(\DateTime $deletedAt = null) { $this->deletedAt = $deletedAt; return $this; } /** * Returns deletedAt. * * @return DateTime */ public function getDeletedAt() { return $this->deletedAt; } }
Add description to adapter generator
import { Base } from 'yeoman-generator'; import generatorArguments from './arguments'; import generatorOptions from './options'; import generatorSteps from './steps'; export default class AdapterGenerator extends Base { constructor(...args) { super(...args); Object.keys(generatorArguments).forEach(key => this.argument(key, generatorArguments[key])); Object.keys(generatorOptions).forEach(key => this.option(key, generatorOptions[key])); this.description = 'Scaffolds a custom adapter for Sails in api/adapters folder'; } get configuring() { return generatorSteps.configuring; } get conflicts() { return generatorSteps.conflicts; } get default() { return generatorSteps.default; } get end() { return generatorSteps.end; } get initializing() { return generatorSteps.initializing } get install() { return generatorSteps.install; } get prompting() { return generatorSteps.prompting } get writing() { return generatorSteps.writing; } }
import { Base } from 'yeoman-generator'; import generatorArguments from './arguments'; import generatorOptions from './options'; import generatorSteps from './steps'; export default class AdapterGenerator extends Base { constructor(...args) { super(...args); Object.keys(generatorArguments).forEach(key => this.argument(key, generatorArguments[key])); Object.keys(generatorOptions).forEach(key => this.option(key, generatorOptions[key])); } get configuring() { return generatorSteps.configuring; } get conflicts() { return generatorSteps.conflicts; } get default() { return generatorSteps.default; } get end() { return generatorSteps.end; } get initializing() { return generatorSteps.initializing } get install() { return generatorSteps.install; } get prompting() { return generatorSteps.prompting } get writing() { return generatorSteps.writing; } }
Set Access-Control-Allow-Origin header value for production
const program = require('commander'); const MongoClient = require('mongodb').MongoClient; const logger = require('./logging').logger; program .version('0.1.0') .option('-e, --environment <e>', 'An environment of the working project', /^(dev|production)$/i, 'production') .option('-o, --origin <o>', 'The original host added to Access-Control-Allow-Origin header', ['http://www.hearthintellect.com:4000']) .option('-m, --mongo <m>', 'The url of mongodb','mongodb://hearthintellect-mongo:27017/') .parse(process.argv); function Setting(program) { this.environment = program.environment; this.origin = program.origin; } function getSetting() { return new Setting(program); } MongoClient.connect(program.mongo, function (err, db) { if (err) throw err; logger.info('数据库已创建!'); Setting.prototype.db = db.db('hearthstone'); Setting.prototype.db.collection('cards').ensureIndex({name: 'text', text: 'text'}); }); module.exports.getSetting = getSetting;
const program = require('commander'); const MongoClient = require('mongodb').MongoClient; const logger = require('./logging').logger; program .version('0.1.0') .option('-e, --environment <e>', 'An environment of the working project', /^(dev|production)$/i, 'production') .option('-o, --origin <o>', 'The original host added to Access-Control-Allow-Origin header', ['http://localhost', 'http://localhost:4200', 'http://localhost:4500']) .option('-m, --mongo <m>', 'The url of mongodb','mongodb://hearthintellect-mongo:27017/') .parse(process.argv); function Setting(program) { this.environment = program.environment; this.origin = program.origin; } function getSetting() { return new Setting(program); } MongoClient.connect(program.mongo, function (err, db) { if (err) throw err; logger.info('数据库已创建!'); Setting.prototype.db = db.db('hearthstone'); Setting.prototype.db.collection('cards').ensureIndex({name: 'text', text: 'text'}); }); module.exports.getSetting = getSetting;
Make sure we include package data too.
#!/usr/bin/env python from setuptools import setup, find_packages setup( name="django-salmonella", version='0.6', author='Lincoln Loop: Seth Buntin, Yann Malet', author_email='info@lincolnloop.com', description=("raw_id_fields widget replacement that handles display of an object's " "string value on change and can be overridden via a template."), packages=find_packages(), package_data={'salmonella': [ 'static/salmonella/js/*.js', 'static/salmonella/img/*.gif', 'templates/salmonella/*.html', 'templates/salmonella/admin/*.html', 'templates/salmonella/admin/widgets/*.html' ]}, include_package_data=True, url="http://github.com/lincolnloop/django-salmonella/", zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
#!/usr/bin/env python from setuptools import setup, find_packages setup( name="django-salmonella", version='0.6', author='Lincoln Loop: Seth Buntin, Yann Malet', author_email='info@lincolnloop.com', description=("raw_id_fields widget replacement that handles display of an object's " "string value on change and can be overridden via a template."), packages=find_packages(), package_data={'salmonella': [ 'static/salmonella/js/*.js', 'static/salmonella/img/*.gif', 'templates/salmonella/*.html', 'templates/salmonella/admin/*.html', 'templates/salmonella/admin/widgets/*.html' ]}, url="http://github.com/lincolnloop/django-salmonella/", zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
Fix persian name caused by encoding issue.
package net.sf.jabref.logic.l10n; import java.util.Map; import java.util.TreeMap; public class Languages { public static final Map<String, String> LANGUAGES; static { LANGUAGES = new TreeMap<>(); // LANGUAGES contains mappings for supported languages. LANGUAGES.put("Dansk", "da"); LANGUAGES.put("Deutsch", "de"); LANGUAGES.put("English", "en"); LANGUAGES.put("Español", "es"); LANGUAGES.put("Persian (فارسی)", "fa"); LANGUAGES.put("Fran\u00E7ais", "fr"); LANGUAGES.put("Bahasa Indonesia", "in"); LANGUAGES.put("Italiano", "it"); LANGUAGES.put("Japanese", "ja"); LANGUAGES.put("Nederlands", "nl"); LANGUAGES.put("Norsk", "no"); LANGUAGES.put("Brazilian Portugese", "pt_BR"); LANGUAGES.put("Russian", "ru"); LANGUAGES.put("Turkish", "tr"); LANGUAGES.put("Vietnamese", "vi"); LANGUAGES.put("Simplified Chinese", "zh"); } }
package net.sf.jabref.logic.l10n; import java.util.Map; import java.util.TreeMap; public class Languages { public static final Map<String, String> LANGUAGES; static { LANGUAGES = new TreeMap<>(); // LANGUAGES contains mappings for supported languages. LANGUAGES.put("Dansk", "da"); LANGUAGES.put("Deutsch", "de"); LANGUAGES.put("English", "en"); LANGUAGES.put("Espaol", "es"); LANGUAGES.put("Persian (?????)", "fa"); LANGUAGES.put("Fran\u00E7ais", "fr"); LANGUAGES.put("Bahasa Indonesia", "in"); LANGUAGES.put("Italiano", "it"); LANGUAGES.put("Japanese", "ja"); LANGUAGES.put("Nederlands", "nl"); LANGUAGES.put("Norsk", "no"); LANGUAGES.put("Brazilian Portugese", "pt_BR"); LANGUAGES.put("Russian", "ru"); LANGUAGES.put("Turkish", "tr"); LANGUAGES.put("Vietnamese", "vi"); LANGUAGES.put("Simplified Chinese", "zh"); } }
Use HyperlinkedIdentityField for entries in ProjectDetailSerializer
# -*- coding: utf-8 -*- # # (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'trex' for details. # from rest_framework.serializers import ( HyperlinkedModelSerializer, HyperlinkedIdentityField, ) from trex.models.project import Project, Entry class ProjectSerializer(HyperlinkedModelSerializer): class Meta: model = Project fields = ("url", "name", "description", "active", "created") class ProjectDetailSerializer(HyperlinkedModelSerializer): entries = HyperlinkedIdentityField(view_name="project-entries-list") class Meta: model = Project fields = ("name", "description", "active", "created", "entries") class EntryDetailSerializer(HyperlinkedModelSerializer): class Meta: model = Entry fields = ("date", "duration", "description", "state", "user", "created")
# -*- coding: utf-8 -*- # # (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'trex' for details. # from rest_framework.serializers import HyperlinkedModelSerializer from trex.models.project import Project, Entry class ProjectSerializer(HyperlinkedModelSerializer): class Meta: model = Project fields = ("url", "name", "description", "active", "created") class ProjectDetailSerializer(HyperlinkedModelSerializer): class Meta: model = Project fields = ("name", "description", "active", "created", "entries") class EntryDetailSerializer(HyperlinkedModelSerializer): class Meta: model = Entry fields = ("date", "duration", "description", "state", "user", "created")
Increase tree grow chance when testing
import Phaser from 'phaser'; import Tree from '../Tree'; import config from '../../../config'; const chanceToGrow = config.test ? 60 : 10; export default function place() { this.placed = true; this.game.time.events.add(Phaser.Timer.SECOND * 5, function() { if (this.destroyed) return; const number = Math.floor(Math.random() * 100) + 1; const playerTile = this.game.state.states.Game.player.tile; const thisTile = this.tile; if ( chanceToGrow <= number && (playerTile.x !== thisTile.x || playerTile.y !== thisTile.y) ) { new Tree({ game: this.game, x: this.x, y: this.y, }); this.destroy(); } else { place.call(this); } }, this); }
import Phaser from 'phaser'; import Tree from '../Tree'; const chanceToGrow = 10; export default function place() { this.placed = true; this.game.time.events.add(Phaser.Timer.SECOND * 5, function() { if (this.destroyed) return; const number = Math.floor(Math.random() * 100) + 1; const playerTile = this.game.state.states.Game.player.tile; const thisTile = this.tile; if ( chanceToGrow <= number && (playerTile.x !== thisTile.x || playerTile.y !== thisTile.y) ) { new Tree({ game: this.game, x: this.x, y: this.y, }); this.destroy(); } else { place.call(this); } }, this); }
Reorder writing of bashrc body sections.
#!/usr/bin/python # install_dotfiles # This script will build platform-specific dotfiles and create the appropriate symlinks in ~ import platform import os sysName = platform.system() os.remove('bashrc') bashrc = open('bashrc','a') bashrc.write("#!/bin/bash\n") bashrc.write("# This file was generated by a script. Do not edit manually!\n") def writeSection(fileName, allowComments): f = open(fileName,'r') for line in f: if line.startswith('#'): if allowComments: bashrc.write(line) else: bashrc.write(line) if sysName == 'Linux': bashrc.write("# ~/.bashrc: executed by bash(1) for non-login shells.\n") if os.path.isfile('bash_private'): writeSection('bash_private',False) writeSection('bash_common',False) writeSection('bash_linux',True) elif sysName == 'Darwin': bashrc.write("# ~/.bash_profile: executed by bash(1) for lon-login shells.\n") writeSection('bash_mac',True) if os.path.isfile('bash_private'): writeSection('bash_private',False) writeSection('bash_common',False) else: print "System not supported!" bashrc.close() exit(1) bashrc.close()
#!/usr/bin/python # install_dotfiles # This script will build platform-specific dotfiles and create the appropriate symlinks in ~ import platform import os sysName = platform.system() os.remove('bashrc') bashrc = open('bashrc','a') def writeSection(fileName, allowComments): f = open(fileName,'r') for line in f: if line.startswith('#'): if allowComments: bashrc.write(line) else: bashrc.write(line) if sysName == 'Linux': writeSection('bash_linux',True) elif sysName == 'Darwin': writeSection('bash_mac',True) else: print "System not supported!" bashrc.close() exit(1) if os.path.isfile('bash_private'): writeSection('bash_private',False) writeSection('bash_common',False) bashrc.close()
Correct but on Capital filter
/* Filters */ angular.module('myApp.filters').filter('interpolate', function(version) { 'use strict'; return function(text) { return String(text).replace(/\%VERSION\%/mg, version); }; }).filter('percent', function() { 'use strict'; return function(number) { if (typeof number != 'number') { return ""; } var value = number * 100; return Math.round(value * 10) / 10; }; }).filter('integer', function() { 'use strict'; return function(number) { if (typeof number != 'number') { return ""; } return Math.round(number); }; }).filter('capital', function() { 'use strict'; return function(text) { if (text) { return text.charAt(0).toUpperCase() + text.slice(1); } return text; }; }) ;
/* Filters */ angular.module('myApp.filters').filter('interpolate', function(version) { 'use strict'; return function(text) { return String(text).replace(/\%VERSION\%/mg, version); }; }).filter('percent', function() { 'use strict'; return function(number) { if (typeof number != 'number') { return ""; } var value = number * 100; return Math.round(value * 10) / 10; }; }).filter('integer', function() { 'use strict'; return function(number) { if (typeof number != 'number') { return ""; } return Math.round(number); }; }).filter('capital', function() { 'use strict'; return function(text) { if (text.length > 0) { return text.charAt(0).toUpperCase() + text.slice(1); } return text; }; }) ;
Add method for human markers
package org.pdxfinder.repositories; import org.pdxfinder.dao.Marker; import org.springframework.data.neo4j.annotation.Query; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.repository.query.Param; import java.util.Collection; import java.util.List; /** * Interface for Markers */ public interface MarkerRepository extends PagingAndSortingRepository<Marker, Long> { @Query("MATCH (t:Marker) WHERE t.symbol = {symbol} RETURN t") Marker findBySymbol(@Param("symbol") String symbol); @Query("MATCH (t:Marker) WHERE t.name = {name} RETURN t") Marker findByName(@Param("name") String name); @Query("MATCH (m:Marker) RETURN m") Collection<Marker> findAllMarkers(); @Query("MATCH (s:Sample)--(:MolecularCharacterization)--(:MarkerAssociation)--(m:Marker) RETURN m") Collection<Marker> findAllHumanMarkers(); @Query("MATCH (s:Sample)--(:MolecularCharacterization)--(:MarkerAssociation)--(m:Marker) WHERE s.sourceSampleId = {sampleId} return m") Collection<Marker> findAllBySampleId(@Param("sampleId") String sampleId); }
package org.pdxfinder.repositories; import org.pdxfinder.dao.Marker; import org.springframework.data.neo4j.annotation.Query; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.repository.query.Param; import java.util.Collection; import java.util.List; /** * Interface for Markers */ public interface MarkerRepository extends PagingAndSortingRepository<Marker, Long> { @Query("MATCH (t:Marker) WHERE t.symbol = {symbol} RETURN t") Marker findBySymbol(@Param("symbol") String symbol); @Query("MATCH (t:Marker) WHERE t.name = {name} RETURN t") Marker findByName(@Param("name") String name); @Query("MATCH (m:Marker) RETURN m") Collection<Marker> findAllMarkers(); @Query("MATCH (s:Sample)--(:MolecularCharacterization)--(:MarkerAssociation)--(m:Marker) WHERE s.sourceSampleId = {sampleId} return m") Collection<Marker> findAllBySampleId(@Param("sampleId") String sampleId); }
feat(router): Add a precommit extension point to the pipeline
import {Container} from 'aurelia-dependency-injection'; import {Pipeline} from './pipeline'; import {BuildNavigationPlanStep} from './navigation-plan'; import {ApplyModelBindersStep} from './model-binding'; import {LoadRouteStep} from './route-loading'; import {CommitChangesStep} from './navigation-context'; import { CanDeactivatePreviousStep, CanActivateNextStep, DeactivatePreviousStep, ActivateNextStep } from './activation'; import {createRouteFilterStep} from './route-filters'; export class PipelineProvider { static inject(){ return [Container]; } constructor(container){ this.container = container; this.steps = [ BuildNavigationPlanStep, CanDeactivatePreviousStep, //optional LoadRouteStep, createRouteFilterStep('authorize'), createRouteFilterStep('modelbind'), CanActivateNextStep, //optional //NOTE: app state changes start below - point of no return DeactivatePreviousStep, //optional ActivateNextStep, //optional createRouteFilterStep('precommit'), CommitChangesStep ]; } createPipeline(navigationContext) { var pipeline = new Pipeline(); this.steps.forEach(step => pipeline.withStep(this.container.get(step))); return pipeline; } }
import {Container} from 'aurelia-dependency-injection'; import {Pipeline} from './pipeline'; import {BuildNavigationPlanStep} from './navigation-plan'; import {ApplyModelBindersStep} from './model-binding'; import {LoadRouteStep} from './route-loading'; import {CommitChangesStep} from './navigation-context'; import { CanDeactivatePreviousStep, CanActivateNextStep, DeactivatePreviousStep, ActivateNextStep } from './activation'; import {createRouteFilterStep} from './route-filters'; export class PipelineProvider { static inject(){ return [Container]; } constructor(container){ this.container = container; this.steps = [ BuildNavigationPlanStep, CanDeactivatePreviousStep, //optional LoadRouteStep, createRouteFilterStep('authorize'), createRouteFilterStep('modelbind'), CanActivateNextStep, //optional //NOTE: app state changes start below - point of no return DeactivatePreviousStep, //optional ActivateNextStep, //optional CommitChangesStep ]; } createPipeline(navigationContext) { var pipeline = new Pipeline(); this.steps.forEach(step => pipeline.withStep(this.container.get(step))); return pipeline; } }
Remove random from aggregated feed parsing We had random data display in earlier versions of the app but don't actually use it. During an RB deploy today where we wanted to change the format to an array we discovered that the app was still expecting the random property to be an object. Therefore let's remove the random property from even being read in to allow for more flexibility in the future. Change-Id: I56a33249d0083c88eec3254aca9173a7c8edfbd6
package org.wikipedia.feed.aggregated; import android.support.annotation.Nullable; import com.google.gson.annotations.SerializedName; import org.wikipedia.feed.model.CardPageItem; import org.wikipedia.feed.mostread.MostReadArticles; import org.wikipedia.feed.news.NewsItem; import org.wikipedia.feed.image.FeaturedImage; import java.util.List; public class AggregatedFeedContent { @SuppressWarnings("unused") @Nullable private CardPageItem tfa; @SuppressWarnings("unused") @Nullable private List<NewsItem> news; @SuppressWarnings("unused") @SerializedName("mostread") @Nullable private MostReadArticles mostRead; @SuppressWarnings("unused") @Nullable private FeaturedImage image; @Nullable public CardPageItem tfa() { return tfa; } @Nullable public List<NewsItem> news() { return news; } @Nullable public MostReadArticles mostRead() { return mostRead; } @Nullable public FeaturedImage potd() { return image; } }
package org.wikipedia.feed.aggregated; import android.support.annotation.Nullable; import com.google.gson.annotations.SerializedName; import org.wikipedia.feed.model.CardPageItem; import org.wikipedia.feed.mostread.MostReadArticles; import org.wikipedia.feed.news.NewsItem; import org.wikipedia.feed.image.FeaturedImage; import java.util.List; public class AggregatedFeedContent { @SuppressWarnings("unused") @Nullable private CardPageItem tfa; @SuppressWarnings("unused") @Nullable private List<NewsItem> news; @SuppressWarnings("unused") @Nullable private CardPageItem random; @SuppressWarnings("unused") @SerializedName("mostread") @Nullable private MostReadArticles mostRead; @SuppressWarnings("unused") @Nullable private FeaturedImage image; @Nullable public CardPageItem tfa() { return tfa; } @Nullable public List<NewsItem> news() { return news; } @Nullable public MostReadArticles mostRead() { return mostRead; } @Nullable public FeaturedImage potd() { return image; } }
Make ipythonprinting test more robust
"""Tests that the IPython printing module is properly loaded. """ from sympy.interactive.session import init_ipython_session from sympy.external import import_module ipython = import_module("IPython", min_module_version="0.11") # disable tests if ipython is not present if not ipython: disabled = True def test_ipythonprinting(): # Initialize and setup IPython session app = init_ipython_session() app.run_cell("ip = get_ipython()") app.run_cell("inst = ip.instance()") app.run_cell("format = inst.display_formatter.format") app.run_cell("from sympy import Symbol") # Printing without printing extension app.run_cell("a = format(Symbol('pi'))") assert app.user_ns['a']['text/plain'] == "pi" # Load printing extension app.run_cell("%load_ext sympy.interactive.ipythonprinting") # Printing with printing extension app.run_cell("a = format(Symbol('pi'))") assert app.user_ns['a']['text/plain'] == u'\u03c0'
"""Tests that the IPython printing module is properly loaded. """ from sympy.interactive.session import init_ipython_session from sympy.external import import_module ipython = import_module("IPython", min_module_version="0.11") # disable tests if ipython is not present if not ipython: disabled = True def test_ipythonprinting(): # Initialize and setup IPython session app = init_ipython_session() app.run_cell("from IPython.core.interactiveshell import InteractiveShell") app.run_cell("inst = InteractiveShell.instance()") app.run_cell("format = inst.display_formatter.format") app.run_cell("from sympy import Symbol") # Printing without printing extension app.run_cell("a = format(Symbol('pi'))") assert app.user_ns['a']['text/plain'] == "pi" # Load printing extension app.run_cell("%load_ext sympy.interactive.ipythonprinting") # Printing with printing extension app.run_cell("a = format(Symbol('pi'))") assert app.user_ns['a']['text/plain'] == u'\u03c0'
Use new menu ordener in api controller
<?php namespace Modules\Menu\Http\Controllers\Api; use Illuminate\Contracts\Cache\Repository; use Illuminate\Http\Request; use Modules\Menu\Services\MenuOrdener; class MenuItemController { /** * @var Repository */ private $cache; /** * @var MenuOrdener */ private $menuOrdener; public function __construct(MenuOrdener $menuOrdener, Repository $cache) { $this->cache = $cache; $this->menuOrdener = $menuOrdener; } /** * Update all menu items * @param Request $request */ public function update(Request $request) { $this->cache->tags('menuItems')->flush(); foreach ($request->all() as $position => $item) { $this->menuOrdener->handle($item, $position); } } }
<?php namespace Modules\Menu\Http\Controllers\Api; use Illuminate\Contracts\Cache\Repository; use Illuminate\Http\Request; use Modules\Menu\Services\MenuService; class MenuItemController { /** * @var MenuService */ private $menuService; /** * @var Repository */ private $cache; public function __construct(MenuService $menuService, Repository $cache) { $this->menuService = $menuService; $this->cache = $cache; } /** * Update all menu items * @param Request $request */ public function update(Request $request) { $this->cache->tags('menuItems')->flush(); foreach ($request->all() as $position => $item) { $this->menuService->handle($item, $position); } } }
Remove useless if check statement
var amqp = require('amqplib'); var amqpUrl, amqpConnection, intervalID; function connect(_amqpUrl) { amqpUrl = amqpUrl || _amqpUrl || process.env.AMQP_URL || 'amqp://localhost'; return amqp.connect(amqpUrl) .then(function (_connection) { amqpConnection = _connection; _connection.on('close', reconnect); _connection.on('error', reconnect); intervalID = clearInterval(intervalID); return createChannel(); }); } function createChannel() { return amqpConnection.createChannel() .then(function (_channel) { _channel.on('close', recreateChannel); _channel.on('error', recreateChannel); intervalID = clearInterval(intervalID); return _channel; }); } function recreateChannel() { if (!intervalID) { intervalID = setInterval(createChannel, 1000); } } function reconnect() { if (!intervalID) { intervalID = setInterval(connect, 1000); } } function disconnect() { if (amqpConnection) { amqpConnection.close(); } } module.exports = function () { return { connect: connect, reconnect: reconnect, disconnect: disconnect }; };
var amqp = require('amqplib'); var amqpUrl, amqpConnection, intervalID; function connect(_amqpUrl) { amqpUrl = amqpUrl || _amqpUrl || process.env.AMQP_URL || 'amqp://localhost'; return amqp.connect(amqpUrl) .then(function (_connection) { amqpConnection = _connection; _connection.on('close', reconnect); _connection.on('error', reconnect); intervalID = clearInterval(intervalID); return createChannel(); }); } function createChannel() { if (amqpConnection) { return amqpConnection.createChannel() .then(function (_channel) { _channel.on('close', recreateChannel); _channel.on('error', recreateChannel); intervalID = clearInterval(intervalID); return _channel; }); } else { reconnect(); } } function recreateChannel() { if (!intervalID) { intervalID = setInterval(createChannel, 1000); } } function reconnect() { if (!intervalID) { intervalID = setInterval(connect, 1000); } } function disconnect() { if (amqpConnection) { amqpConnection.close(); } } module.exports = function () { return { connect: connect, reconnect: reconnect, disconnect: disconnect }; };
Remove unused import of "os"
"""Linux-specific code""" from pysyte.types import paths def xdg_home(): """path to $XDG_CONFIG_HOME >>> assert xdg_home() == paths.path('~/.config').expand() """ return paths.environ_path('XDG_CONFIG_HOME', '~/.config') def xdg_home_config(filename): """path to that file in $XDG_CONFIG_HOME >>> assert xdg_home_config('fred') == paths.path('~/.config/fred').expand() """ return xdg_home() / filename def xdg_dirs(): """paths in $XDG_CONFIG_DIRS""" return paths.environ_paths('XDG_CONFIG_DIRS') def xdg_homes(): return [xdg_home()] bash_paste = 'xclip -selection clipboard' bash_copy = 'xclip -selection clipboard -o'
"""Linux-specific code""" import os from pysyte.types import paths def xdg_home(): """path to $XDG_CONFIG_HOME >>> assert xdg_home() == os.path.expanduser('~/.config') """ return paths.environ_path('XDG_CONFIG_HOME', '~/.config') def xdg_home_config(filename): """path to that file in $XDG_CONFIG_HOME >>> assert xdg_home_config('fred') == os.path.expanduser('~/.config/fred') """ return xdg_home() / filename def xdg_dirs(): """paths in $XDG_CONFIG_DIRS""" return paths.environ_paths('XDG_CONFIG_DIRS') def xdg_homes(): return [xdg_home()] bash_paste = 'xclip -selection clipboard' bash_copy = 'xclip -selection clipboard -o'
Remove doNotForce method as it represents the default property value already
<?php namespace NotificationChannels\Authy; class AuthyMessage { /** * Determine whether to force the notification over cellphone network. * * @var bool */ public $force = false; /** * The notification method (sms/call). * * @var string */ public $method = 'sms'; /** * Create a new Authy message instance. * * @return static */ public static function create() { return new static(); } /** * Indicate that the notification is forced over cellphone network. * * @return $this */ public function force() { $this->force = true; return $this; } /** * Set the method of the Authy message. * * @param string $method * * @return $this */ public function method($method) { $this->method = $method === 'call' ? 'call' : 'sms'; return $this; } }
<?php namespace NotificationChannels\Authy; class AuthyMessage { /** * Determine whether to force the notification over cellphone network. * * @var bool */ public $force = false; /** * The notification method (sms/call). * * @var string */ public $method = 'sms'; /** * Create a new Authy message instance. * * @return static */ public static function create() { return new static(); } /** * Indicate that the notification is forced over cellphone network. * * * @return $this */ public function force() { $this->force = true; return $this; } /** * Indicate that the notification is not forced over cellphone network. * * @return $this */ public function doNotForce() { $this->force = false; return $this; } /** * Set the method of the Authy message. * * @param string $method * * @return $this */ public function method($method) { $this->method = $method === 'call' ? 'call' : 'sms'; return $this; } }
Revert "Add browser: true to env map to suppress eslint errors for browser globals" This reverts commit b314d1b8a1c2ec7c26600b4e7f39f83083a1b835. See commit 79167ab0f855beb6942d576735a19d65f0f503e2.
module.exports = { "root": true, "env": { "es6": true }, "extends": "eslint:recommended", "parserOptions": { "sourceType": "module" }, "rules": { "indent": [ "warn", "tab", { "SwitchCase": 1 } ], "linebreak-style": [ "error", "unix" ], "quotes": [ "error", "double" ], "semi": [ "error", "always" ], "no-console": [ "error", { allow: ["warn", "error"] } ], "no-unused-vars": [ "error", { "args": "none" } ] } };
module.exports = { "root": true, "env": { "es6": true, "browser": true }, "extends": "eslint:recommended", "parserOptions": { "sourceType": "module" }, "rules": { "indent": [ "warn", "tab", { "SwitchCase": 1 } ], "linebreak-style": [ "error", "unix" ], "quotes": [ "error", "double" ], "semi": [ "error", "always" ], "no-console": [ "error", { allow: ["warn", "error"] } ], "no-unused-vars": [ "error", { "args": "none" } ] } };
Save the default plugin configuration. Signed-off-by: Ian Macalinao <08370e385f4778cad8fe504ec5445edd3d45bd9a@gmail.com>
package com.simplyian.easydb; import com.simplyian.easydb.command.DBReloadCommand; import org.bukkit.plugin.java.JavaPlugin; /** * EasyDBPlugin Main class. */ public class EasyDBPlugin extends JavaPlugin { private Database db; @Override public void onEnable() { // Make sure the config has been made saveDefaultConfig(); reloadDb(); getCommand("dbreload").setExecutor(new DBReloadCommand(this)); } /** * Loads the database. */ public void reloadDb() { String dbUser = getConfig().getString("db.user"); String dbPass = getConfig().getString("db.pass", ""); String dbHost = getConfig().getString("db.host"); int dbPort = getConfig().getInt("db.port"); String dbName = getConfig().getString("db.name"); db = new Database(this, dbUser, dbPass, dbHost, dbPort, dbName); } /** * Gets the database. * * @return */ public Database getDb() { return db; } }
package com.simplyian.easydb; import com.simplyian.easydb.command.DBReloadCommand; import org.bukkit.plugin.java.JavaPlugin; /** * EasyDBPlugin Main class. */ public class EasyDBPlugin extends JavaPlugin { private Database db; @Override public void onEnable() { reloadDb(); getCommand("dbreload").setExecutor(new DBReloadCommand(this)); } /** * Loads the database. */ public void reloadDb() { String dbUser = getConfig().getString("db.user"); String dbPass = getConfig().getString("db.pass", ""); String dbHost = getConfig().getString("db.host"); int dbPort = getConfig().getInt("db.port"); String dbName = getConfig().getString("db.name"); db = new Database(this, dbUser, dbPass, dbHost, dbPort, dbName); } /** * Gets the database. * * @return */ public Database getDb() { return db; } }
Revert "Conditionally set browser for karma" This reverts commit 9f43fe898e74a0541430a06532ba8b504796af6c.
module.exports = function (config) { config.set({ port: 9876, logLevel: config.LOG_INFO, autoWatch: true, singleRun: false, colors: true, plugins: [ 'karma-jasmine', 'karma-sinon', 'karma-spec-reporter', 'karma-phantomjs-launcher', 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-browserify', 'karma-sourcemap-loader' ], browsers: ['PhantomJS'], frameworks: ['jasmine', 'sinon', 'browserify'], reporters: ['spec'], files: [ 'spec/helpers/**/*.coffee', 'spec/**/*-behavior.coffee', 'spec/**/*-spec.coffee' ], preprocessors: { 'src/**/*.coffee': ['browserify', 'sourcemap'], 'spec/**/*.coffee': ['browserify', 'sourcemap'] }, browserify: { extensions: ['.coffee'], transform: ['coffeeify'], watch: true, debug: true } }); };
module.exports = function (config) { config.set({ port: 9876, logLevel: config.LOG_INFO, autoWatch: true, singleRun: false, colors: true, plugins: [ 'karma-jasmine', 'karma-sinon', 'karma-spec-reporter', 'karma-phantomjs-launcher', 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-browserify', 'karma-sourcemap-loader' ], browsers: process.env.CI === true ? ['PhantomJS'] : [], frameworks: ['jasmine', 'sinon', 'browserify'], reporters: ['spec'], files: [ 'spec/helpers/**/*.coffee', 'spec/**/*-behavior.coffee', 'spec/**/*-spec.coffee' ], preprocessors: { 'src/**/*.coffee': ['browserify', 'sourcemap'], 'spec/**/*.coffee': ['browserify', 'sourcemap'] }, browserify: { extensions: ['.coffee'], transform: ['coffeeify'], watch: true, debug: true } }); };
Fix for broken 'add file set' button Just changed the nesting so that the form includes the pane-footer and the 'submit' button/input. Former-commit-id: 665cf13c7ffc7c6bc88eee66f431ac1e001cf986
<?php defined('C5_EXECUTE') or die("Access Denied."); ?> <? $ih = Loader::helper('concrete/interface'); ?> <?=Loader::helper('concrete/dashboard')->getDashboardPaneHeaderWrapper(t('Add Set'), false, false, false)?> <form method="post" id="file-sets-add" action="<?=$this->url('/dashboard/files/add_set', 'do_add')?>"> <div class="ccm-pane-body"> <?=$validation_token->output('file_sets_add');?> <div class="clearfix"> <?=Loader::helper("form")->label('file_set_name', t('Name'))?> <div class="input"> <?=$form->text('file_set_name','', array('class' => 'span6'))?> </div> </div> </div> <div class="ccm-pane-footer"> <?=Loader::helper("form")->submit('add', t('Add File Set'), array('class' => 'primary'))?> </div> </form> <?=Loader::helper('concrete/dashboard')->getDashboardPaneFooterWrapper(false);?>
<?php defined('C5_EXECUTE') or die("Access Denied."); ?> <? $ih = Loader::helper('concrete/interface'); ?> <?=Loader::helper('concrete/dashboard')->getDashboardPaneHeaderWrapper(t('Add Set'), false, false, false)?> <div class="ccm-pane-body"> <form method="post" id="file-sets-add" action="<?=$this->url('/dashboard/files/add_set', 'do_add')?>"> <?=$validation_token->output('file_sets_add');?> <div class="clearfix"> <?=Loader::helper("form")->label('file_set_name', t('Name'))?> <div class="input"> <?=$form->text('file_set_name','', array('class' => 'span6'))?> </div> </div> </form> </div> <div class="ccm-pane-footer"> <?=Loader::helper("form")->submit('add', t('Add File Set'), array('class' => 'primary'))?> </div> <?=Loader::helper('concrete/dashboard')->getDashboardPaneFooterWrapper(false);?>
Add forms inside page editor. TinyMCE removes attitubutes.
function setImageValue(url){ $('.mce-btn.mce-open').parent().find('.mce-textbox').val(url); } $(document).ready(function(){ $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); tinymce.init({ menubar: false, selector:'textarea.richTextBox', skin: 'voyager', plugins: 'link, image, code, youtube, giphy, table, textcolor', extended_valid_elements : 'input[onclick|value|style|type|class|name]', file_browser_callback: function(field_name, url, type, win) { if(type =='image'){ $('#upload_file').trigger('click'); } }, toolbar: 'styleselect bold italic underline | forecolor backcolor | alignleft aligncenter alignright | bullist numlist outdent indent | link image table youtube giphy | code', convert_urls: false, image_caption: true, image_title: true }); });
function setImageValue(url){ $('.mce-btn.mce-open').parent().find('.mce-textbox').val(url); } $(document).ready(function(){ $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); tinymce.init({ menubar: false, selector:'textarea.richTextBox', skin: 'voyager', plugins: 'link, image, code, youtube, giphy, table, textcolor', extended_valid_elements : 'input[onclick|value|style|type]', file_browser_callback: function(field_name, url, type, win) { if(type =='image'){ $('#upload_file').trigger('click'); } }, toolbar: 'styleselect bold italic underline | forecolor backcolor | alignleft aligncenter alignright | bullist numlist outdent indent | link image table youtube giphy | code', convert_urls: false, image_caption: true, image_title: true }); });
Add missing @ in phpdoc return statement
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Cache\Adapter; use Psr\Cache\CacheItemPoolInterface; use Symfony\Component\Cache\CacheItem; /** * Interface for adapters managing instances of Symfony's CacheItem. * * @author Kévin Dunglas <dunglas@gmail.com> */ interface AdapterInterface extends CacheItemPoolInterface { /** * {@inheritdoc} * * @return CacheItem */ public function getItem($key); /** * {@inheritdoc} * * @return \Traversable|CacheItem[] */ public function getItems(array $keys = array()); }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Cache\Adapter; use Psr\Cache\CacheItemPoolInterface; use Symfony\Component\Cache\CacheItem; /** * Interface for adapters managing instances of Symfony's CacheItem. * * @author Kévin Dunglas <dunglas@gmail.com> */ interface AdapterInterface extends CacheItemPoolInterface { /** * {@inheritdoc} * * @return CacheItem */ public function getItem($key); /** * {@inheritdoc} * * return \Traversable|CacheItem[] */ public function getItems(array $keys = array()); }
Switch to using python standard library importlib Available in Python 2.7+, which is all that Gargoyle now supports. The Django version is removed in 1.9.
""" gargoyle ~~~~~~~~ :copyright: (c) 2010 DISQUS. :license: Apache License 2.0, see LICENSE for more details. """ from gargoyle.manager import gargoyle try: VERSION = __import__('pkg_resources').get_distribution('gargoyle-yplan').version except Exception, e: VERSION = 'unknown' __all__ = ('gargoyle', 'autodiscover', 'VERSION') def autodiscover(): """ Auto-discover INSTALLED_APPS' gargoyle modules and fail silently when not present. This forces an import on them to register any gargoyle bits they may want. """ import copy from django.conf import settings from importlib import import_module for app in settings.INSTALLED_APPS: # Attempt to import the app's gargoyle module. before_import_registry = copy.copy(gargoyle._registry) try: import_module('%s.gargoyle' % app) except: # Reset the model registry to the state before the last import as # this import will have to reoccur on the next request and this # could raise NotRegistered and AlreadyRegistered exceptions gargoyle._registry = before_import_registry # load builtins __import__('gargoyle.builtins')
""" gargoyle ~~~~~~~~ :copyright: (c) 2010 DISQUS. :license: Apache License 2.0, see LICENSE for more details. """ from gargoyle.manager import gargoyle try: VERSION = __import__('pkg_resources').get_distribution('gargoyle-yplan').version except Exception, e: VERSION = 'unknown' __all__ = ('gargoyle', 'autodiscover', 'VERSION') def autodiscover(): """ Auto-discover INSTALLED_APPS' gargoyle modules and fail silently when not present. This forces an import on them to register any gargoyle bits they may want. """ import copy from django.conf import settings from django.utils.importlib import import_module for app in settings.INSTALLED_APPS: # Attempt to import the app's gargoyle module. before_import_registry = copy.copy(gargoyle._registry) try: import_module('%s.gargoyle' % app) except: # Reset the model registry to the state before the last import as # this import will have to reoccur on the next request and this # could raise NotRegistered and AlreadyRegistered exceptions gargoyle._registry = before_import_registry # load builtins __import__('gargoyle.builtins')
[DDW-557] Correct path for EPOCH files in Linux
// @flow import fs from 'fs'; import path from 'path'; import { appFolderPath } from '../config'; import { getNumberOfEpochsConsolidatedChannel } from '../ipc/getNumberOfEpochsConsolidated.ipc'; import type { GetNumberOfEpochsConsolidatedChannelResponse } from '../../common/ipc/api'; import { environment } from '../environment'; const { isLinux } = environment; export const getNumberOfEpochsConsolidated = () => { getNumberOfEpochsConsolidatedChannel .onRequest((): Promise<GetNumberOfEpochsConsolidatedChannelResponse> => { const epochsPath = isLinux ? path.join(appFolderPath, 'DB', 'epochs') : path.join(appFolderPath, 'DB-1.0', 'epochs'); let latestConsolidatedEpoch = 0; if (fs.existsSync(epochsPath)) { const epochfiles = fs .readdirSync(epochsPath) .filter(file => file.indexOf('.epoch') > -1) .map(file => parseInt(file.split('.').shift(), 10)); if (epochfiles.length) latestConsolidatedEpoch = Math.max(...epochfiles); } return Promise.resolve(latestConsolidatedEpoch); }); };
// @flow import fs from 'fs'; import path from 'path'; import { appFolderPath } from '../config'; import { getNumberOfEpochsConsolidatedChannel } from '../ipc/getNumberOfEpochsConsolidated.ipc'; import type { GetNumberOfEpochsConsolidatedChannelResponse } from '../../common/ipc/api'; export const getNumberOfEpochsConsolidated = () => { getNumberOfEpochsConsolidatedChannel .onRequest((): Promise<GetNumberOfEpochsConsolidatedChannelResponse> => { const epochsPath = path.join(appFolderPath, 'DB-1.0', 'epochs'); let latestConsolidatedEpoch = 0; if (fs.existsSync(epochsPath)) { const epochfiles = fs .readdirSync(epochsPath) .filter(file => file.indexOf('.epoch') > -1) .map(file => parseInt(file.split('.').shift(), 10)); if (epochfiles.length) latestConsolidatedEpoch = Math.max(...epochfiles); } return Promise.resolve(latestConsolidatedEpoch); }); };
Remove unused test class attr
from django.test import TestCase from conman.tests.utils import RequestTestCase from . import factories from .. import views class TestPageDetail(RequestTestCase): def test_get_object(self): """PageDetail displays the page instance passed in the node kwarg.""" request = self.create_request() page = factories.PageFactory.create() view = views.PageDetail(request=request, kwargs={'node': page}) obj = view.get_object() self.assertEqual(obj, page) class TestPageDetailIntegration(TestCase): def test_get(self): """A page's content is rendered at its url.""" page = factories.PageFactory.create(content='This is a test') response = self.client.get(page.url) self.assertIn(page.content, response.rendered_content)
from django.test import TestCase from conman.tests.utils import RequestTestCase from . import factories from .. import views class TestPageDetail(RequestTestCase): def test_get_object(self): """PageDetail displays the page instance passed in the node kwarg.""" request = self.create_request() page = factories.PageFactory.create() view = views.PageDetail(request=request, kwargs={'node': page}) obj = view.get_object() self.assertEqual(obj, page) class TestPageDetailIntegration(TestCase): view = views.PageDetail def test_get(self): """A page's content is rendered at its url.""" page = factories.PageFactory.create(content='This is a test') response = self.client.get(page.url) self.assertIn(page.content, response.rendered_content)
Fix problems with UTF-8 README.rst
#!/usr/bin/env python from codecs import open from setuptools import find_packages, setup with open('README.rst', 'r', 'utf-8') as f: readme = f.read() setup( name='django-paginationlinks', version='0.1', description='Django Pagination Links', long_description=readme, url='https://github.com/blancltd/django-paginationlinks', maintainer='Alex Tomkins', maintainer_email='alex@blanc.ltd.uk', platforms=['any'], packages=find_packages(), classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', ], license='BSD', )
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='django-paginationlinks', version='0.1', description='Django Pagination Links', long_description=open('README.rst').read(), url='https://github.com/blancltd/django-paginationlinks', maintainer='Alex Tomkins', maintainer_email='alex@blanc.ltd.uk', platforms=['any'], packages=find_packages(), classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', ], license='BSD', )
Implement parser for trends and their frequencies and store those trends in datastore
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.sps.data; public final class Trend { private final long id; private final String title; private final long frequency; private final long timestamp; public Trend(long id, String title, long frequency, long timestamp) { this.id = id; this.title = title; this.frequency = frequency; this.timestamp = timestamp; } }
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.sps.data; public final class Trend { private final long id; private final String title; private final long frequency; private final long timestamp; public Trend(long id, String title, long frequency, long timestamp) { this.id = id; this.title = title; this.frequency = frequency; this.timestamp = timestamp; } }
Add speaker name in talk page
<?php /** * @file * template.php */ /** * theme_preprocess_page */ function tedxlausanne_preprocess_page(&$variables) { // Display speaker name in the talk title if(isset($variables['node']) && isset($variables['node']->field_talk_speaker['und'][0]['entity']->title) && $variables['node']->type == 'talk'){ $speaker = $variables['node']->field_talk_speaker['und'][0]['entity']->title; $variables['title'] = '<strong>'.$speaker.'</strong><br/> '.$variables['node']->title; } } /** * Preprocess variables for node.tpl.php * * @see node.tpl.php */ function tedxlausanne_preprocess_node(&$variables) { // That will let you use a template file like: node--[type|nodeid]--teaser.tpl.php if($variables['view_mode'] == 'teaser') { $variables['theme_hook_suggestions'][] = 'node__' . $variables['node']->type . '__teaser'; } if($variables['view_mode'] == 'full_teaser') { $variables['theme_hook_suggestions'][] = 'node__' . $variables['node']->type . '__full_teaser'; } }
<?php /** * @file * template.php */ /** * theme_preprocess_page */ function tedxlausanne_preprocess_page(&$variables) { } /** * Preprocess variables for node.tpl.php * * @see node.tpl.php */ function tedxlausanne_preprocess_node(&$variables) { // That will let you use a template file like: node--[type|nodeid]--teaser.tpl.php if($variables['view_mode'] == 'teaser') { $variables['theme_hook_suggestions'][] = 'node__' . $variables['node']->type . '__teaser'; } if($variables['view_mode'] == 'full_teaser') { $variables['theme_hook_suggestions'][] = 'node__' . $variables['node']->type . '__full_teaser'; } // if (module_exists('devel')) { // dpm($variables); // } }
Drop loading jquery by django-debug-toolbar - it is integrated now
# -*- coding: utf-8 -*- ''' Local Configurations - Runs in Debug mode - Uses console backend for emails - Use Django Debug Toolbar ''' from configurations import values from .common import Common class Local(Common): # DEBUG DEBUG = values.BooleanValue(True) TEMPLATE_DEBUG = DEBUG # END DEBUG # INSTALLED_APPS INSTALLED_APPS = Common.INSTALLED_APPS # END INSTALLED_APPS # Mail settings EMAIL_HOST = "localhost" EMAIL_PORT = 1025 EMAIL_BACKEND = values.Value('django.core.mail.backends.console.EmailBackend') # End mail settings # django-debug-toolbar MIDDLEWARE_CLASSES = Common.MIDDLEWARE_CLASSES + ('debug_toolbar.middleware.DebugToolbarMiddleware',) INSTALLED_APPS += ('debug_toolbar', 'django_extensions', 'autofixture',) INTERNAL_IPS = ('127.0.0.1',) DEBUG_TOOLBAR_CONFIG = { 'DISABLE_PANELS': [ 'debug_toolbar.panels.redirects.RedirectsPanel', ], 'SHOW_TEMPLATE_CONTEXT': True, } # end django-debug-toolbar # Your local stuff: Below this line define 3rd party libary settings
# -*- coding: utf-8 -*- ''' Local Configurations - Runs in Debug mode - Uses console backend for emails - Use Django Debug Toolbar ''' from configurations import values from .common import Common class Local(Common): # DEBUG DEBUG = values.BooleanValue(True) TEMPLATE_DEBUG = DEBUG # END DEBUG # INSTALLED_APPS INSTALLED_APPS = Common.INSTALLED_APPS # END INSTALLED_APPS # Mail settings EMAIL_HOST = "localhost" EMAIL_PORT = 1025 EMAIL_BACKEND = values.Value('django.core.mail.backends.console.EmailBackend') # End mail settings # django-debug-toolbar MIDDLEWARE_CLASSES = Common.MIDDLEWARE_CLASSES + ('debug_toolbar.middleware.DebugToolbarMiddleware',) INSTALLED_APPS += ('debug_toolbar', 'django_extensions', 'autofixture',) INTERNAL_IPS = ('127.0.0.1',) DEBUG_TOOLBAR_CONFIG = { 'DISABLE_PANELS': [ 'debug_toolbar.panels.redirects.RedirectsPanel', ], 'SHOW_TEMPLATE_CONTEXT': True, 'JQUERY_URL': 'http://localhost:8000/static/js/jquery.min.js', } # end django-debug-toolbar # Your local stuff: Below this line define 3rd party libary settings
Allow undefined endpoints by default git-svn-id: 9326b53cbc4a8f4c3d02979b62b178127d5150fe@1033 c7d0bf07-ec0d-0410-b2cc-d48fa9be22ba
package org.codehaus.xfire.spring.config; import java.util.List; import javax.xml.namespace.QName; public abstract class AbstractSoapBindingBean { private String transport; private List endpoints; private QName name; private boolean allowUndefinedEndpoints = true; public boolean isAllowUndefinedEndpoints() { return allowUndefinedEndpoints; } public void setAllowUndefinedEndpoints(boolean allowUndefinedEndpoints) { this.allowUndefinedEndpoints = allowUndefinedEndpoints; } public QName getName() { return name; } public void setName(QName name) { this.name = name; } public String getTransport() { return transport; } public void setTransport(String transport) { this.transport = transport; } public List getEndpoints() { return endpoints; } public void setEndpoints(List endpoints) { this.endpoints = endpoints; } }
package org.codehaus.xfire.spring.config; import java.util.List; import javax.xml.namespace.QName; public abstract class AbstractSoapBindingBean { private String transport; private List endpoints; private QName name; private boolean allowUndefinedEndpoints; public boolean isAllowUndefinedEndpoints() { return allowUndefinedEndpoints; } public void setAllowUndefinedEndpoints(boolean allowUndefinedEndpoints) { this.allowUndefinedEndpoints = allowUndefinedEndpoints; } public QName getName() { return name; } public void setName(QName name) { this.name = name; } public String getTransport() { return transport; } public void setTransport(String transport) { this.transport = transport; } public List getEndpoints() { return endpoints; } public void setEndpoints(List endpoints) { this.endpoints = endpoints; } }
Add a get note method
function NoteApplication (author) { this.author = author; this.notes = []; this.create = function(note_content) { if (note_content.length > 0) { this.notes.push(note_content); return "You have created a note"; } else { return "You haven't entered a valid note"; } } this.listNotes = function(){ if(this.noteArray.length < 1){ console.log("There are no notes in the collection."); } else{for(let i = 0; i < this.notes.length; i++){ console.log("\nNote ID: " + this.notes[i]); console.log(this.notes[i]); console.log("\n\nBy Author " + this.author + "\n"); } this.get = function(note_id) { return "Note ID: " + this.notes[note_id]; } }
function NoteApplication (author) { this.author = author; this.notes = []; this.create = function(note_content) { if (note_content.length > 0) { this.notes.push(note_content); return "You have created a note"; } else { return "You haven't entered a valid note"; } } this.listNotes = function(){ if(this.noteArray.length < 1){ console.log("There are no notes in the collection."); } else{for(let i = 0; i < this.noteArray.length; i++){ console.log("\nNote ID: " + this.noteArray[i]); console.log(this.noteArray[i]); console.log("\n\nBy Author " + this.author + "\n"); } }
Fix galley close on esc
(function () { var addImageGallery = function(post) { if(post.length && !post.hasClass('smi-img-gallery')) { console.log('POST: ', post); post.addClass('smi-img-gallery'); post.find('img').each(function(){ var img = $(this); var link = img.attr('src'); if(!link || img.closest('a').length){ return; } var a = $('<a class="smi-post-img" data-fancybox="smi-post-images">'); a.attr('href', link); img.replaceWith(a); a.append(img); }); var fb = post.find('a.smi-post-img').fancybox({ loop: true, beforeClose: function(instance, current, event){ if(event && event.stopPropagation){ event.stopPropagation(); } } }); } }; //TODO: TEMP setInterval(function(){ var post = $('.PostFull__body'); addImageGallery(post); },100); })();
(function () { var addImageGallery = function(post) { if(post.length && !post.hasClass('smi-img-gallery')) { console.log('POST: ', post); post.addClass('smi-img-gallery'); post.find('img').each(function(){ var img = $(this); var link = img.attr('src'); if(!link || img.closest('a').length){ return; } var a = $('<a class="smi-post-img" data-fancybox="smi-post-images">'); a.attr('href', link); img.replaceWith(a); a.append(img); }); post.find('a.smi-post-img').fancybox({ loop: true }); } }; //TODO: TEMP setInterval(function(){ var post = $('.PostFull__body'); addImageGallery(post); },100); })();
Remove DOMContentLoaded event listener after it's used
import detectIt from 'detect-it'; import addListener from 'the-listener'; function setupCurrentInput() { const body = document.querySelector('body'); let currentInput = undefined; function updateCurrentInput(input) { if (input !== currentInput) { body.classList.remove(`current-input-${currentInput}`); body.classList.add(`current-input-${input}`); currentInput = input; } } if (detectIt.deviceType === 'mouseOnly') updateCurrentInput('mouse'); else if (detectIt.deviceType === 'touchOnly') { updateCurrentInput('touch'); // add blank touch listener to body to enable :active state when touching the screen addListener(body, { 'touchstart passive capture': () => {} }); } else { // add listeners for hybrid device addListener(window, { 'touchstart passive capture': () => { updateCurrentInput('touch'); }, 'mousedown mouseenter mousemove passive capture': () => { updateCurrentInput('mouse'); }, }, { pointermove: false } ); /* eslint no-unused-expressions: ["error", { "allowTernary": true }] */ detectIt.primaryHover === 'hover' ? updateCurrentInput('mouse') : updateCurrentInput('touch'); } document.removeEventListener('DOMContentLoaded', setupCurrentInput); } (() => { const body = document.querySelector('body'); if (body) setupCurrentInput(); else document.addEventListener('DOMContentLoaded', setupCurrentInput); })();
import detectIt from 'detect-it'; import addListener from 'the-listener'; function setupCurrentInput() { const body = document.querySelector('body'); let currentInput = undefined; function updateCurrentInput(input) { if (input !== currentInput) { body.classList.remove(`current-input-${currentInput}`); body.classList.add(`current-input-${input}`); currentInput = input; } } if (detectIt.deviceType === 'mouseOnly') updateCurrentInput('mouse'); else if (detectIt.deviceType === 'touchOnly') { updateCurrentInput('touch'); // add blank touch listener to body to enable :active state when touching the screen addListener(body, { 'touchstart passive capture': () => {} }); } else { // add listeners for hybrid device addListener(window, { 'touchstart passive capture': () => { updateCurrentInput('touch'); }, 'mousedown mouseenter mousemove passive capture': () => { updateCurrentInput('mouse'); }, }, { pointermove: false } ); /* eslint no-unused-expressions: ["error", { "allowTernary": true }] */ detectIt.primaryHover === 'hover' ? updateCurrentInput('mouse') : updateCurrentInput('touch'); } } (() => { const body = document.querySelector('body'); if (body) setupCurrentInput(); else document.addEventListener('DOMContentLoaded', setupCurrentInput); })();
chore(engine): Improve wording in a javadoc comment
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. Camunda licenses this file to you under the Apache License, * Version 2.0; 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.camunda.bpm.client.interceptor; /** * <p>Client request interceptor makes it possible to apply changes to each request before it is sent to the http server</p> * * @author Tassilo Weidner */ @FunctionalInterface public interface ClientRequestInterceptor { /** * Gets invoked before a request is sent to the http server * * @param requestContext provides the data of the request and offers methods to change it */ void intercept(ClientRequestContext requestContext); }
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. Camunda licenses this file to you under the Apache License, * Version 2.0; 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.camunda.bpm.client.interceptor; /** * <p>Client request interceptor makes it possible to apply changes to each request before it is sent to the http server</p> * * @author Tassilo Weidner */ @FunctionalInterface public interface ClientRequestInterceptor { /** * Has been invoked before a request is sent to the http server * * @param requestContext provides the data of the request and offers methods to change it */ void intercept(ClientRequestContext requestContext); }
Attach image_input_click function to window object So other parts of the page can access it
///////////////////////////////////////////////////////////////////////////// // // Simple image input // //////////////////////////////////////////////////////////////////////////////// // click on image, return coordinates // put a dot at location of click, on imag window.image_input_click = function(id,event){ iidiv = document.getElementById("imageinput_"+id); pos_x = event.offsetX?(event.offsetX):event.pageX-iidiv.offsetLeft; pos_y = event.offsetY?(event.offsetY):event.pageY-iidiv.offsetTop; result = "[" + pos_x + "," + pos_y + "]"; cx = (pos_x-15) +"px"; cy = (pos_y-15) +"px" ; // alert(result); document.getElementById("cross_"+id).style.left = cx; document.getElementById("cross_"+id).style.top = cy; document.getElementById("cross_"+id).style.visibility = "visible" ; document.getElementById("input_"+id).value =result; };
///////////////////////////////////////////////////////////////////////////// // // Simple image input // //////////////////////////////////////////////////////////////////////////////// // click on image, return coordinates // put a dot at location of click, on imag // window.image_input_click = function(id,event){ function image_input_click(id,event){ iidiv = document.getElementById("imageinput_"+id); pos_x = event.offsetX?(event.offsetX):event.pageX-iidiv.offsetLeft; pos_y = event.offsetY?(event.offsetY):event.pageY-iidiv.offsetTop; result = "[" + pos_x + "," + pos_y + "]"; cx = (pos_x-15) +"px"; cy = (pos_y-15) +"px" ; // alert(result); document.getElementById("cross_"+id).style.left = cx; document.getElementById("cross_"+id).style.top = cy; document.getElementById("cross_"+id).style.visibility = "visible" ; document.getElementById("input_"+id).value =result; }
Adjust signature of test class fully
<?php namespace Neos\Flow\Tests\Functional\Configuration\Fixtures; /* * This file is part of the Neos.Flow package. * * (c) Contributors of the Neos Project - www.neos.io * * This package is Open Source Software. For the full copyright and license * information, please view the LICENSE file which was distributed with this * source code. */ use Neos\Flow\Annotations as Flow; class RootDirectoryIgnoringYamlSource extends \Neos\Flow\Configuration\Source\YamlSource { /** * Loads the specified configuration file and returns its content as an * array. If the file does not exist or could not be loaded, an empty * array is returned * * @param string $pathAndFilename Full path and filename of the file to load, excluding the file extension (ie. ".yaml") * @param boolean $allowSplitSource If TRUE, the type will be used as a prefix when looking for configuration files * @return array * @throws \Neos\Flow\Configuration\Exception\ParseErrorException */ public function load(string $pathAndFilename, bool $allowSplitSource = false): array { if (strpos($pathAndFilename, FLOW_PATH_CONFIGURATION) === 0) { return []; } else { return parent::load($pathAndFilename, $allowSplitSource); } } }
<?php namespace Neos\Flow\Tests\Functional\Configuration\Fixtures; /* * This file is part of the Neos.Flow package. * * (c) Contributors of the Neos Project - www.neos.io * * This package is Open Source Software. For the full copyright and license * information, please view the LICENSE file which was distributed with this * source code. */ use Neos\Flow\Annotations as Flow; class RootDirectoryIgnoringYamlSource extends \Neos\Flow\Configuration\Source\YamlSource { /** * Loads the specified configuration file and returns its content as an * array. If the file does not exist or could not be loaded, an empty * array is returned * * @param string $pathAndFilename Full path and filename of the file to load, excluding the file extension (ie. ".yaml") * @param boolean $allowSplitSource If TRUE, the type will be used as a prefix when looking for configuration files * @return array * @throws \Neos\Flow\Configuration\Exception\ParseErrorException */ public function load($pathAndFilename, $allowSplitSource = false): array { if (strpos($pathAndFilename, FLOW_PATH_CONFIGURATION) === 0) { return []; } else { return parent::load($pathAndFilename, $allowSplitSource); } } }
Fix dataconversion. Tests are passing now
<?php namespace OpenSRS\backwardcompatibility\dataconversion\domains\lookup; use OpenSRS\backwardcompatibility\dataconversion\DataConversion; use OpenSRS\Exception; class LookupDomain extends DataConversion { // New structure for API calls handled by // the toolkit. // // index: field name // value: location of data to map to this // field from the original structure // // example 1: // "cookie" => 'data->cookie' // this will map ->data->cookie in the // original object to ->cookie in the // new format // // example 2: // ['attributes']['domain'] = 'data->domain' // this will map ->data->domain in the original // to ->attributes->domain in the new format protected $newStructure = array( 'attributes' => array( 'domain' => 'data->searchstring', ) ); public function convertDataObject( $dataObject, $newStructure = null ) { $p = new parent(); if(is_null($newStructure)){ $newStructure = $this->newStructure; } $newDataObject = $p->convertDataObject( $dataObject, $newStructure ); return $newDataObject; } }
<?php namespace OpenSRS\backwardcompatibility\dataconversion\domains\lookup; use OpenSRS\backwardcompatibility\dataconversion\DataConversion; use OpenSRS\Exception; class LookupDomain extends DataConversion { // New structure for API calls handled by // the toolkit. // // index: field name // value: location of data to map to this // field from the original structure // // example 1: // "cookie" => 'data->cookie' // this will map ->data->cookie in the // original object to ->cookie in the // new format // // example 2: // ['attributes']['domain'] = 'data->domain' // this will map ->data->domain in the original // to ->attributes->domain in the new format protected $newStructure = array( 'attributes' => array( 'domain' => 'data->domain', ) ); public function convertDataObject( $dataObject, $newStructure = null ) { $p = new parent(); var_dump($dataObject); if(is_null($newStructure)){ $newStructure = $this->newStructure; } $newDataObject = $p->convertDataObject( $dataObject, $newStructure ); return $newDataObject; } }
CSRA-535: Add log info for successful save
import express from 'express'; import { databaseLogger as log } from '../services/logger'; export default function createRouter(assessment) { const router = express.Router(); router.post('/', (req, res) => { assessment.record(req.body) .then( (result) => { log.info(`Saved assessment, assessment_id: ${result.assessment_id}`); res.json({ status: 'OK', data: { id: result.assessment_id }, }); }).catch((err) => { res.status(500); const response = { status: 'ERROR', error: { code: 'unknown', message: err.message, }, }; if (err.type === 'validation') { res.status(400); response.error.code = 'validation'; } else { log.error(err); } res.json(response); }); }); return router; }
import express from 'express'; import { databaseLogger as log } from '../services/logger'; export default function createRouter(assessment) { const router = express.Router(); router.post('/', (req, res) => { assessment.record(req.body) .then( result => res.json({ status: 'OK', data: { id: result.assessment_id }, }), ).catch( (err) => { res.status(500); const response = { status: 'ERROR', error: { code: 'unknown', message: err.message, }, }; if (err.type === 'validation') { res.status(400); response.error.code = 'validation'; } else { log.error(err); } res.json(response); }, ); }); return router; }
Deal with the compass.rb -> config.rb change
# Copyright 2013 Donald Stufft # # 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.path import shutil import invoke @invoke.task def build(): # Build our CSS files invoke.run("compass compile -c config.rb --force") @invoke.task def watch(): try: # Watch With Compass invoke.run("compass watch -c config.rb") except KeyboardInterrupt: pass
# Copyright 2013 Donald Stufft # # 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.path import shutil import invoke @invoke.task def build(): # Build our CSS files invoke.run("compass compile -c compass.rb --force") @invoke.task def watch(): try: # Watch With Compass invoke.run("compass watch -c compass.rb") except KeyboardInterrupt: pass
Save confirmed files with Google Books ID
from flask import Flask, render_template, request, jsonify import os import shutil import requests app = Flask(__name__) app.config.from_object('config.Debug') @app.route('/upload', methods=['GET', 'POST']) def upload(): if request.method == 'GET': return render_template('upload.html') elif request.method == 'POST': file = request.files['file'] if file: filename = os.urandom(30).encode('hex') + '.' + file.filename.split('.')[-1] while os.path.isfile(os.path.join(app.config['TEMP_DIR'], filename)): filename = os.urandom(30).encode('hex') file.save(os.path.join(app.config['TEMP_DIR'], filename)) return jsonify(filename=filename) @app.route('/confirm/<filename>/<id>', methods=['POST']) def confirm(filename, id): r = requests.get('https://www.googleapis.com/books/v1/volumes/s1gVAAAAYAAJ').json() print r['id'] if os.path.isfile(os.path.join(app.config['TEMP_DIR'], filename)): shutil.move(os.path.join(app.config['TEMP_DIR'], filename), os.path.join(app.config['LIB_DIR'], r['id']+'.'+filename.split('.')[-1])) return '' if __name__ == "__main__": app.run()
from flask import Flask, render_template, request, jsonify import os import shutil app = Flask(__name__) app.config.from_object('config.Debug') @app.route('/upload', methods=['GET', 'POST']) def upload(): if request.method == 'GET': return render_template('upload.html') elif request.method == 'POST': file = request.files['file'] if file: filename = os.urandom(30).encode('hex') + '.' + file.filename.split('.')[-1] while os.path.isfile(os.path.join(app.config['TEMP_DIR'], filename)): filename = os.urandom(30).encode('hex') file.save(os.path.join(app.config['TEMP_DIR'], filename)) return jsonify(filename=filename) @app.route('/confirm/<filename>/<id>', methods=['POST']) def confirm(filename, id): if os.path.isfile(os.path.join(app.config['TEMP_DIR'], filename)): shutil.move(os.path.join(app.config['TEMP_DIR'], filename), os.path.join(app.config['LIB_DIR'], filename)) return '' if __name__ == "__main__": app.run()
Fix script to include repos in PYTHONPATH The repos checkout needs to be in the PYTHONPATH for the import of the xstatic module to work. Since we invoke the xstatic_check_version.py by absolute path, Python does not include the cwd() in the PYTHONPATH. Change-Id: Idd4f8db6334c9f29168e3bc39de3ed95a4e1c60f
#! /usr/bin/env python # # 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 importlib import os import sys from setuptools_scm import get_version # add the xstatic repos checkout to the PYTHONPATH so we can # import its contents sys.path.append(os.getcwd()) xs = None for name in os.listdir('xstatic/pkg'): if os.path.isdir('xstatic/pkg/' + name): if xs is not None: sys.exit('More than one xstatic.pkg package found.') xs = importlib.import_module('xstatic.pkg.' + name) if xs is None: sys.exit('No xstatic.pkg package found.') git_version = get_version() if git_version != xs.PACKAGE_VERSION: sys.exit('git tag version ({}) does not match package version ({})'. format(git_version, xs.PACKAGE_VERSION))
#! /usr/bin/env python # # 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 importlib import os import sys from setuptools_scm import get_version xs = None for name in os.listdir('xstatic/pkg'): if os.path.isdir('xstatic/pkg/' + name): if xs is not None: sys.exit('More than one xstatic.pkg package found.') xs = importlib.import_module('xstatic.pkg.' + name) if xs is None: sys.exit('No xstatic.pkg package found.') git_version = get_version() if git_version != xs.PACKAGE_VERSION: sys.exit('git tag version ({}) does not match package version ({})'. format(git_version, xs.PACKAGE_VERSION))
Fix checkstyle error that one line exceeds the width.
package com.orhanobut.hawk; import java.lang.reflect.Type; /** * Intermediate layer that handles serialization/deserialization for the end result. * This is not the same as {@link Serializer}. This interface is only used to convert the intermediate value * into String or vice-versa to be used for {@link Storage} * * <p>Use custom implementation if built-in implementation is not enough.</p> * * @see GsonParser */ public interface Parser { /** * Deserialize the given text for the given type and returns it. * * @param content is the value that will be deserialized. * @param type is the object type which value will be converted to. * @param <T> is the expected type. * @return the expected type. * @throws Exception if the operation is not successful. */ <T> T fromJson(String content, Type type) throws Exception; /** * Serialize the given object to String. * * @param body is the object that will be serialized. * @return the serialized text. */ String toJson(Object body); }
package com.orhanobut.hawk; import java.lang.reflect.Type; /** * Intermediate layer that handles serialization/deserialization for the end result. * This is not the same as {@link Serializer}. This interface is only used to convert the intermediate value into String, * or vice-versa to be used for {@link Storage} * * <p>Use custom implementation if built-in implementation is not enough.</p> * * @see GsonParser */ public interface Parser { /** * Deserialize the given text for the given type and returns it. * * @param content is the value that will be deserialized. * @param type is the object type which value will be converted to. * @param <T> is the expected type. * @return the expected type. * @throws Exception if the operation is not successful. */ <T> T fromJson(String content, Type type) throws Exception; /** * Serialize the given object to String. * * @param body is the object that will be serialized. * @return the serialized text. */ String toJson(Object body); }
Select a citation after updating.
import { documentHelpers } from '../model' import ApiExtension from './ApiExtension' export default class ReferenceApi extends ApiExtension { /** * @param {object} data from ReferenceModal state */ addReference (data) { return this.insertReference(data) } /** * @param {object} data from ReferenceModal state * @param {object} currentReference */ insertReference (data, currentReference) { const editorSession = this.api.getEditorSession() const doc = editorSession.getDocument() const root = doc.root let insertPos = root.references.length if (currentReference) { insertPos = currentReference.getPosition() + 1 } const nodeData = Object.assign({}, data, { type: 'reference' }) return this.api.insertNode([root.id, 'references'], insertPos, nodeData) } /** * @param {string} citationId * @param {object} data from CitationModal state */ updateCitation (citationId, data) { this.api.getEditorSession().transaction(tx => { documentHelpers.updateProperty(tx, [citationId, 'references'], data.references) this.api._selectInlineNode(tx, tx.get(citationId)) }) } }
import { documentHelpers } from '../model' import ApiExtension from './ApiExtension' export default class ReferenceApi extends ApiExtension { /** * @param {object} data from ReferenceModal state */ addReference (data) { return this.insertReference(data) } /** * @param {object} data from ReferenceModal state * @param {object} currentReference */ insertReference (data, currentReference) { const editorSession = this.api.getEditorSession() const doc = editorSession.getDocument() const root = doc.root let insertPos = root.references.length if (currentReference) { insertPos = currentReference.getPosition() + 1 } const nodeData = Object.assign({}, data, { type: 'reference' }) return this.api.insertNode([root.id, 'references'], insertPos, nodeData) } /** * @param {string} citationId * @param {object} data from CitationModal state */ updateCitation (citationId, data) { this.api.getEditorSession().transaction(tx => { documentHelpers.updateProperty(tx, [citationId, 'references'], data.references) this.api._selectItem(tx, tx.get(citationId)) }) } }
Return a JsonNode not a String from the serializer so that Play sends the correct headers.
package controllers.api; import java.io.IOException; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; /** * Helper methods for writing REST API routines * @author mattwigway * */ public class JsonManager<T> { private static ObjectMapper om = new ObjectMapper(); private Class<T> theClass; /** * Convert an object to its JSON representation * @param o the object to convert * @return the JSON string * @throws JsonProcessingException */ public JsonNode write (T o) throws JsonProcessingException { return om.valueToTree(o); } public T read (String s) throws JsonParseException, JsonMappingException, IOException { return om.readValue(s, theClass); } public T read (JsonParser p) throws JsonParseException, JsonMappingException, IOException { return om.readValue(p, theClass); } }
package controllers.api; import java.io.IOException; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; /** * Helper methods for writing REST API routines * @author mattwigway * */ public class JsonManager<T> { private static ObjectMapper om = new ObjectMapper(); private Class<T> theClass; /** * Convert an object to its JSON representation * @param o the object to convert * @return the JSON string * @throws JsonProcessingException */ public String write (T o) throws JsonProcessingException { return om.writeValueAsString(o); } public T read (String s) throws JsonParseException, JsonMappingException, IOException { return om.readValue(s, theClass); } public T read (JsonParser p) throws JsonParseException, JsonMappingException, IOException { return om.readValue(p, theClass); } }
Allow local statisticians to view the ReportToken link links
<?php namespace TmlpStats\Policies; use TmlpStats\User; class ReportTokenPolicy extends Policy { /** * Create a new policy instance. * * @return void */ public function __construct() { // } /** * Can $user view the full list of reportTokens? * * @param User $user * @return bool */ public function index(User $user) { return false; // admin only } /** * Can user view the ReportToken's URL? * * @param User $user * @return bool */ public function readLink(User $user) { return ($user->hasRole('globalStatistician') || $user->hasRole('localStatistician')); } }
<?php namespace TmlpStats\Policies; use TmlpStats\User; class ReportTokenPolicy extends Policy { /** * Create a new policy instance. * * @return void */ public function __construct() { // } /** * Can $user view the full list of reportTokens? * * @param User $user * @return bool */ public function index(User $user) { return false; // admin only } /** * Can user view the ReportToken's URL? * * @param User $user * @return bool */ public function readLink(User $user) { return $user->hasRole('globalStatistician'); } }
Handle just parse errors in provider Previously all errors were reported as JSON parse errors.
/* * Copyright 2014-2015 Fabian Tollenaar <fabian@starting-point.nl> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var Transform = require('stream').Transform; function FromJson() { Transform.call(this, { objectMode: true }); } require('util').inherits(FromJson, Transform); FromJson.prototype._transform = function(chunk, encoding, done) { var parsed = null; try { parsed = JSON.parse(chunk.toString()); } catch (ex) { console.error("Could not parse JSON:" + chunk.toString()); } if (parsed) { this.push(parsed) } done(); } module.exports = FromJson;
/* * Copyright 2014-2015 Fabian Tollenaar <fabian@starting-point.nl> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var Transform = require('stream').Transform; function FromJson() { Transform.call(this, { objectMode: true }); } require('util').inherits(FromJson, Transform); FromJson.prototype._transform = function(chunk, encoding, done) { try { this.push(JSON.parse(chunk.toString())); } catch (ex) { console.error("Could not parse JSON:" + chunk.toString()); } done(); } module.exports = FromJson;
Use different type hint here.
<?php namespace ParagonIE\Halite\Asymmetric; use ParagonIE\Halite\Alerts\{ CannotPerformOperation, InvalidType }; use ParagonIE\Halite\HiddenString; use ParagonIE\Halite\Key; /** * Class SecretKey * @package ParagonIE\Halite\Asymmetric * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ class SecretKey extends Key { /** * SecretKey constructor. * @param HiddenString $keyMaterial - The actual key data * * @throws CannotPerformOperation * @throws InvalidType */ public function __construct(HiddenString $keyMaterial) { parent::__construct($keyMaterial); $this->isAsymmetricKey = true; } /** * See the appropriate derived class. * @throws CannotPerformOperation * @return mixed */ public function derivePublicKey() { throw new CannotPerformOperation( 'This is not implemented in the base class' ); } }
<?php namespace ParagonIE\Halite\Asymmetric; use ParagonIE\Halite\Alerts\{ CannotPerformOperation, InvalidType }; use ParagonIE\Halite\HiddenString; use ParagonIE\Halite\Key; /** * Class SecretKey * @package ParagonIE\Halite\Asymmetric * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ class SecretKey extends Key { /** * SecretKey constructor. * @param HiddenString $keyMaterial - The actual key data * * @throws CannotPerformOperation * @throws InvalidType */ public function __construct(HiddenString $keyMaterial) { parent::__construct($keyMaterial); $this->isAsymmetricKey = true; } /** * See the appropriate derived class. * @throws CannotPerformOperation * @return void */ public function derivePublicKey() { throw new CannotPerformOperation( 'This is not implemented in the base class' ); } }
Debug update continued: Removed the cost of mesh position to ints.
package net.piemaster.jario.systems; import net.piemaster.jario.components.CollisionMesh; import net.piemaster.jario.components.Transform; import com.artemis.ComponentMapper; import com.artemis.Entity; import com.artemis.EntityProcessingSystem; public class CollisionMeshSystem extends EntityProcessingSystem { private ComponentMapper<Transform> transformMapper; private ComponentMapper<CollisionMesh> meshMapper; @SuppressWarnings("unchecked") public CollisionMeshSystem() { super(Transform.class, CollisionMesh.class); } @Override public void initialize() { transformMapper = new ComponentMapper<Transform>(Transform.class, world.getEntityManager()); meshMapper = new ComponentMapper<CollisionMesh>(CollisionMesh.class, world.getEntityManager()); } @Override protected void process(Entity e) { CollisionMesh mesh = meshMapper.get(e); if(mesh != null) { Transform t = transformMapper.get(e); meshMapper.get(e).setLocation(t.getX(), t.getY()); } } }
package net.piemaster.jario.systems; import net.piemaster.jario.components.CollisionMesh; import net.piemaster.jario.components.Transform; import com.artemis.ComponentMapper; import com.artemis.Entity; import com.artemis.EntityProcessingSystem; public class CollisionMeshSystem extends EntityProcessingSystem { private ComponentMapper<Transform> transformMapper; private ComponentMapper<CollisionMesh> meshMapper; @SuppressWarnings("unchecked") public CollisionMeshSystem() { super(Transform.class, CollisionMesh.class); } @Override public void initialize() { transformMapper = new ComponentMapper<Transform>(Transform.class, world.getEntityManager()); meshMapper = new ComponentMapper<CollisionMesh>(CollisionMesh.class, world.getEntityManager()); } @Override protected void process(Entity e) { CollisionMesh mesh = meshMapper.get(e); if(mesh != null) { Transform t = transformMapper.get(e); meshMapper.get(e).setLocation((int)t.getX(), (int)t.getY()); } } }
Reorder config groups for better documentation
package io.quarkus.dynamodb.runtime; import io.quarkus.runtime.annotations.ConfigItem; import io.quarkus.runtime.annotations.ConfigPhase; import io.quarkus.runtime.annotations.ConfigRoot; @ConfigRoot(phase = ConfigPhase.RUN_TIME) public class DynamodbConfig { /** * Enable DynamoDB service endpoint discovery. */ @ConfigItem public boolean enableEndpointDiscovery; /** * SDK client configurations */ @ConfigItem(name = ConfigItem.PARENT) public SdkConfig sdk; /** * AWS service configurations */ @ConfigItem public AwsConfig aws; /** * Apache HTTP client transport configuration */ @ConfigItem public ApacheHttpClientConfig syncClient; /** * Netty HTTP client transport configuration */ @ConfigItem public NettyHttpClientConfig asyncClient; }
package io.quarkus.dynamodb.runtime; import io.quarkus.runtime.annotations.ConfigItem; import io.quarkus.runtime.annotations.ConfigPhase; import io.quarkus.runtime.annotations.ConfigRoot; @ConfigRoot(phase = ConfigPhase.RUN_TIME) public class DynamodbConfig { /** * Enable DynamoDB service endpoint discovery. */ @ConfigItem public boolean enableEndpointDiscovery; /** * AWS service configurations */ @ConfigItem public AwsConfig aws; /** * SDK client configurations */ @ConfigItem(name = ConfigItem.PARENT) public SdkConfig sdk; /** * Apache HTTP client transport configuration */ @ConfigItem public ApacheHttpClientConfig syncClient; /** * Netty HTTP client transport configuration */ @ConfigItem public NettyHttpClientConfig asyncClient; }
Add simple stub for GitHub Webhooks
<?php require_once 'lib/Config.php'; require_once 'lib/Session.php'; require_once 'lib/functions.php'; require_once 'lib/Slim/Slim.php'; \Slim\Slim::registerAutoloader(); $db = new PDO(Config::get('datasource')); $app = new \Slim\Slim(); /* Index */ $app->get('/', function() use ($app) { $app->redirect('https://decke.github.io/redports/', 301); }); /* GitHub Webhooks */ $app->post('/github/', function() use ($app) { switch($app->request->headers->get('X-GitHub-Event')) { case 'ping': $app->response->write('pong'); break; case 'push': $app->response->write('Push event not implemented yet'); break; default: $app->response->write('Event type not implemented'); break; } }); /* Jobs */ $app->get('/api/jobs/:jobid', 'isAllowed', function($jobid) use ($app) { $app->response->headers->set('Content-Type', 'application/json'); $app->response->write(json_encode(array("jobid" => $jobid))); })->conditions(array('jobid' => '[0-9]{1,}')); $app->run();
<?php require_once 'lib/Config.php'; require_once 'lib/Session.php'; require_once 'lib/functions.php'; require_once 'lib/Slim/Slim.php'; \Slim\Slim::registerAutoloader(); $db = new PDO(Config::get('datasource')); $app = new \Slim\Slim(); /* Index */ $app->get('/', function() use ($app) { $app->redirect('https://decke.github.io/redports/', 301); }); /* Jobs */ $app->get('/api/jobs/:jobid', 'isAllowed', function($jobid) use ($app) { $app->response->headers->set('Content-Type', 'application/json'); $app->response->write(json_encode(array("jobid" => $jobid))); })->conditions(array('jobid' => '[0-9]{1,}')); $app->run();
Use Node 10.x within Vagrant
module.exports = { config: { FulgensVersion: '1.0.0', Name: "citybuilder", Vagrant: { Box: 'ubuntu/xenial64', BeforeInstall: [ "curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -" ], Install: 'nodejs docker.io' } }, software: { "couchdb": { Source: "couchdb" }, "node": { Source: "node", Artifact: "startServer.js", ExposedPort: 8080, configFile: { Name: "citybuilder.properties", Connections: [ { Source:"couchdb", Var: "dbHost", Content: "http://$$VALUE$$:5984" }, { Source:"couchdb", Var: "db", Content: "http://$$VALUE$$:5984/citybuilder" }, ], Content: [ "dbSchema=citybuilder", "httpPort=8080", "httpHost=0.0.0.0" ], AttachAsEnvVar: ["CITYBUILDER_PROPERTIES", "$$SELF_NAME$$"] } } } }
module.exports = { config: { Name: "citybuilder", Vagrant: { Box: 'ubuntu/xenial64', Install: 'npm docker.io' } }, software: { "couchdb": { Source: "couchdb" }, "node": { Source: "node", Artifact: "startServer.js", ExposedPort: 8080, configFile: { Name: "citybuilder.properties", Connections: [ { Source:"couchdb", Var: "dbHost", Content: "http://$$VALUE$$:5984" }, { Source:"couchdb", Var: "db", Content: "http://$$VALUE$$:5984/citybuilder" }, ], Content: [ "dbSchema=citybuilder", "httpPort=8080", "httpHost=0.0.0.0" ], AttachAsEnvVar: ["CITYBUILDER_PROPERTIES", "$$SELF_NAME$$"] } } } }
Add test URL to try against server
/*global define*/ // ignore non-camel case decided by server /* jshint -W106*/ define(['underscore', 'backbone'], function(_, Backbone) { 'use strict'; // UsageModel // -------- // // This is the model backing the Usage Widget // window.Usage = Backbone.Model.extend({ url: function() { return '/api/v1/cluster/' + this.get('cluster') + '/space'; }, defaults: { added_date: Date.now(), cluster: 1, id: 0, total_avail: 0, total_space: 0, total_used: 0 }, getPercentageUsed: function() { return this.get('total_used') / this.get('total_avail') * 100; } }); return window.Usage; });
/*global define*/ // ignore non-camel case decided by server /* jshint -W106*/ define(['underscore', 'backbone'], function(_, Backbone) { 'use strict'; // UsageModel // -------- // // This is the model backing the Usage Widget // return Backbone.Model.extend({ defaults: { added_date: Date.now(), cluster: 0, id: 0, total_avail: 0, total_space: 0, total_used: 0 }, getPercentageUsed: function() { return this.get('total_used') / this.get('total_avail') * 100; } }); });
Use 0.0 as our version Signed-off-by: Tycho Andersen <10c18fcb898ee6b17d6575d444b125d10b3f4d6a@canonical.com>
/* This is a FLEXible file which can be used by both client and daemon. * Teehee. */ package lxd import ( "bufio" "os" "path/filepath" ) var Version = "0.0" /* * Please increment the api compat number every time you change the API. * * Version 1.0: ping */ var APICompat = 1 var APIVersion = "1.0" // VarPath returns the provided path elements joined by a slash and // appended to the end of $LXD_DIR, which defaults to /var/lib/lxd. func VarPath(path ...string) string { varDir := os.Getenv("LXD_DIR") if varDir == "" { varDir = "/var/lib/lxd" } items := []string{varDir} items = append(items, path...) return filepath.Join(items...) } func ReadStdin() ([]byte, error) { buf := bufio.NewReader(os.Stdin) line, _, err := buf.ReadLine() if err != nil { return nil, err } return line, nil }
/* This is a FLEXible file which can be used by both client and daemon. * Teehee. */ package lxd import ( "bufio" "os" "path/filepath" ) var Version = "0.0.1" /* * Please increment the api compat number every time you change the API. * * Version 1.0: ping */ var APICompat = 1 var APIVersion = "1.0" // VarPath returns the provided path elements joined by a slash and // appended to the end of $LXD_DIR, which defaults to /var/lib/lxd. func VarPath(path ...string) string { varDir := os.Getenv("LXD_DIR") if varDir == "" { varDir = "/var/lib/lxd" } items := []string{varDir} items = append(items, path...) return filepath.Join(items...) } func ReadStdin() ([]byte, error) { buf := bufio.NewReader(os.Stdin) line, _, err := buf.ReadLine() if err != nil { return nil, err } return line, nil }
Change branding on default config.
/* exported defaults */ /* Magic Mirror * Config Defauls * * By Michael Teeuw http://michaelteeuw.nl * MIT Licensed. */ var defaults = { port: 8080, language: "en", timeFormat: 24, modules: [ { module: "helloworld", position: "upper_third", config: { text: "Magic Mirror<sup>2</sup>", classes: "large thin" } }, { module: "helloworld", position: "middle_center", config: { text: "Please create a config file." } }, { module: "helloworld", position: "middle_center", config: { text: "See README for more information.", classes: "small dimmed" } }, { module: "helloworld", position: "bottom_bar", config: { text: "www.michaelteeuw.nl", classes: "xsmall dimmed" } }, ], paths: { modules: "modules", vendor: "vendor" }, }; /*************** DO NOT EDIT THE LINE BELOW ***************/ if (typeof module !== "undefined") {module.exports = defaults;}
/* exported defaults */ /* Magic Mirror * Config Defauls * * By Michael Teeuw http://michaelteeuw.nl * MIT Licensed. */ var defaults = { port: 8080, language: "en", timeFormat: 24, modules: [ { module: "helloworld", position: "upper_third", config: { text: "Magic Mirror V2", classes: "large thin" } }, { module: "helloworld", position: "middle_center", config: { text: "Please create a config file." } }, { module: "helloworld", position: "middle_center", config: { text: "See README for more information.", classes: "small dimmed" } }, { module: "helloworld", position: "bottom_bar", config: { text: "www.michaelteeuw.nl", classes: "xsmall dimmed" } }, ], paths: { modules: "modules", vendor: "vendor" }, }; /*************** DO NOT EDIT THE LINE BELOW ***************/ if (typeof module !== "undefined") {module.exports = defaults;}
Store and load methods (stubs)
/* * 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 nl.meg.propertiesutility; import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; /** * * @author meine */ public class Properties { private final Map<String, String> properties = new HashMap<>(); public Properties(){ } public void setProperty(String key, String value){ properties.put(key, value); } public String getProperty(String property){ return properties.get(property); } public String getProperty(String property, String defaultValue){ if(properties.containsKey(property)){ return properties.get(property); }else{ return defaultValue; } } public void load(InputStream in){ } public void store (OutputStream out, String comments){ } }
/* * 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 nl.meg.propertiesutility; import java.util.HashMap; import java.util.Map; /** * * @author meine */ public class Properties { private final Map<String, String> properties = new HashMap<>(); public Properties(){ } public void setProperty(String key, String value){ properties.put(key, value); } public String getProperty(String property){ return properties.get(property); } public String getProperty(String property, String defaultValue){ if(properties.containsKey(property)){ return properties.get(property); }else{ return defaultValue; } } }
Use try-with-resources instead of try/finally
/* * Copyright 2010 Proofpoint, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.proofpoint.jmx; import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; final class NetUtils { private NetUtils() { } public static int findUnusedPort() throws IOException { int port; try (ServerSocket socket = new ServerSocket()) { socket.bind(new InetSocketAddress(0)); port = socket.getLocalPort(); } return port; } }
/* * Copyright 2010 Proofpoint, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.proofpoint.jmx; import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; final class NetUtils { private NetUtils() { } public static int findUnusedPort() throws IOException { int port; ServerSocket socket = new ServerSocket(); try { socket.bind(new InetSocketAddress(0)); port = socket.getLocalPort(); } finally { socket.close(); } return port; } }
Fix spec compliance of error title
<?php declare(strict_types=1); namespace WoohooLabs\Yin\JsonApi\Exception; use WoohooLabs\Yin\JsonApi\Schema\Error\Error; class RelationshipNotExists extends AbstractJsonApiException { /** * @var string */ protected $relationship; public function __construct(string $relationship) { parent::__construct("The requested relationship '$relationship' does not exist!"); $this->relationship = $relationship; } protected function getErrors(): array { return [ Error::create() ->setStatus("404") ->setCode("RELATIONSHIP_NOT_EXISTS") ->setTitle("The requested relationship does not exist!") ->setDetail($this->getMessage()) ]; } public function getRelationship(): string { return $this->relationship; } }
<?php declare(strict_types=1); namespace WoohooLabs\Yin\JsonApi\Exception; use WoohooLabs\Yin\JsonApi\Schema\Error\Error; class RelationshipNotExists extends AbstractJsonApiException { /** * @var string */ protected $relationship; public function __construct(string $relationship) { parent::__construct("The requested relationship '$relationship' does not exist!"); $this->relationship = $relationship; } protected function getErrors(): array { return [ Error::create() ->setStatus("404") ->setCode("RELATIONSHIP_NOT_EXISTS") ->setTitle("The requested relationship '$this->relationship' does not exist!") ->setDetail($this->getMessage()) ]; } public function getRelationship(): string { return $this->relationship; } }
Refactor Store Query to On-Demand Query with backward compatibility.
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.siddhi.core.exception; /** * Exception class to be used when an error occurs while executing on-demand queries. * This is deprecated and use OnDemandQueryRuntimeException instead. */ @Deprecated public abstract class StoreQueryRuntimeException extends RuntimeException { protected StoreQueryRuntimeException() { super(); } protected StoreQueryRuntimeException(String message) { super(message); } protected StoreQueryRuntimeException(String message, Throwable throwable) { super(message, throwable); } protected StoreQueryRuntimeException(Throwable throwable) { super(throwable); } public abstract boolean isClassLoadingIssue(); }
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.siddhi.core.exception; /** * Exception class to be used when an error occurs while executing on-demand queries. * This is deprecated and use OnDemandQueryRuntimeException instead. */ @Deprecated public abstract class StoreQueryRuntimeException extends RuntimeException { boolean classLoadingIssue = false; protected StoreQueryRuntimeException() { super(); } protected StoreQueryRuntimeException(String message) { super(message); } protected StoreQueryRuntimeException(String message, Throwable throwable) { super(message, throwable); } protected StoreQueryRuntimeException(Throwable throwable) { super(throwable); } public abstract boolean isClassLoadingIssue(); }
Remove the "view/" part for viewing signatures
from django.conf.urls import patterns, include, url from rest_framework import routers from crashmanager import views router = routers.DefaultRouter() router.register(r'signatures', views.BucketViewSet) router.register(r'crashes', views.CrashEntryViewSet) urlpatterns = patterns('', url(r'^rest/api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^logout/$', views.logout_view, name='logout'), url(r'^$', views.index, name='index'), url(r'^signatures/$', views.signatures, name='signatures'), url(r'^signatures/new/$', views.newSignature, name='signew'), url(r'^signatures/(?P<sigid>\d+)/edit/$', views.editSignature, name='sigedit'), url(r'^signatures/(?P<sigid>\d+)/linkextbug/$', views.editSignature, name='linkextbug'), url(r'^signatures/(?P<sigid>\d+)/$', views.viewSignature, name='sigview'), url(r'^signatures/(?P<sigid>\d+)/delete/$', views.deleteSignature, name='sigdel'), url(r'^crashes/$', views.crashes, name='crashes'), url(r'^crashes/(?P<crashid>\d+)/$', views.viewCrashEntry, name='crashview'), url(r'^rest/', include(router.urls)), )
from django.conf.urls import patterns, include, url from rest_framework import routers from crashmanager import views router = routers.DefaultRouter() router.register(r'signatures', views.BucketViewSet) router.register(r'crashes', views.CrashEntryViewSet) urlpatterns = patterns('', url(r'^rest/api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^logout/$', views.logout_view, name='logout'), url(r'^$', views.index, name='index'), url(r'^signatures/$', views.signatures, name='signatures'), url(r'^signatures/new/$', views.newSignature, name='signew'), url(r'^signatures/(?P<sigid>\d+)/edit/$', views.editSignature, name='sigedit'), url(r'^signatures/(?P<sigid>\d+)/linkextbug/$', views.editSignature, name='linkextbug'), url(r'^signatures/(?P<sigid>\d+)/view/$', views.viewSignature, name='sigview'), url(r'^signatures/(?P<sigid>\d+)/delete/$', views.deleteSignature, name='sigdel'), url(r'^crashes/$', views.crashes, name='crashes'), url(r'^crashes/(?P<crashid>\d+)/$', views.viewCrashEntry, name='crashview'), url(r'^rest/', include(router.urls)), )
Fix reaggroing when player gets hit while deaggrod.
import Obstacle from './Obstacle' export default class extends Obstacle { constructor (game, player, x, y, frame, bulletFrame) { super(game, player, x, y, frame) this.weapon = this.game.plugins.add(Phaser.Weapon) this.weapon.trackSprite(this) this.weapon.createBullets(50, 'chars_small', bulletFrame) this.weapon.bulletSpeed = 600 this.weapon.fireRate = 200 this.target = null } update () { super.update() this.game.physics.arcade.overlap(this.player, this.weapon.bullets, this.onCollision, null, this) if (!this.inCamera) { return } if (this.target != null) { this.weapon.fireAtSprite(this.target) } else if (this.weapon.fire()) { this.weapon.fireAngle += 30 } } onCollision () { super.onCollision() if (this.target != null) { const saved = this.target this.target = null setTimeout(() => this.target = saved, 1000) } } }
import Obstacle from './Obstacle' export default class extends Obstacle { constructor (game, player, x, y, frame, bulletFrame) { super(game, player, x, y, frame) this.weapon = this.game.plugins.add(Phaser.Weapon) this.weapon.trackSprite(this) this.weapon.createBullets(50, 'chars_small', bulletFrame) this.weapon.bulletSpeed = 600 this.weapon.fireRate = 200 this.target = null } update () { super.update() this.game.physics.arcade.overlap(this.player, this.weapon.bullets, this.onCollision, null, this) if (!this.inCamera) { return } if (this.target != null) { this.weapon.fireAtSprite(this.target) } else if (this.weapon.fire()) { this.weapon.fireAngle += 30 } } onCollision () { super.onCollision() const saved = this.target this.target = null setTimeout(() => this.target = saved, 1000) } }
Use sceneRecord.get to get current route
/* @flow */ import React from "react-native"; import routeMapper from "../routes/routeMapper"; import Colors from "../../Colors.json"; const { NavigationCard, StyleSheet, View } = React; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: Colors.lightGrey }, normal: { marginTop: 56 } }); const renderScene = function(navState: Object, onNavigation: Function): Function { return props => { const route = props.sceneRecord.get("route"); // eslint-disable-line react/prop-types const { component: RouteComponent, passProps } = routeMapper(route); return ( <NavigationCard {...props}> <View style={[ styles.container, route.fullscreen ? null : styles.normal ]}> <RouteComponent {...passProps} style={styles.container} onNavigation={onNavigation} /> </View> </NavigationCard> ); }; }; export default renderScene;
/* @flow */ import React from "react-native"; import routeMapper from "../routes/routeMapper"; import Colors from "../../Colors.json"; const { NavigationCard, StyleSheet, View } = React; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: Colors.lightGrey }, normal: { marginTop: 56 } }); const renderScene = function(navState: Object, onNavigation: Function): Function { return props => { const route = navState.get(navState.index); const { component: RouteComponent, passProps } = routeMapper(route); return ( <NavigationCard {...props}> <View style={[ styles.container, route.fullscreen ? null : styles.normal ]}> <RouteComponent {...passProps} style={styles.container} onNavigation={onNavigation} /> </View> </NavigationCard> ); }; }; export default renderScene;