text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix service name in frontend
<?php namespace Frontend\Modules\ContentBlocks\Widgets; use Backend\Modules\ContentBlocks\Entity\ContentBlock; use Backend\Modules\ContentBlocks\Repository\ContentBlockRepository; use Frontend\Core\Engine\Base\Widget as FrontendBaseWidget; use Frontend\Core\Language\Locale; /** * This is the detail widget. */ class Detail extends FrontendBaseWidget { /** * Execute the extra */ public function execute() { parent::execute(); $contentBlock = $this->get('content_blocks.repository.content_block')->findOneByIdAndLocale( (int) $this->data['id'], Locale::frontendLanguage() ); // if the content block is not found or if it is hidden, just return an array with empty text // @deprecated fix this for version 5, we just shouldn't assign this instead of this hack, but we need it for BC if (!$contentBlock instanceof ContentBlock || $contentBlock->isHidden()) { $contentBlock = ['text' => '']; } $this->tpl->assign('widgetContentBlocks', $contentBlock); // That's all folks! } }
<?php namespace Frontend\Modules\ContentBlocks\Widgets; use Backend\Modules\ContentBlocks\Entity\ContentBlock; use Backend\Modules\ContentBlocks\Repository\ContentBlockRepository; use Frontend\Core\Engine\Base\Widget as FrontendBaseWidget; use Frontend\Core\Language\Locale; /** * This is the detail widget. */ class Detail extends FrontendBaseWidget { /** * Execute the extra */ public function execute() { parent::execute(); $contentBlock = $this->get('content_blocks.repository.content_blocks')->findOneByIdAndLocale( (int) $this->data['id'], Locale::frontendLanguage() ); // if the content block is not found or if it is hidden, just return an array with empty text // @deprecated fix this for version 5, we just shouldn't assign this instead of this hack, but we need it for BC if (!$contentBlock instanceof ContentBlock || $contentBlock->isHidden()) { $contentBlock = ['text' => '']; } $this->tpl->assign('widgetContentBlocks', $contentBlock); // That's all folks! } }
Add color log in the world generator
'use strict'; const rethinkDB = require('rethinkdb'); const program = require('commander'); const log = require('./log'); var worldDB = 'labyrinth'; if (require.main === module) { program .version('0.0.1') .option('-p, --port <n>', 'Port for RethinkDB, default is 28015', parseInt, {isDefault: 28015}) .option('-t, --test <n>', 'Create n Corals', parseInt) .parse(process.argv); rethinkDB.connect( {host: 'localhost', port: 28015}, function(err, conn) { if (err) throw err; rethinkDB .dbCreate(worldDB) .run(conn, (err, res) => { if (err) { log.error(`The world is exist. ` + `If you really want create a new world, ` + `delete the database "${worldDB}".`); throw err; } }); }); }
'use strict'; const rethinkDB = require('rethinkdb'); const program = require('commander'); const colors = require('colors'); const common = require('./common'); var worldDB = 'labyrinth'; if (require.main === module) { program .version('0.0.1') .option('-p, --port <n>', 'Port for RethinkDB, default is 28015', parseInt, {isDefault: 28015}) .option('-t, --test <n>', 'Create n Corals', parseInt) .parse(process.argv); rethinkDB.connect( {host: 'localhost', port: 28015}, function(err, conn) { if (err) throw err; rethinkDB .dbCreate(worldDB) .run(conn, (err, res) => { if (err) { common.log(colors.red(`The world is exist. ` + `If you really want create a new world, ` + `delete the database "${worldDB}".`)); throw err; } }); }); }
Write pi code to use button
#!/home/pi/coffee/venv/bin/python import os import sys import time from coffee.models import Status sys.path.append(os.path.dirname(os.path.dirname(__file__))) DEBUG = 1 # The GPIO pin the button is connected to BUTTON_PIN = 7 # The GPIO pin the button's LED is connected to LED_PIN = 4 def main(): import RPi.GPIO as GPIO status = Status() GPIO.setmode(GPIO.BCM) GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(LED_PIN, GPIO.OUT, initial=1) # Blink the LED, leave off def blink_led(num_blinks, blink_duration, blink_pause): for b in range(num_blinks): GPIO.output(LED_PIN, 1) time.sleep(blink_duration) GPIO.output(LED_PIN, 0) time.sleep(blink_pause) GPIO.output(LED_PIN, 0) # Listen for button presses while True: input_value = GPIO.input(BUTTON_PIN) if input_value == False: status.update(True) blink_led(3, 0.3, 0.2) status.update(False) time.sleep(0.1) main()
#!/home/pi/coffee/venv/bin/python import os import sys import time from coffee.models import Status sys.path.append(os.path.dirname(os.path.dirname(__file__))) DEBUG = 1 PIN = 14 def main(): import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) status = Status() def rc_time(RCpin): reading = 0 GPIO.setup(RCpin, GPIO.OUT) GPIO.output(RCpin, GPIO.LOW) time.sleep(0.1) GPIO.setup(RCpin, GPIO.IN) while (GPIO.input(RCpin) == GPIO.LOW): reading += 1 if reading > 5000: return reading return reading while True: if rc_time(PIN) <= 5000: status.update(True) else: status.update(False) main()
Use Production value as flag default
package core import ( "flag" "net/http" ) var ( // Production allows handlers know whether the server is running in a production environment. Production bool // Address is the TCP network address on which the server is listening and serving. Default is ":8080". Address = ":8080" // beforeRun stores a set of functions that are triggered just before running the server. beforeRun []func() ) func init() { flag.BoolVar(&Production, "production", Production, "run the server in production environment") flag.StringVar(&Address, "address", Address, "the address to listen and serving on") } // BeforeRun adds a function that will be triggered just before running the server. func BeforeRun(f func()) { beforeRun = append(beforeRun, f) } // Run starts the server for listening and serving. func Run() { for _, f := range beforeRun { f() } panic(http.ListenAndServe(Address, defaultHandlersStack)) }
package core import ( "flag" "net/http" ) var ( // Production allows handlers know whether the server is running in a production environment. Production bool // Address is the TCP network address on which the server is listening and serving. Default is ":8080". Address = ":8080" // beforeRun stores a set of functions that are triggered just before running the server. beforeRun []func() ) func init() { flag.BoolVar(&Production, "production", false, "run the server in production environment") flag.StringVar(&Address, "address", Address, "the address to listen and serving on") } // BeforeRun adds a function that will be triggered just before running the server. func BeforeRun(f func()) { beforeRun = append(beforeRun, f) } // Run starts the server for listening and serving. func Run() { for _, f := range beforeRun { f() } panic(http.ListenAndServe(Address, defaultHandlersStack)) }
Add russian i18n for angular.
/** * This is a manifest file that will be compiled into application.js, which will * include all the files listed below. * * Any JavaScript file within this directory can be referenced here using a * relative path. * * It's not advisable to add code directly here, but if you do, it will appear * at the bottom of the compiled file. */ //= require lib/jquery-2.1.0.min //= require lib/moment-2.6.0.min //= require lib/moment-langs.min //= require lib/daterangepicker-1.3.5 //= require lib/bootstrap.min //= require lib/underscore-1.6.0.min //= require lib/angular-1.2.16 //= require lib/angular-locale_ru-ru //= require lib/angular-route-1.2.16 //= require lib/angular-cookies-1.2.16 //= require lib/angular-file-upload-0.5.5 //= require lib/ng-bs-daterangepicker-0.0.1 //= require lib/angular-google-maps-1.0.18.min //= require lib/angular-strap-2.0.1 //= require lib/angular-strap-tpl-2.0.1 //= require config //= require_tree ng //= require lib/ng-directives
/** * This is a manifest file that will be compiled into application.js, which will * include all the files listed below. * * Any JavaScript file within this directory can be referenced here using a * relative path. * * It's not advisable to add code directly here, but if you do, it will appear * at the bottom of the compiled file. */ //= require lib/jquery-2.1.0.min //= require lib/moment-2.6.0.min //= require lib/moment-langs.min //= require lib/daterangepicker-1.3.5 //= require lib/bootstrap.min //= require lib/underscore-1.6.0.min //= require lib/angular-1.2.16 //= require lib/angular-route-1.2.16 //= require lib/angular-cookies-1.2.16 //= require lib/angular-file-upload-0.5.5 //= require lib/ng-bs-daterangepicker-0.0.1 //= require lib/angular-google-maps-1.0.18.min //= require lib/angular-strap-2.0.1 //= require config //= require_tree ng //= require lib/ng-directives
Upgrade Meteor to 1.2.0.1 for ddp-proxy-endpoint
Package.describe({ name: 'xamfoo:ddp-proxy-endpoint', version: '0.1.0', // Brief, one-line summary of the package. summary: 'Server package to support xamfoo:ddp-proxy', // URL to the Git repository containing the source code for this package. git: 'https://github.com/xamfoo/ddp-proxy', // By default, Meteor will default to using README.md for documentation. // To avoid submitting documentation, set this field to null. documentation: 'README.md' }); function configure (api) { api.versionsFrom('1.2.0.1'); api.use(['meteor', 'ddp', 'underscore'], 'server'); api.addFiles('ddp-proxy-endpoint.js', 'server'); } Package.onUse(function(api) { configure(api); }); Package.onTest(function(api) { configure(api); api.use(['tinytest', 'mongo'], 'server'); api.use('xamfoo:ddp-proxy', 'server'); api.addFiles(['test-fixtures.js', 'tests.js'], 'server'); });
Package.describe({ name: 'xamfoo:ddp-proxy-endpoint', version: '0.1.0', // Brief, one-line summary of the package. summary: 'Server package to support xamfoo:ddp-proxy', // URL to the Git repository containing the source code for this package. git: 'https://github.com/xamfoo/ddp-proxy', // By default, Meteor will default to using README.md for documentation. // To avoid submitting documentation, set this field to null. documentation: 'README.md' }); function configure (api) { api.versionsFrom('1.0.4.1'); api.use(['meteor', 'ddp', 'underscore'], 'server'); api.addFiles('ddp-proxy-endpoint.js', 'server'); } Package.onUse(function(api) { configure(api); }); Package.onTest(function(api) { configure(api); api.use(['tinytest', 'mongo'], 'server'); api.use('xamfoo:ddp-proxy', 'server'); api.addFiles(['test-fixtures.js', 'tests.js'], 'server'); });
Fix the artist loading & info bug
import http from '../http'; import albumInfo from './album'; import artistInfo from './artist'; export default { /** * Get extra song information (lyrics, artist info, album info). * * @param {Object} song * @param {?Function} cb */ fetch(song, cb = null) { // Check if the song's info has been retrieved before. if (song.infoRetrieved) { cb && cb(); return; } http.get(`${song.id}/info`, response => { const data = response.data; song.lyrics = data.lyrics; data.artist_info && artistInfo.merge(song.artist, data.artist_info); data.album_info && albumInfo.merge(song.album, data.album_info); song.infoRetrieved = true; cb && cb(); }); }, };
import http from '../http'; import albumInfo from './album'; import artistInfo from './artist'; export default { /** * Get extra song information (lyrics, artist info, album info). * * @param {Object} song * @param {?Function} cb */ fetch(song, cb = null) { // Check if the song's info has been retrieved before. if (song.infoRetrieved) { cb && cb(); return; } http.get(`${song.id}/info`, response => { const data = response.data; song.lyrics = data.lyrics; data.artist_info && artistInfo.merge(song.album.artist, data.artist_info); data.album_info && albumInfo.merge(song.album, data.album_info); song.infoRetrieved = true; cb && cb(); }); }, };
Save settings immediately after installation.
<?php namespace Craft; class CryptographerPlugin extends BasePlugin { function getName() { return Craft::t('Cryptographer'); } function getVersion() { return '0.1'; } function getDeveloper() { return 'Miranj'; } function getDeveloperUrl() { return 'http://miranj.in'; } protected function defineSettings() { return array( 'secret' => array(AttributeType::String, 'default' => md5(rand())), ); } public function getSettingsHtml() { return craft()->templates->render('cryptographer/_settings', array( 'settings' => $this->getSettings(), )); } public function onAfterInstall() { // Save plugin settings immediately after install craft()->plugins->savePluginSettings($this, $this->getSettings()); } public function addTwigExtension() { Craft::import('plugins.cryptographer.twigextensions.CryptographerTwigExtension'); return new CryptographerTwigExtension(); } }
<?php namespace Craft; class CryptographerPlugin extends BasePlugin { function getName() { return Craft::t('Cryptographer'); } function getVersion() { return '0.1'; } function getDeveloper() { return 'Miranj'; } function getDeveloperUrl() { return 'http://miranj.in'; } protected function defineSettings() { return array( 'secret' => array(AttributeType::String, 'default' => md5(rand())), ); } public function getSettingsHtml() { return craft()->templates->render('cryptographer/_settings', array( 'settings' => $this->getSettings(), )); } public function addTwigExtension() { Craft::import('plugins.cryptographer.twigextensions.CryptographerTwigExtension'); return new CryptographerTwigExtension(); } }
Increase distance of traversal when key is presesd
function Game(){ this.$track = $('#racetrack'); this.finishLine = this.$track.width() - 54; } function Player(id){ this.player = $('.player')[id - 1]; this.position = 10; } Player.prototype.move = function(){ this.position += 20; }; Player.prototype.updatePosition = function(){ $player = $(this.player); $player.css('margin-left', this.position); }; $(document).ready(function() { var game = new Game(); var player1 = new Player(1); var player2 = new Player(2); $(document).on('keyup', function(keyPress){ if(keyPress.keyCode === 80) { player1.move(); player1.updatePosition(); } else if (keyPress.keyCode === 81) { player2.move(); player2.updatePosition(); } }); });
function Game(){ this.$track = $('#racetrack'); this.finishLine = this.$track.width() - 54; } function Player(id){ this.player = $('.player')[id - 1]; this.position = 10; } Player.prototype.move = function(){ this.position += 10; }; Player.prototype.updatePosition = function(){ $player = $(this.player); $player.css('margin-left', this.position); }; $(document).ready(function() { var game = new Game(); var player1 = new Player(1); var player2 = new Player(2); $(document).on('keyup', function(keyPress){ if(keyPress.keyCode === 80) { player1.move(); player1.updatePosition(); } else if (keyPress.keyCode === 81) { player2.move(); player2.updatePosition(); } }); });
Fix unicode for unknown names
from django.contrib.gis.db import models from councils.models import Council class PollingStation(models.Model): council = models.ForeignKey(Council, null=True) internal_council_id = models.CharField(blank=True, max_length=100) postcode = models.CharField(blank=True, null=True, max_length=100) address = models.TextField(blank=True, null=True) location = models.PointField(null=True, blank=True) objects = models.GeoManager() class PollingDistrict(models.Model): name = models.CharField(blank=True, null=True, max_length=255) council = models.ForeignKey(Council, null=True) internal_council_id = models.CharField(blank=True, max_length=100) extra_id = models.CharField(blank=True, null=True, max_length=100) area = models.MultiPolygonField(null=True, blank=True, geography=True) objects = models.GeoManager() def __unicode__(self): name = self.name or "Unnamed" return "%s (%s)" % (name, self.council)
from django.contrib.gis.db import models from councils.models import Council class PollingStation(models.Model): council = models.ForeignKey(Council, null=True) internal_council_id = models.CharField(blank=True, max_length=100) postcode = models.CharField(blank=True, null=True, max_length=100) address = models.TextField(blank=True, null=True) location = models.PointField(null=True, blank=True) objects = models.GeoManager() class PollingDistrict(models.Model): name = models.CharField(blank=True, null=True, max_length=255) council = models.ForeignKey(Council, null=True) internal_council_id = models.CharField(blank=True, max_length=100) extra_id = models.CharField(blank=True, null=True, max_length=100) area = models.MultiPolygonField(null=True, blank=True, geography=True) objects = models.GeoManager() def __unicode__(self): return self.name
Remove useless '.js' in require
var expect = require('chai').expect; var encryption = require('../../../server/utils/encryption'); module.exports = function() { describe('Utils: encryption', function() { describe('#createSalt', function() { it('should return a random salt of 172 char', function() { encryption.createSalt().length.should.equal(172); }); }); describe('#hashPassword', function() { it('should return an hex string of 40 chararacters', function() { var salt = encryption.createSalt(); var hashedPassword = encryption.hashPassword(salt, 'password'); /[^a-f0-9]/.test(hashedPassword).should.equal(false); hashedPassword.length.should.equal(40); }); }); describe('#createToken', function() { it('should return a random hex string of 48 characters', function() { var token = encryption.createToken(); /[^a-f0-9]/.test(token).should.equal(false); token.length.should.equal(48); }); }); }); };
var expect = require('chai').expect; var encryption = require('../../../server/utils/encryption.js'); module.exports = function() { describe('Utils: encryption', function() { describe('#createSalt', function() { it('should return a random salt of 172 char', function() { encryption.createSalt().length.should.equal(172); }); }); describe('#hashPassword', function() { it('should return an hex string of 40 chararacters', function() { var salt = encryption.createSalt(); var hashedPassword = encryption.hashPassword(salt, 'password'); /[^a-f0-9]/.test(hashedPassword).should.equal(false); hashedPassword.length.should.equal(40); }); }); describe('#createToken', function() { it('should return a random hex string of 48 characters', function() { var token = encryption.createToken(); /[^a-f0-9]/.test(token).should.equal(false); token.length.should.equal(48); }); }); }); };
Remove useless code in signal handler example.
# -*- coding: utf-8 -*- from riot.app import quit_app, run_tag from riot.tags.style import parse_style from riot.tags.tags import parse_tag_from_node from riot.tags.utils import convert_string_to_node from riot.virtual_dom import define_tag, mount sig = define_tag('sig', ''' <sig> <filler valign="top"> <pile> <edit caption="What is your name?" class="highlight" id="ask" onchange="{ answer }" /> <div /> <text><span if="{ name }">Nick to meet you, </span><span class="highlight">{ name }</span></text> <div /> <button id="exit" label="Exit" onclick="{ exit }" /> </pile> </filler> <script> import urwid def init(self, opts): import urwid self.name = opts['name'] def answer(self, edit, text): self.name = text </script> </sig> ''') style = ''' .highlight { foreground: default,bold; background: default; mono: bold; } ''' root = convert_string_to_node('<sig></sig>') mount(root, 'sig', 'sig', {'name': 'Default'}) app = parse_tag_from_node(root) run_tag(app, parse_style(style))
# -*- coding: utf-8 -*- from riot.app import quit_app, run_tag from riot.tags.style import parse_style from riot.tags.tags import parse_tag_from_node from riot.tags.utils import convert_string_to_node from riot.virtual_dom import define_tag, mount sig = define_tag('sig', ''' <sig> <filler valign="top"> <pile> <edit caption="What is your name?" class="highlight" id="ask" onchange="{ answer }" /> <div /> <text><span if="{ name }">Nick to meet you, </span><span class="highlight">{ name }</span></text> <div /> <button id="exit" label="Exit" onclick="{ exit }" /> </pile> </filler> <script> import urwid def init(self, opts): import urwid self.name = opts['name'] def answer(self, edit, text): self.update({'name': text}) def exit(self, button): import urwid raise urwid.ExitMainLoop() </script> </sig> ''') style = ''' .highlight { foreground: default,bold; background: default; mono: bold; } ''' root = convert_string_to_node('<sig></sig>') mount(root, 'sig', 'sig', {'name': 'Default'}) app = parse_tag_from_node(root) run_tag(app, parse_style(style))
Add a "forced" NotifySource constant
package signaller import ( "fmt" ) // NotifySource indicates what mechanism triggered the event. type NotifySource int // String provides a printable representation of a NotifySource. func (ns NotifySource) String() string { switch ns { case KNS_FORCED: return "forced" case KNS_TIMER: return "timer" case KNS_ZK: return "zk" default: return fmt.Sprintf("unknown(%d)", ns) } } const ( KNS_FORCED NotifySource = iota // Event was created externally to signaller KNS_TIMER // Event was triggered by a timer KNS_ZK // Event was triggered by Zookeeper ) // Notifications are obtained from the channel returned by Open(). type Notification struct { Source NotifySource // The mechanism that caused the event Appname string // The name of the application that caused the event Data []byte // Optional data associated with the event }
package signaller import ( "fmt" ) // NotifySource indicates what mechanism triggered the event. type NotifySource int // String provides a printable representation of a NotifySource. func (ns NotifySource) String() string { switch ns { case KNS_TIMER: return "timer" case KNS_ZK: return "zk" default: return fmt.Sprintf("unknown(%d)", ns) } } const ( KNS_TIMER NotifySource = iota // Event was triggered by a timer KNS_ZK // Event was triggered by Zookeeper ) // Notifications are obtained from the channel returned by Open(). type Notification struct { Source NotifySource // The mechanism that caused the event Appname string // The name of the application that caused the event Data []byte // Optional data associated with the event }
Make the API not use trailing slashes. This is what Ember expects.
"""lcp URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin from rest_framework import routers from planner.views import SchoolViewSet router = routers.DefaultRouter(trailing_slash=False) router.register('schools', SchoolViewSet) urlpatterns = [ url(r'^', include(router.urls)), url(r'^admin/', admin.site.urls), url(r'^api-auth/', include('rest_framework.urls')), ]
"""lcp URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin from rest_framework import routers from planner.views import SchoolViewSet router = routers.DefaultRouter() router.register('schools', SchoolViewSet) urlpatterns = [ url(r'^', include(router.urls)), url(r'^admin/', admin.site.urls), url(r'^api-auth/', include('rest_framework.urls')), ]
Switch to route based request
(function(window){ window.ajax = function(route, options) { var data = options.data || {}, success = options.success || function(response){}, error = options.error || function(response){}, request = new XMLHttpRequest(); request.open(route.method, route.url, true); request.setRequestHeader("X-Requested-With", "XMLHttpRequest"); request.addEventListener("load", function(evt) { success(JSON.parse(request.responseText), request); }); request.addEventListener("error", function(evt) { error(request); }); if(method === 'POST') { request.send(data); } else { request.send(); } }; })(window);
(function(window){ window.ajax = function(url, options) { var method = options.method || 'GET', data = options.data || {}, success = options.success || function(response){}, error = options.error || function(response){}, request = new XMLHttpRequest(); request.open(method, url, true); request.setRequestHeader("X-Requested-With", "XMLHttpRequest"); request.addEventListener("load", function(evt) { success(JSON.parse(request.responseText), request); }); request.addEventListener("error", function(evt) { error(request); }); if(method === 'POST') { request.send(data); } else { request.send(); } }; })(window);
Add current Directory to repo.
const test = require('tape'); // Load Array.prototype.customMap function require('./exercises/map/map'); // Load Array.prototype.customFilter function require('./exercises/filter/filter'); // Load Array.prototype.concatAll function. require('./exercises/concatAll/concatAll'); // Load Array.prototype.concatMap function. require('./exercises/concatMap/concatMap'); test('Practice the concept of unit testing with simple tape library', function(nest) { // TODO: Make unit test pass with actual and expected assertion. nest.test('Unit test the map function', assert => { assert.equal(actual, expected, `should render default message`); assert.end(); }); // TODO: Unit test filter function nest.test('Unit test the filter function', assert => { }); // TODO: Unit test concatAll function // TODO: Unit test concatMap function });
const test = require('tape'); // Load Array.prototype.customMap function require('../exercises/map/map'); // Load Array.prototype.customFilter function require('../exercises/filter/filter'); // Load Array.prototype.concatAll function. require('../exercises/concatAll/concatAll'); // Load Array.prototype.concatMap function. require('../exercises/concatMap/concatMap'); test('Practice the concept of unit testing with simple tape library', function(nest) { // TODO: Make unit test pass with actual and expected assertion. nest.test('Unit test the map function', assert => { assert.equal(actual, expected, `should render default message`); assert.end(); }); // TODO: Unit test filter function nest.test('Unit test the filter function', assert => { }); // TODO: Unit test concatAll function // TODO: Unit test concatMap function });
Fix getClient bugs found by smoketest
# # Copyright (c) 2008 rPath, Inc. # # This program is distributed under the terms of the Common Public License, # version 1.0. A copy of this license should have been distributed with this # source file in a file called LICENSE. If it is not present, the license # is always available at http://www.rpath.com/permanent/licenses/CPL-1.0. # # This program is distributed in the hope that it will be useful, but # without any warranty; without even the implied warranty of merchantability # or fitness for a particular purpose. See the Common Public License for # full details. # """ The rBuild Appliance Developer Process Toolkit client object The C{client} module provides the core objects used for consuming rBuild as a Python API. Instances of C{rBuildClient} are the handles used as the core API item by which consumers of the python API call the plugins that implement rBuild functionality, and by which plugins communicate with each other. """ from rbuild import rbuildcfg from rbuild.internal import pluginloader class rBuildClient(object): def __init__(self, pluginMgr, cfg): self.cfg = cfg self.pluginMgr = pluginMgr for plugin in pluginMgr.plugins: setattr(self, plugin.__class__.__name__, plugin) def getClient(disabledPlugins=None, root=None): cfg = rbuildcfg.rBuildConfiguration(readConfigFiles=True, ignoreErrors=True, root=root) plugins = pluginloader.getPlugins([], cfg.pluginDirs, disabledPlugins) return rBuildClient(plugins, cfg)
# # Copyright (c) 2008 rPath, Inc. # # This program is distributed under the terms of the Common Public License, # version 1.0. A copy of this license should have been distributed with this # source file in a file called LICENSE. If it is not present, the license # is always available at http://www.rpath.com/permanent/licenses/CPL-1.0. # # This program is distributed in the hope that it will be useful, but # without any warranty; without even the implied warranty of merchantability # or fitness for a particular purpose. See the Common Public License for # full details. # """ The rBuild Appliance Developer Process Toolkit client object The C{client} module provides the core objects used for consuming rBuild as a Python API. Instances of C{rBuildClient} are the handles used as the core API item by which consumers of the python API call the plugins that implement rBuild functionality, and by which plugins communicate with each other. """ class rBuildClient(object): def __init__(self, pluginMgr, cfg): self.cfg = cfg self.pluginMgr = pluginMgr for plugin in pluginMgr.plugins: setattr(self, plugin.__class__.__name__, plugin) def getClient(disabledPlugins=None): cfg = rbuild.rBuildConfiguration(ignoreErrors=True) plugins = pluginloader.getPlugins(cfg, disabledPlugins) return rbuildClient(cfg, plugins)
Add "include_initial" kwarg to support tailing stack updates `get_events` will return all events that have occurred for a stack. This is useless if we're tailing an update to a stack.
import time def _tail_print(e): print("%s %s %s" % (e.resource_status, e.resource_type, e.event_id)) def get_events(conn, stackname): """Get the events in batches and return in chronological order""" next = None event_list = [] while 1: events = conn.describe_stack_events(stackname, next) event_list.append(events) if events.next_token is None: break next = events.next_token time.sleep(1) return reversed(sum(event_list, [])) def tail(conn, stack_name, log_func=_tail_print, sleep_time=5, include_initial=True): """Show and then tail the event log""" # First dump the full list of events in chronological order and keep # track of the events we've seen already seen = set() initial_events = get_events(conn, stack_name) for e in initial_events: if include_initial: log_func(e) seen.add(e.event_id) # Now keep looping through and dump the new events while 1: events = get_events(conn, stack_name) for e in events: if e.event_id not in seen: log_func(e) seen.add(e.event_id) time.sleep(sleep_time)
import time def _tail_print(e): print("%s %s %s" % (e.resource_status, e.resource_type, e.event_id)) def get_events(conn, stackname): """Get the events in batches and return in chronological order""" next = None event_list = [] while 1: events = conn.describe_stack_events(stackname, next) event_list.append(events) if events.next_token is None: break next = events.next_token time.sleep(1) return reversed(sum(event_list, [])) def tail(conn, stack_name, log_func=_tail_print, sleep_time=5): """Show and then tail the event log""" # First dump the full list of events in chronological order and keep # track of the events we've seen already seen = set() initial_events = get_events(conn, stack_name) for e in initial_events: log_func(e) seen.add(e.event_id) # Now keep looping through and dump the new events while 1: events = get_events(conn, stack_name) for e in events: if e.event_id not in seen: log_func(e) seen.add(e.event_id) time.sleep(sleep_time)
Change http back to https
var server = io.connect('https://'+window.location.host); $('#name').on('submit', function(e){ e.preventDefault(); $(this).hide(); $('#chat_form').show(); var name = $('#name_input').val() server.emit('join', name) $('#status').text('Status: Connected to chat') }); $('#chat_form').on('submit', function(e){ e.preventDefault(); var message = $('#chat_input').val(); server.emit('messages', message); }); server.on('messages', function(data){ insertMessage(data); }) server.on('addUser', function(name){ insertUser(name) }) server.on('removeUser', function(name){ $('#'+name).remove() insertLeaveMessage(name) }) function insertMessage(data) { $('#chatbox').append('<p class="messages">'+data.name+data.message+'</p>') if ($('#chatbox').children().length > 11){ $($('#chatbox').children()[3]).remove() } $('#chat_form #chat_input').val('') } function insertLeaveMessage(data) { $('#chatbox').append('<p class="messages">'+data+' has left the chat</p>') } function insertUser(data){ $('#current_users').append('<p id='+data+'>'+data+'</p>') }
var server = io.connect('http://'+window.location.host); $('#name').on('submit', function(e){ e.preventDefault(); $(this).hide(); $('#chat_form').show(); var name = $('#name_input').val() server.emit('join', name) $('#status').text('Status: Connected to chat') }); $('#chat_form').on('submit', function(e){ e.preventDefault(); var message = $('#chat_input').val(); server.emit('messages', message); }); server.on('messages', function(data){ insertMessage(data); }) server.on('addUser', function(name){ insertUser(name) }) server.on('removeUser', function(name){ $('#'+name).remove() insertLeaveMessage(name) }) function insertMessage(data) { $('#chatbox').append('<p class="messages">'+data.name+data.message+'</p>') if ($('#chatbox').children().length > 11){ $($('#chatbox').children()[3]).remove() } $('#chat_form #chat_input').val('') } function insertLeaveMessage(data) { $('#chatbox').append('<p class="messages">'+data+' has left the chat</p>') } function insertUser(data){ $('#current_users').append('<p id='+data+'>'+data+'</p>') }
Remove redundant modifiers for interface fields
package net.elprespufferfish.rssreader; import android.provider.BaseColumns; public class DatabaseSchema { public interface FeedTable extends BaseColumns { String TABLE_NAME = "feeds"; String FEED_NAME = "feed_name"; String FEED_URL = "feed_url"; } public interface ArticleTable extends BaseColumns { String TABLE_NAME = "articles"; String ARTICLE_FEED = "article_feed"; String ARTICLE_NAME = "article_name"; String ARTICLE_URL = "article_url"; String ARTICLE_PUBLICATION_DATE = "article_pubdate"; String ARTICLE_DESCRIPTION = "article_description"; String ARTICLE_GUID = "article_guid"; String ARTICLE_IS_READ = "article_is_read"; } private DatabaseSchema() { // prevent instantiations } }
package net.elprespufferfish.rssreader; import android.provider.BaseColumns; public class DatabaseSchema { public static interface FeedTable extends BaseColumns { public static final String TABLE_NAME = "feeds"; public static final String FEED_NAME = "feed_name"; public static final String FEED_URL = "feed_url"; } public static interface ArticleTable extends BaseColumns { public static final String TABLE_NAME = "articles"; public static final String ARTICLE_FEED = "article_feed"; public static final String ARTICLE_NAME = "article_name"; public static final String ARTICLE_URL = "article_url"; public static final String ARTICLE_PUBLICATION_DATE = "article_pubdate"; public static final String ARTICLE_DESCRIPTION = "article_description"; public static final String ARTICLE_GUID = "article_guid"; public static final String ARTICLE_IS_READ = "article_is_read"; } private DatabaseSchema() { // prevent instantiations } }
Add save method to temp db serv
const db = function () { let localData = JSON.parse(localStorage.getItem("data")); return localData || { index: 0 }; }; const save = function (data) { localStorage.setItem("data", JSON.stringify(data)); }; let server = { add(item) { const data = db(); data.index++; item.id = data.index; data[data.index] = item; save(data); return data; }, update(item) { const id = item.id; const data = db(); data[id] = item; save(data); return data; }, delete(id) { const data = db(); delete data[id]; save(data); return data; }, getData() { return db(); } }; export default server;
const db = function () { let localData = JSON.parse(localStorage.getItem("data")); return localData || { index: 0 }; }; let server = { add(item) { const data = db(); data.index++; debugger; item.id = data.index; data[data.index] = item; localStorage.setItem("data", JSON.stringify(data)); return data; }, update(item) { const id = item.id; const data = db(); data[id] = item; localStorage.setItem("data", JSON.stringify(data)); return data; }, delete(id) { const data = db(); delete data[id]; localStorage.setItem("data", JSON.stringify(data)); return data; }, getData(){ return db(); } }; export default server;
Enable tests for Safari 9
var argv = require('yargs').argv; module.exports = { plugins: { 'random-output': true }, registerHooks: function(context) { var saucelabsPlatforms = [ 'macOS 10.12/iphone@10.3', 'macOS 10.12/ipad@10.3', 'Windows 10/microsoftedge@15', 'Windows 10/internet explorer@11', 'macOS 10.12/safari@11.0', 'macOS 9.3.2/iphone@9.3' ]; var cronPlatforms = [ 'Android/chrome', 'Windows 10/chrome@59', 'Windows 10/firefox@54' ]; if (argv.env === 'saucelabs') { context.options.plugins.sauce.browsers = saucelabsPlatforms; } else if (argv.env === 'saucelabs-cron') { context.options.plugins.sauce.browsers = cronPlatforms; } } };
var argv = require('yargs').argv; module.exports = { plugins: { 'random-output': true }, registerHooks: function(context) { var saucelabsPlatforms = [ 'macOS 10.12/iphone@10.3', 'macOS 10.12/ipad@10.3', 'Windows 10/microsoftedge@15', 'Windows 10/internet explorer@11', 'macOS 10.12/safari@11.0' ]; var cronPlatforms = [ 'Android/chrome', 'Windows 10/chrome@59', 'Windows 10/firefox@54' ]; if (argv.env === 'saucelabs') { context.options.plugins.sauce.browsers = saucelabsPlatforms; } else if (argv.env === 'saucelabs-cron') { context.options.plugins.sauce.browsers = cronPlatforms; } } };
Add actual error message to log
<?php namespace Busuu\IosReceiptsApi; use GuzzleHttp\Client; class AppleClient { /** @var Client $client */ private $client; /** @var string */ private $password; public function __construct($password) { $this->client = new Client(); $this->password = $password; } /** * Fetch the receipt from apple * * @param $receiptData * @param $endpoint * @return array */ public function fetchReceipt($receiptData, $endpoint) { try { $data = [ 'password' => $this->password, 'receipt-data' => $receiptData ]; $response = $this->client->post($endpoint, ['body' => json_encode($data)]); return json_decode($response->getBody(), true); } catch (\Exception $e) { throw new \InvalidArgumentException( sprintf('Error in the communication with Apple - %s', $e->getMessage()) ); } } }
<?php namespace Busuu\IosReceiptsApi; use GuzzleHttp\Client; class AppleClient { /** @var Client $client */ private $client; /** @var string */ private $password; public function __construct($password) { $this->client = new Client(); $this->password = $password; } /** * Fetch the receipt from apple * * @param $receiptData * @param $endpoint * @return array */ public function fetchReceipt($receiptData, $endpoint) { try { $data = [ 'password' => $this->password, 'receipt-data' => $receiptData ]; $response = $this->client->post($endpoint, ['body' => json_encode($data)]); return json_decode($response->getBody(), true); } catch (\Exception $e) { throw new \InvalidArgumentException('Error in the communication with Apple'); } } }
[FrameworkBundle] Fix ClassCacheWarme when classes.php is already warmed
<?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\Bundle\FrameworkBundle\CacheWarmer; use Symfony\Component\ClassLoader\ClassCollectionLoader; use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface; /** * Generates the Class Cache (classes.php) file. * * @author Tugdual Saunier <tucksaun@gmail.com> */ class ClassCacheCacheWarmer implements CacheWarmerInterface { /** * Warms up the cache. * * @param string $cacheDir The cache directory */ public function warmUp($cacheDir) { $classmap = $cacheDir.'/classes.map'; if (!is_file($classmap)) { return; } if (file_exists($cacheDir.'/classes.php')) { return; } ClassCollectionLoader::load(include($classmap), $cacheDir, 'classes', false); } /** * Checks whether this warmer is optional or not. * * @return bool always true */ public function isOptional() { return true; } }
<?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\Bundle\FrameworkBundle\CacheWarmer; use Symfony\Component\ClassLoader\ClassCollectionLoader; use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface; /** * Generates the Class Cache (classes.php) file. * * @author Tugdual Saunier <tucksaun@gmail.com> */ class ClassCacheCacheWarmer implements CacheWarmerInterface { /** * Warms up the cache. * * @param string $cacheDir The cache directory */ public function warmUp($cacheDir) { $classmap = $cacheDir.'/classes.map'; if (!is_file($classmap)) { return; } ClassCollectionLoader::load(include($classmap), $cacheDir, 'classes', false); } /** * Checks whether this warmer is optional or not. * * @return bool always true */ public function isOptional() { return true; } }
Rewrite as a pitching loader, adding support for webpack v2 exports['default']
var loaderUtils = require("loader-utils"); module.exports = function() {} module.exports.pitch = function applyLoader(remainingRequest) { var query = loaderUtils.parseQuery(this.query); var args = []; this.cacheable && this.cacheable(); // apply?config=key => sourceFn(require('webpack.config').key) if (typeof query.config === "string") { if (!(query.config in this.options)) throw new Error("apply-loader: '"+query.config+"' property not present in webpack config"); args.push(this.options[query.config]); } // apply?{obj: {a: 1, b: 2}} => sourceFn({a: 1, b:2}) if (query.obj) { args.push(query.obj); } // apply?args[]=1&args[]=2 => sourceFn(1, 2) if (Array.isArray(query.args)) { args.push.apply(args, query.args); } return [ "var req = require(", JSON.stringify("!!" + remainingRequest), ");\n", "module.exports = (req['default'] || req).apply(req, ", JSON.stringify(args), ")" ].join("") };
var loaderUtils = require('loader-utils'); module.exports = function applyLoader(source) { var query = loaderUtils.parseQuery(this.query); var args = []; this.cacheable && this.cacheable(); // apply?config=key => sourceFn(require('webpack.config').key) if (typeof query.config === 'string') { if (!(query.config in this.options)) throw new Error("apply-loader: '"+query.config+"' property not present in webpack config"); args.push(this.options[query.config]); } // apply?{obj: {a: 1, b: 2}} => sourceFn({a: 1, b:2}) if (query.obj) { args.push(query.obj); } // apply?args[]=1&args[]=2 => sourceFn(1, 2) if (Array.isArray(query.args)) { args.push.apply(args, query.args); } var json = JSON.stringify(args); source += "\n\nmodule.exports = module.exports.apply(module, " + json + ")"; return source; };
Use array spread operator in replace method
import Em from 'ember'; import { ArrayController } from 'ember-legacy-controllers'; var get = Em.get; var copy = Em.copy; var ArrayPauser = ArrayController.extend({ isPaused: false, buffer: Em.computed(function () { return Em.A(); }), addToBuffer: function (idx, removedCount, added) { var buffer = get(this, 'buffer'); buffer.pushObject([idx, removedCount, added]); }, clearBuffer: Em.observer('isPaused', function () { var buffer = get(this, 'buffer'); var arrangedContent = get(this, 'arrangedContent'); buffer.forEach((args) => { arrangedContent.replace(...args); }); buffer.clear(); }), arrangedContent: Em.computed('content', function () { var content = get(this, 'content'); var clone = copy(content); return clone; }), contentArrayDidChange: function (arr, idx, removedCount, addedCount) { var added = arr.slice(idx, idx + addedCount); var isPaused = get(this, 'isPaused'); var arrangedContent; if (isPaused) { this.addToBuffer(idx, removedCount, added); } else { arrangedContent = get(this, 'arrangedContent'); arrangedContent.replace(idx, removedCount, added); } } }); export default ArrayPauser;
import Em from 'ember'; import { ArrayController } from 'ember-legacy-controllers'; var get = Em.get; var copy = Em.copy; var ArrayPauser = ArrayController.extend({ isPaused: false, buffer: Em.computed(function () { return Em.A(); }), addToBuffer: function (idx, removedCount, added) { var buffer = get(this, 'buffer'); buffer.pushObject([idx, removedCount, added]); }, clearBuffer: Em.observer('isPaused', function () { var buffer = get(this, 'buffer'); var arrangedContent = get(this, 'arrangedContent'); buffer.forEach(function ([idx, removedCount, added]) { arrangedContent.replace(idx, removedCount, added); }); buffer.clear(); }), arrangedContent: Em.computed('content', function () { var content = get(this, 'content'); var clone = copy(content); return clone; }), contentArrayDidChange: function (arr, idx, removedCount, addedCount) { var added = arr.slice(idx, idx + addedCount); var isPaused = get(this, 'isPaused'); var arrangedContent; if (isPaused) { this.addToBuffer(idx, removedCount, added); } else { arrangedContent = get(this, 'arrangedContent'); arrangedContent.replace(idx, removedCount, added); } } }); export default ArrayPauser;
Remove filter for pdf/epub/mobi files when outputting
var Promise = require('../utils/promise'); var IGNORE_FILES = require('../constants/ignoreFiles'); /** Parse ignore files @param {Book} @return {Book} */ function parseIgnore(book) { if (book.isLanguageBook()) { return Promise.reject(new Error('Ignore files could be parsed for language books')); } var fs = book.getFS(); var ignore = book.getIgnore(); ignore.addPattern([ // Skip Git stuff '.git/', // Skip OS X meta data '.DS_Store', // Skip stuff installed by plugins 'node_modules', // Skip book outputs '_book', // Ignore files in the templates folder '_layouts' ]); return Promise.serie(IGNORE_FILES, function(filename) { return fs.readAsString(filename) .then(function(content) { ignore.addPattern(content.toString().split(/\r?\n/)); }, function(err) { return Promise(); }); }) .thenResolve(book); } module.exports = parseIgnore;
var Promise = require('../utils/promise'); var IGNORE_FILES = require('../constants/ignoreFiles'); /** Parse ignore files @param {Book} @return {Book} */ function parseIgnore(book) { if (book.isLanguageBook()) { return Promise.reject(new Error('Ignore files could be parsed for language books')); } var fs = book.getFS(); var ignore = book.getIgnore(); ignore.addPattern([ // Skip Git stuff '.git/', // Skip OS X meta data '.DS_Store', // Skip stuff installed by plugins 'node_modules', // Skip book outputs '_book', '*.pdf', '*.epub', '*.mobi', // Ignore files in the templates folder '_layouts' ]); return Promise.serie(IGNORE_FILES, function(filename) { return fs.readAsString(filename) .then(function(content) { ignore.addPattern(content.toString().split(/\r?\n/)); }, function(err) { return Promise(); }); }) .thenResolve(book); } module.exports = parseIgnore;
Remove myself from the HTTPie team
""" Generate snippets to copy-paste. """ import sys from jinja2 import Template from fetch import HERE, load_awesome_people TPL_FILE = HERE / 'snippet.jinja2' HTTPIE_TEAM = { 'claudiatd', 'jakubroztocil', 'jkbr', } def generate_snippets(release: str) -> str: people = load_awesome_people() contributors = { name: details for name, details in people.items() if details['github'] not in HTTPIE_TEAM and (release in details['committed'] or release in details['reported']) } template = Template(source=TPL_FILE.read_text(encoding='utf-8')) output = template.render(contributors=contributors, release=release) print(output) return 0 if __name__ == '__main__': ret = 1 try: ret = generate_snippets(sys.argv[1]) except (IndexError, TypeError): ret = 2 print(f''' Generate snippets for contributors to a release. Usage: python {sys.argv[0]} {sys.argv[0]} <RELEASE> ''') sys.exit(ret)
""" Generate snippets to copy-paste. """ import sys from jinja2 import Template from fetch import HERE, load_awesome_people TPL_FILE = HERE / 'snippet.jinja2' HTTPIE_TEAM = { 'BoboTiG', 'claudiatd', 'jakubroztocil', 'jkbr', } def generate_snippets(release: str) -> str: people = load_awesome_people() contributors = { name: details for name, details in people.items() if details['github'] not in HTTPIE_TEAM and (release in details['committed'] or release in details['reported']) } template = Template(source=TPL_FILE.read_text(encoding='utf-8')) output = template.render(contributors=contributors, release=release) print(output) return 0 if __name__ == '__main__': ret = 1 try: ret = generate_snippets(sys.argv[1]) except (IndexError, TypeError): ret = 2 print(f''' Generate snippets for contributors to a release. Usage: python {sys.argv[0]} {sys.argv[0]} <RELEASE> ''') sys.exit(ret)
Use wss on https pages
(function () { 'use strict'; /*global ab: false, RealtimeUpdate: false */ window.wsRealtime = { init: function (server, port, timeline) { var protocol = (document.location.protocol === 'https:') ? 'wss' : 'ws', conn = new ab.Session( protocol + '://' + server + ':' + port, function () { // Connect conn.subscribe(timeline, function (undefined, data) { RealtimeUpdate.receive(data); }); }, function () { // Connection closed console.warn('WebSocket connection closed'); }, { // Additional parameters, we're ignoring the WAMP sub-protocol for older browsers 'skipSubprotocolCheck': true } ); } }; }());
(function () { 'use strict'; /*global ab: false, RealtimeUpdate: false */ window.wsRealtime = { init: function (server, port, timeline) { var conn = new ab.Session( 'ws://' + server + ':' + port, function () { // Connect conn.subscribe(timeline, function (undefined, data) { RealtimeUpdate.receive(data); }); }, function () { // Connection closed console.warn('WebSocket connection closed'); }, { // Additional parameters, we're ignoring the WAMP sub-protocol for older browsers 'skipSubprotocolCheck': true } ); } }; }());
Increase the timeout for the logspew test It seems that changing the Nora to only have 1g of memory might be causing this endpoint to be slower than the 45s timeout we had previously Signed-off-by: David Morhovich <1d2e5394c2c3adc275fab845f5e23fc4a9634ec0@pivotal.io>
package wats import ( "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" . "github.com/onsi/gomega/gexec" "github.com/cloudfoundry-incubator/cf-test-helpers/cf" "github.com/cloudfoundry-incubator/cf-test-helpers/helpers" ) var _ = Describe("An application printing a bunch of output", func() { BeforeEach(func() { Eventually(pushNora(appName), CF_PUSH_TIMEOUT).Should(Succeed()) enableDiego(appName) Eventually(runCf("start", appName), CF_PUSH_TIMEOUT).Should(Succeed()) }) AfterEach(func() { Eventually(cf.Cf("logs", appName, "--recent")).Should(Exit()) Eventually(cf.Cf("delete", appName, "-f")).Should(Exit(0)) }) It("doesn't die when printing 32MB", func() { beforeId := helpers.CurlApp(appName, "/id") loggingTimeout := 2 * time.Minute Expect(helpers.CurlAppWithTimeout(appName, "/logspew/32000", loggingTimeout)). To(ContainSubstring("Just wrote 32000 kbytes to the log")) Consistently(func() string { return helpers.CurlApp(appName, "/id") }, "10s").Should(Equal(beforeId)) }) })
package wats import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" . "github.com/onsi/gomega/gexec" "github.com/cloudfoundry-incubator/cf-test-helpers/cf" "github.com/cloudfoundry-incubator/cf-test-helpers/helpers" ) var _ = Describe("An application printing a bunch of output", func() { BeforeEach(func() { Eventually(pushNora(appName), CF_PUSH_TIMEOUT).Should(Succeed()) enableDiego(appName) Eventually(runCf("start", appName), CF_PUSH_TIMEOUT).Should(Succeed()) }) AfterEach(func() { Eventually(cf.Cf("logs", appName, "--recent")).Should(Exit()) Eventually(cf.Cf("delete", appName, "-f")).Should(Exit(0)) }) It("doesn't die when printing 32MB", func() { beforeId := helpers.CurlApp(appName, "/id") Expect(helpers.CurlAppWithTimeout(appName, "/logspew/32000", DEFAULT_TIMEOUT)). To(ContainSubstring("Just wrote 32000 kbytes to the log")) Consistently(func() string { return helpers.CurlApp(appName, "/id") }, "10s").Should(Equal(beforeId)) }) })
Add posibility to run only worker for debug
var worker = function() { var config = require('./config'); var express = require('express'); var app = express(); var http = require('http'); var server = http.createServer(app); var bootstrap = require('./app/bootstrap.js'); bootstrap.setupApp(app, __dirname); bootstrap.bootstrap(app); bootstrap.postrun(); server.listen(config.http.port, config.http.host); }; /* run only one single process and worker for debug */ if('worker' in process.env) { worker(); } else { var pstarter = require('pstarter'); pstarter.startMaster(__dirname + '/config', {}, function() { var config = require('./config'); pstarter.statServer(config.http.statPort, config.http.statHost); if(process.env['NODE_ENV'] && process.env['NODE_ENV'] === 'development') { pstarter.startWatch(__dirname, [__dirname + '/node_modules'], ['.js', '.json', '.html', '.css']); } }).startWorker(function() { worker(); /* Counting request */ server.on('request', function(req, res) { process.send({ cmd : pstarter.cmd.requestCount }); }); }); }
var pstarter = require('pstarter'); pstarter.startMaster(__dirname + '/config', {}, function() { var config = require('./config'); pstarter.statServer(config.http.statPort, config.http.statHost); if (process.env['NODE_ENV'] && process.env['NODE_ENV'] === 'development') { pstarter.startWatch(__dirname, [__dirname +'/node_modules'], ['.js', '.json', '.html', '.css']); } }).startWorker(function() { var config = require('./config'); var express = require('express'); var app = express(); var http = require('http'); var server = http.createServer(app); var bootstrap = require('./app/bootstrap.js'); bootstrap.setupApp(app, __dirname); bootstrap.bootstrap(app); bootstrap.postrun(); server.listen(config.http.port, config.http.host); /* Counting request */ server.on('request', function(req, res) { process.send({ cmd : pstarter.cmd.requestCount }); }); });
Bump version in preparation for release. Beta status
#!/usr/bin/env python import sys from setuptools import setup VERSION = '0.2.1' install_requires = [] if sys.version_info < (2, 7): install_requires.append('argparse') try: from pypandoc import convert read_md = lambda f: convert(f, 'rst') except ImportError: print("Warning: pypandoc module not found, could not convert Markdown to RST") read_md = lambda f: open(f, 'r').read() setup(name='bureaucrat', version=VERSION, author="Andrew Cutler", author_email="andrew@adlibre.com.au", description="Procfile and Deployfile process manager for virtual environments", license="BSD", long_description=read_md('README.md'), url='https://github.com/adlibre/python-bureaucrat', download_url='https://github.com/adlibre/python-bureaucrat/archive/v%s.tar.gz' % VERSION, classifiers=[ "Development Status :: 4 - Beta", "Environment :: Console", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: Unix", "Programming Language :: Python", "Topic :: Utilities", ], scripts=['bureaucrat'], install_requires=install_requires, )
#!/usr/bin/env python import sys from setuptools import setup VERSION = '0.2.0' install_requires = [] if sys.version_info < (2, 7): install_requires.append('argparse') try: from pypandoc import convert read_md = lambda f: convert(f, 'rst') except ImportError: print("Warning: pypandoc module not found, could not convert Markdown to RST") read_md = lambda f: open(f, 'r').read() setup(name='bureaucrat', version=VERSION, author="Andrew Cutler", author_email="andrew@adlibre.com.au", description="Procfile and Deployfile process manager for virtual environments", license="BSD", long_description=read_md('README.md'), url='https://github.com/adlibre/python-bureaucrat', download_url='https://github.com/adlibre/python-bureaucrat/archive/v%s.tar.gz' % VERSION, classifiers=[ "Development Status :: 3 - Alpha", "Environment :: Console", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: Unix", "Programming Language :: Python", "Topic :: Utilities", ], scripts=['bureaucrat'], install_requires=install_requires, )
Exclude docbook converter from webpack
/*--------------------------------------------------------------------------------------------- * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; const path = require('path'); module.exports = { target: 'node', entry: './src/extension.ts', output: { path: path.resolve(__dirname, 'dist'), filename: 'extension.js', libraryTarget: 'commonjs2', devtoolModuleFilenameTemplate: '../[resource-path]', }, devtool: 'source-map', externals: { vscode: 'commonjs vscode', // the vscode-module is created on-the-fly and must be excluded. 'asciidoctor-opal-runtime': 'asciidoctor-opal-runtime', '@asciidoctor/core': '@asciidoctor/core', '@asciidoctor/docbook-converter': '@asciidoctor/docbook-converter', }, resolve: { extensions: ['.tsx', '.ts', '.js'], }, module: { rules: [ { test: /\.tsx?$/, use: 'ts-loader', exclude: /node_modules/, }, ], }, };
/*--------------------------------------------------------------------------------------------- * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; const path = require('path'); module.exports = { target: 'node', entry: './src/extension.ts', output: { path: path.resolve(__dirname, 'dist'), filename: 'extension.js', libraryTarget: 'commonjs2', devtoolModuleFilenameTemplate: '../[resource-path]', }, devtool: 'source-map', externals: { vscode: 'commonjs vscode', // the vscode-module is created on-the-fly and must be excluded. 'asciidoctor-opal-runtime': 'asciidoctor-opal-runtime', '@asciidoctor/core': '@asciidoctor/core', }, resolve: { extensions: ['.tsx', '.ts', '.js'], }, module: { rules: [ { test: /\.tsx?$/, use: 'ts-loader', exclude: /node_modules/, }, ], }, };
Convert CompareTree Query into an ES6 class Related issues: https://github.com/vigetlabs/microcosm/issues/305
import Emitter from '../emitter' import { get } from '../utils' import { getKeyPaths, getKeyStrings } from '../key-path' /** * @fileoverview Leaf nodes of the comparison tree are queries. A * grouping of data subscriptions. */ class Query extends Emitter { static getId(keyPaths) { return 'query:' + getKeyStrings(getKeyPaths(keyPaths)) } constructor(id, keys) { super() this.id = id this.keyPaths = getKeyPaths(keys) } extract(state) { let length = this.keyPaths.length let values = Array(length) for (var i = 0; i < length; i++) { values[i] = get(state, this.keyPaths[i]) } return values } trigger(state) { let values = this.extract(state) this._emit('change', ...values) } isAlone() { return this._events.length <= 0 } } export default Query
import Emitter from '../emitter' import { get, inherit } from '../utils' import { getKeyPaths, getKeyStrings } from '../key-path' export default function Query(id, keys) { Emitter.call(this) this.id = id this.keyPaths = getKeyPaths(keys) } Query.getId = function(keyPaths) { return 'query:' + getKeyStrings(getKeyPaths(keyPaths)) } inherit(Query, Emitter, { extract(state) { let length = this.keyPaths.length let values = Array(length) for (var i = 0; i < length; i++) { values[i] = get(state, this.keyPaths[i]) } return values }, trigger(state) { let values = this.extract(state) this._emit('change', ...values) }, isAlone() { return this._events.length <= 0 } })
Fix walkSync filter from recursing into node_modules
'use strict'; var walkSync = require('walk-sync'); var execFile = require("child_process").execFile; var nodeTestFiles = walkSync('.', { globs: ['{lib,blueprints,tests}/**/*.js'] }) .filter(function(file) { return /.js$/.test(file); }) .filter(function(file) { return !/node_modules|tmp/.test(file); }) .filter(function(file) { return !/tests\/fixtures\//.test(file); }); describe('jscs', function () { nodeTestFiles.forEach(function(path) { it("should pass for " + path, function (done) { var error = new Error(''); execFile( require.resolve('jscs/bin/jscs'), [path, '--verbose', '--config', '.repo-jscsrc'], onProcessFinished ); function onProcessFinished (_, stdout) { if (_) { error.stack = stdout; throw error; } else { done(); } } }); }); });
'use strict'; var walkSync = require('walk-sync'); var execFile = require("child_process").execFile; var nodeTestFiles = walkSync('.') .filter(function(file) { return /.js$/.test(file); }) .filter(function(file) { return !/node_modules|tmp/.test(file); }) .filter(function(file) { return !/tests\/fixtures\//.test(file); }); describe('jscs', function () { nodeTestFiles.forEach(function(path) { it("should pass for " + path, function (done) { var error = new Error(''); execFile( require.resolve('jscs/bin/jscs'), [path, '--verbose', '--config', '.repo-jscsrc'], onProcessFinished ); function onProcessFinished (_, stdout) { if (_) { error.stack = stdout; throw error; } else { done(); } } }); }); });
Fix bug when it crashes on non existent ids. Refactor
function setReadmore (text, btn, more, less) { if (!text || !btn) { return } more = more || 'Read more' less = less || 'Hide' btn.innerHTML = more btn.onclick = function () { if (text.style.display === 'none') { text.style.display = 'inline' btn.innerHTML = less } else { text.style.display = 'none' btn.innerHTML = more } } } [ 'olga', 'yana', 'ermolaeva', 'stepina' ].forEach(function (name) { const text = document.getElementById(name + '_readmore') const btn = document.getElementById(name + '_readmore_btn') setReadmore(text, btn, 'Leggi tutto', 'Meno') })
set_readmore( document.getElementById('olga_readmore'), document.getElementById('olga_readmore_btn'), 'Leggi tutto', 'Meno' ) set_readmore( document.getElementById('yana_readmore'), document.getElementById('yana_readmore_btn'), 'Leggi tutto', 'Meno' ) set_readmore( document.getElementById('shkapa_readmore'), document.getElementById('shkapa_readmore_btn'), 'Leggi tutto', 'Meno' ) set_readmore( document.getElementById('surikova_readmore'), document.getElementById('surikova_readmore_btn'), 'Leggi tutto', 'Meno' ) set_readmore( document.getElementById('ermolaeva_readmore'), document.getElementById('ermolaeva_readmore_btn'), 'Leggi tutto', 'Meno' ) set_readmore( document.getElementById('stepina_readmore'), document.getElementById('stepina_readmore_btn'), 'Leggi tutto', 'Meno' ) function set_readmore (text, btn, more, less) { more = more || 'Read more' less = less || 'Hide' btn.innerHTML = more btn.onclick = function () { if (text.style.display === 'none') { text.style.display = 'inline' btn.innerHTML = less } else { text.style.display = 'none' btn.innerHTML = more } } }
Fix failing tests by injecting an empty koji module.
#!/usr/bin/python # -*- coding: utf-8 -*- """ Tests for koji_sign module. """ import unittest import os import sys # HACK: inject empty koji module to silence failing tests. # We need to add koji to deps (currently not possible) # or create a mock object for testing. import imp sys.modules["koji"] = imp.new_module("koji") DIR = os.path.dirname(__file__) sys.path.insert(0, os.path.join(DIR, "..")) from releng_sop.common import Environment # noqa: E402 from releng_sop.koji_sign import get_rpmsign_class, LocalRPMSign # noqa: E402 RELEASES_DIR = os.path.join(DIR, "releases") ENVIRONMENTS_DIR = os.path.join(DIR, "environments") class TestRPMSignClass(unittest.TestCase): """ Tests related to RPMSign classes. """ longMessage = True def test_get_rpmsign_class(self): """Test if a RPMSign class can be properly loaded based on env settings.""" env = Environment("test-env", config_dirs=[ENVIRONMENTS_DIR]) cls = get_rpmsign_class(env) self.assertEqual(cls, LocalRPMSign) if __name__ == "__main__": unittest.main()
#!/usr/bin/python # -*- coding: utf-8 -*- """ Tests for koji_sign module. """ import unittest import os import sys DIR = os.path.dirname(__file__) sys.path.insert(0, os.path.join(DIR, "..")) from releng_sop.common import Environment # noqa: E402 from releng_sop.koji_sign import get_rpmsign_class, LocalRPMSign # noqa: E402 RELEASES_DIR = os.path.join(DIR, "releases") ENVIRONMENTS_DIR = os.path.join(DIR, "environments") class TestRPMSignClass(unittest.TestCase): """ Tests related to RPMSign classes. """ longMessage = True def test_get_rpmsign_class(self): """Test if a RPMSign class can be properly loaded based on env settings.""" env = Environment("test-env", config_dirs=[ENVIRONMENTS_DIR]) cls = get_rpmsign_class(env) self.assertEqual(cls, LocalRPMSign) if __name__ == "__main__": unittest.main()
Check if title should be updated This change prevents the document.title of being updated regardless if it had changed or not. When using DocumentTitle today, any time some child component updates, the current document.title updates as well, and it shouldn't.
'use strict'; var React = require('react'), withSideEffect = require('react-side-effect'); function reducePropsToState(propsList) { var innermostProps = propsList[propsList.length - 1]; if (innermostProps) { return innermostProps.title; } } function handleStateChangeOnClient(title) { if (title !== document.title) { document.title = title || ''; } } var DocumentTitle = React.createClass({ displayName: 'DocumentTitle', propTypes: { title: React.PropTypes.string.isRequired }, render: function render() { if (this.props.children) { return React.Children.only(this.props.children); } else { return null; } } }); module.exports = withSideEffect( reducePropsToState, handleStateChangeOnClient )(DocumentTitle);
'use strict'; var React = require('react'), withSideEffect = require('react-side-effect'); function reducePropsToState(propsList) { var innermostProps = propsList[propsList.length - 1]; if (innermostProps) { return innermostProps.title; } } function handleStateChangeOnClient(title) { document.title = title || ''; } var DocumentTitle = React.createClass({ displayName: 'DocumentTitle', propTypes: { title: React.PropTypes.string.isRequired }, render: function render() { if (this.props.children) { return React.Children.only(this.props.children); } else { return null; } } }); module.exports = withSideEffect( reducePropsToState, handleStateChangeOnClient )(DocumentTitle);
Javadoc: Correct typo and add missing return description git-svn-id: 5ccfe34f605a6c2f9041ff2965ab60012c62539a@1776143 13f79535-47bb-0310-9956-ffa450edef68
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.jmeter.report.processor; /** * The interface ResultData represents a result from samples processing. * * @since 3.0 */ public interface ResultData { /** * Accepts the specified visitor. * * @param visitor * the visitor (must not be {@code null}) * @param <T> * type of the results of the {@link ResultDataVisitor} * @return result of the vist */ <T> T accept(ResultDataVisitor<T> visitor); }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.jmeter.report.processor; /** * The interface ResultData represents a result from samples processing. * * @since 3.0 */ public interface ResultData { /** * Accepts the specified visitor. * * @param visitor * the visitor (must not be {@code null}) * @paran <T> type of the results of the {@link ResultDataVisitor} */ <T> T accept(ResultDataVisitor<T> visitor); }
Fix bad require of ReadyStateManager
/** * This replaces the React Native Image component to register when it's finished * loading to avoid race conditions in visual tests. */ const React = require('react'); const Image = require('react-native/Libraries/Image/Image'); const { registerImageLoading } = require('./ready-state-manager'); class ReadyStateEmittingImage extends React.Component { constructor(props) { super(props); let resolver = null; if (props.source) { registerImageLoading( new Promise((resolve, reject) => { resolver = resolve; }) ); } this.handleLoadEnd = e => { if (resolver) { resolver(); resolver = null; } if (this.props.onLoadEnd) { this.props.onLoadEnd(e); } }; } render() { return <Image {...this.props} onLoadEnd={this.handleLoadEnd} />; } } ReadyStateEmittingImage.propTypes = Image.propTypes; ReadyStateEmittingImage.prefetch = Image.prefetch; ReadyStateEmittingImage.getSize = Image.getSize; module.exports = ReadyStateEmittingImage;
/** * This replaces the React Native Image component to register when it's finished * loading to avoid race conditions in visual tests. */ const React = require('react'); const Image = require('react-native/Libraries/Image/Image'); const { registerImageLoading } = require('./ready-state-emitting-image'); class ReadyStateEmittingImage extends React.Component { constructor(props) { super(props); let resolver = null; if (props.source) { registerImageLoading( new Promise((resolve, reject) => { resolver = resolve; }) ); } this.handleLoadEnd = e => { if (resolver) { resolver(); resolver = null; } if (this.props.onLoadEnd) { this.props.onLoadEnd(e); } }; } render() { return <Image {...this.props} onLoadEnd={this.handleLoadEnd} />; } } ReadyStateEmittingImage.propTypes = Image.propTypes; ReadyStateEmittingImage.prefetch = Image.prefetch; ReadyStateEmittingImage.getSize = Image.getSize; module.exports = ReadyStateEmittingImage;
Set package author to Bertrand Bordage
import io from setuptools import find_packages, setup def read(fname): with io.open(fname, encoding='utf-8') as f: return f.read() setup( name='wagtail-pg-search-backend', version='1.0.0.dev0', author='Bertrand Bordage', author_email='bordage.bertrand@gmail.com', packages=find_packages(exclude=['tests']), include_package_data=True, zip_safe=False, url='https://github.com/leukeleu/wagtail-pg-search-backend', description='PostgreSQL full text search backend for Wagtail CMS', long_description=read('README.rst'), keywords=['wagtail', 'postgres', 'fulltext', 'search'], classifiers=[ 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'License :: OSI Approved :: MIT License' ], license='MIT', install_requires=[ 'Django>=1.10', 'psycopg2', 'six', 'wagtail' ], test_suite='runtests.runtests' )
import io from setuptools import find_packages, setup def read(fname): with io.open(fname, encoding='utf-8') as f: return f.read() setup( name='wagtail-pg-search-backend', version='1.0.0.dev0', packages=find_packages(exclude=['tests']), include_package_data=True, zip_safe=False, url='https://github.com/leukeleu/wagtail-pg-search-backend', description='PostgreSQL full text search backend for Wagtail CMS', long_description=read('README.rst'), keywords=['wagtail', 'postgres', 'fulltext', 'search'], classifiers=[ 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'License :: OSI Approved :: MIT License' ], license='MIT', install_requires=[ 'Django>=1.10', 'psycopg2', 'six', 'wagtail' ], test_suite='runtests.runtests' )
Remove extra variable in class
<?php namespace Kirby\Plugin; use c; use tpl; use Twig_Loader_Filesystem; use Twig_Environment; use Twig_Extension_Debug; /** * A Twig <http://twig.sensiolabs.org/> plugin for Kirby <http://getkirby.com/> * @author Matthew Spencer <http://matthewspencer.me/> * @version 0.2 */ class Twig { public function __construct() { $this->autoloader(); $this->twig(); } /** * Require the autoloader */ private function autoloader() { if ( ! file_exists( kirby()->roots()->vendor() . '/autoload.php' ) ) { die( 'Composer autoload does not exist.' ); } require_once( kirby()->roots()->vendor() . '/autoload.php' ); } /** * Load Twig */ private function twig() { $loader = new Twig_Loader_Filesystem( kirby()->roots()->twig() ); $twig = new Twig_Environment( $loader, array( 'debug' => c::get( 'debug' ), ) ); if ( c::get( 'debug' ) ) { $twig->addExtension( new Twig_Extension_Debug() ); } tpl::set( 'twig', $twig ); } }
<?php namespace Kirby\Plugin; use c; use tpl; use Twig_Loader_Filesystem; use Twig_Environment; use Twig_Extension_Debug; /** * A Twig <http://twig.sensiolabs.org/> plugin for Kirby <http://getkirby.com/> * @author Matthew Spencer <http://matthewspencer.me/> * @version 0.2 */ class Twig { var $kirby; public function __construct() { $this->kirby = kirby(); $this->autoloader(); $this->twig(); } /** * Require the autoloader */ private function autoloader() { if ( ! file_exists( $this->kirby->roots()->vendor() . '/autoload.php' ) ) { die( 'Composer autoload does not exist.' ); } require_once( $this->kirby->roots()->vendor() . '/autoload.php' ); } /** * Load Twig */ private function twig() { $loader = new Twig_Loader_Filesystem( $this->kirby->roots()->twig() ); $twig = new Twig_Environment( $loader, array( 'debug' => c::get( 'debug' ), ) ); if ( c::get( 'debug' ) ) { $twig->addExtension( new Twig_Extension_Debug() ); } tpl::set( 'twig', $twig ); } }
Add mock for shapely module Adding a mock for the shapely module allows ReadTheDocs to build the docs even though Shapely isn't installed.
# -*- coding: utf-8 -*- import os import sphinx_rtd_theme import sys from unittest import mock # Add repository root so we can import ichnaea things REPO_DIR = os.path.dirname(os.path.dirname(__file__)) sys.path.append(REPO_DIR) # Fake the shapely module so things will import sys.modules['shapely'] = mock.MagicMock() project = 'Ichnaea' copyright = '2013-2019, Mozilla' # The short X.Y version. version = '2.0' # The full version, including alpha/beta/rc tags. release = '2.0' autoclass_content = 'class' exclude_patterns = ['build/html/README.rst', '.DS_Store', 'Thumbs.db'] html_static_path = [] html_theme = 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] master_doc = 'index' modindex_common_prefix = ['ichnaea.'] pygments_style = 'sphinx' source_suffix = '.rst' templates_path = ['_templates'] extensions = [ 'sphinx.ext.linkcode', 'everett.sphinxext', ] def linkcode_resolve(domain, info): if domain != 'py': return None if not info['module']: return None filename = info['module'].replace('.', '/') return "https://github.com/mozilla/ichnaea/tree/master/%s.py" % filename
# -*- coding: utf-8 -*- import os import sphinx_rtd_theme import sys REPO_DIR = os.path.dirname(os.path.dirname(__file__)) sys.path.append(REPO_DIR) project = 'Ichnaea' copyright = '2013-2019, Mozilla' # The short X.Y version. version = '2.0' # The full version, including alpha/beta/rc tags. release = '2.0' autoclass_content = 'class' exclude_patterns = ['build/html/README.rst', '.DS_Store', 'Thumbs.db'] html_static_path = [] html_theme = 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] master_doc = 'index' modindex_common_prefix = ['ichnaea.'] pygments_style = 'sphinx' source_suffix = '.rst' templates_path = ['_templates'] extensions = [ 'sphinx.ext.linkcode', 'everett.sphinxext', ] def linkcode_resolve(domain, info): if domain != 'py': return None if not info['module']: return None filename = info['module'].replace('.', '/') return "https://github.com/mozilla/ichnaea/tree/master/%s.py" % filename
mailman: Make @match work with newer greasemonkey Using a wildcard for the protocol no longer works.
// ==UserScript== // @name Mailman discard // @namespace http://bd808.com/userscripts/ // @description Automatically selects "Discard" and ticks the "Add" and "Discards" checkboxes on Mailman admin requests for pending messages // @match https?://*/mailman/admindb/* // @match https?://*/lists/admindb/* // @version 0.2 // @author Bryan Davis // @license MIT License; http://opensource.org/licenses/MIT // @downloadURL https://bd808.github.io/userscripts/mailman-discard-and-ban.user.js // @updateURL https://bd808.github.io/userscripts/mailman-discard-and-ban.user.js // @grant none // @run-at document-end // ==/UserScript== (function() { var inputs = document.getElementsByTagName('input'), len = inputs.length; for (var i = 0; i < len; i++) { var input = inputs[i]; if ( input.name.toLowerCase().match(/^senderaction/) && input.value == '3' ) { input.checked = true; } else if (input.name.toLowerCase().match(/^senderfilterp/)) { input.checked = true; } } })();
// ==UserScript== // @name Mailman discard // @namespace http://bd808.com/userscripts/ // @description Automatically selects "Discard" and ticks the "Add" and "Discards" checkboxes on Mailman admin requests for pending messages // @match *://*/mailman/admindb/* // @match *://*/lists/admindb/* // @version 0.1 // @author Bryan Davis // @license MIT License; http://opensource.org/licenses/MIT // @downloadURL https://bd808.github.io/userscripts/mailman-discard-and-ban.user.js // @updateURL https://bd808.github.io/userscripts/mailman-discard-and-ban.user.js // @grant none // @run-at document-end // ==/UserScript== (function() { var inputs = document.getElementsByTagName('input'), len = inputs.length; for (var i = 0; i < len; i++) { var input = inputs[i]; if ( input.name.toLowerCase().match(/^senderaction/) && input.value == '3' ) { input.checked = true; } else if (input.name.toLowerCase().match(/^senderfilterp/)) { input.checked = true; } } })();
Add class alias for BC with older PHPUnit
<?php use WP_CLI_Login\WP_CLI_Login_Server; if (! class_exists('PHPUnit_Framework_TestCase')) { class_alias('PHPUnit\Framework\TestCase', 'PHPUnit_Framework_TestCase'); } class WP_CLI_Login_ServerTest extends PHPUnit_Framework_TestCase { /** @test */ function parses_endpoint_and_key_from_uri() { list($endpoint, $public) = WP_CLI_Login_Server::parseUri('/end/key'); $this->assertSame('end', $endpoint); $this->assertSame('key', $public); } /** @test */ function parses_endpoint_and_key_from_uri_for_subdirectory_site() { list($endpoint, $public) = WP_CLI_Login_Server::parseUri('/abc/end/key'); $this->assertSame('end', $endpoint); $this->assertSame('key', $public); } }
<?php use WP_CLI_Login\WP_CLI_Login_Server; class WP_CLI_Login_ServerTest extends PHPUnit_Framework_TestCase { /** @test */ function parses_endpoint_and_key_from_uri() { list($endpoint, $public) = WP_CLI_Login_Server::parseUri('/end/key'); $this->assertSame('end', $endpoint); $this->assertSame('key', $public); } /** @test */ function parses_endpoint_and_key_from_uri_for_subdirectory_site() { list($endpoint, $public) = WP_CLI_Login_Server::parseUri('/abc/end/key'); $this->assertSame('end', $endpoint); $this->assertSame('key', $public); } }
:bug: Fix test case in react 15
import React from 'react'; let Trigger; // eslint-disable-line if (process.env.REACT === '15') { const ActualTrigger = require.requireActual('rc-trigger'); // cannot use object destruction, cause react 15 test cases fail const render = ActualTrigger.prototype.render; // eslint-disable-line ActualTrigger.prototype.render = () => { const { popupVisible } = this.state; // eslint-disable-line let component; if (popupVisible || this._component) { // eslint-disable-line component = this.getComponent(); // eslint-disable-line } return ( <div id="TriggerContainer"> {render.call(this)} {component} </div> ); }; Trigger = ActualTrigger; } else { const TriggerMock = require('rc-trigger/lib/mock'); // eslint-disable-line Trigger = TriggerMock; } export default Trigger;
import React from 'react'; let Trigger; // eslint-disable-line if (process.env.REACT === '15') { const ActualTrigger = require.requireActual('rc-trigger'); const { render } = ActualTrigger.prototype; ActualTrigger.prototype.render = () => { const { popupVisible } = this.state; // eslint-disable-line let component; if (popupVisible || this._component) { // eslint-disable-line component = this.getComponent(); // eslint-disable-line } return ( <div id="TriggerContainer"> {render.call(this)} {component} </div> ); }; Trigger = ActualTrigger; } else { const TriggerMock = require('rc-trigger/lib/mock'); // eslint-disable-line Trigger = TriggerMock; } export default Trigger;
Add CORS header to API responses
from flask import Flask from flask_restful import abort, Api, Resource from flask_cors import CORS app = Flask("pre-fixlist") api = Api(app) CORS(app) class PrefixListList(Resource): def get(self): # Return a list of all prefix lists we know about return None class PrefixList(Resource): def get(self, listid): # Return a list of versions return None def post(self): # Create a new prefixlist return None def put(self, listid): # Update a prefixlist return None def delete(self, listid): return None class PrefixListVersion(Resource): def get(self, listid, version): # Return a list of prefixes contained in the specific version of the prefixlist return None api.add_resource(PrefixListList, "/prefixlist") api.add_resource(PrefixList, "/prefixlist/<int:listid>") api.add_resource(PrefixListVersion, "/prefixlist/<int:listid>/<string:version>") if __name__ == '__main__': app.run(debug=True)
from flask import Flask from flask_restful import abort, Api, Resource app = Flask("pre-fixlist") api = Api(app) class PrefixListList(Resource): def get(self): # Return a list of all prefix lists we know about return None class PrefixList(Resource): def get(self, listid): # Return a list of versions return None def post(self): # Create a new prefixlist return None def put(self, listid): # Update a prefixlist return None def delete(self, listid): return None class PrefixListVersion(Resource): def get(self, listid, version): # Return a list of prefixes contained in the specific version of the prefixlist return None api.add_resource(PrefixListList, "/prefixlist") api.add_resource(PrefixList, "/prefixlist/<int:listid>") api.add_resource(PrefixListVersion, "/prefixlist/<int:listid>/<string:version>") if __name__ == '__main__': app.run(debug=True)
Fix Contact Us Submit $ADMIN to $ADMIN_SUPER
<?php use App\User; use Bpocallaghan\Titan\Models\Role; if (!function_exists('notify_admins')) { function notify_admins($class, $argument, $forceEmail = "") { if (strlen($forceEmail) >= 2) { $admins = User::where('email', $forceEmail)->get(); } else { $admins = User::whereRole(Role::$ADMIN_SUPER)->get(); } if ($admins) { foreach ($admins as $a => $admin) { $admin->notify(new $class($argument)); } } } }
<?php use App\User; use Bpocallaghan\Titan\Models\Role; if (!function_exists('notify_admins')) { function notify_admins($class, $argument, $forceEmail = "") { if (strlen($forceEmail) >= 2) { $admins = User::where('email', $forceEmail)->get(); } else { $admins = User::whereRole(Role::$ADMIN)->get(); } if ($admins) { foreach ($admins as $a => $admin) { $admin->notify(new $class($argument)); } } } }
Unify the python binaries being invoked in the various scripts.
#!/usr/bin/env python from os import curdir, pardir from os.path import join from distutils.core import setup from Cython.Distutils import Extension, build_ext setup( name = "VapourSynth", description = "A frameserver for the 21st century", url = "http://www.vapoursynth.com/", download_url = "http://code.google.com/p/vapoursynth/", author = "Fredrik Mellbin", author_email = "fredrik.mellbin@gmail.com", license = "LGPL 2.1 or later", version = "1.0.0", long_description = "A portable replacement for Avisynth", platforms = "All", cmdclass = {'build_ext': build_ext}, ext_modules = [Extension("vapoursynth", [join("src", "cython", "vapoursynth.pyx")], libraries = ["vapoursynth"], library_dirs = [curdir, "build"], include_dirs = [curdir, join("src", "cython")], cython_c_in_temp = 1)] )
#!/usr/bin/env python3 from os import curdir, pardir from os.path import join from distutils.core import setup from Cython.Distutils import Extension, build_ext setup( name = "VapourSynth", description = "A frameserver for the 21st century", url = "http://www.vapoursynth.com/", download_url = "http://code.google.com/p/vapoursynth/", author = "Fredrik Mellbin", author_email = "fredrik.mellbin@gmail.com", license = "LGPL 2.1 or later", version = "1.0.0", long_description = "A portable replacement for Avisynth", platforms = "All", cmdclass = {'build_ext': build_ext}, ext_modules = [Extension("vapoursynth", [join("src", "cython", "vapoursynth.pyx")], libraries = ["vapoursynth"], library_dirs = [curdir, "build"], include_dirs = [curdir, join("src", "cython")], cython_c_in_temp = 1)] )
Remove test that is not passed by Fuse.js itself
<?php require_once __DIR__ . '/../vendor/autoload.php'; use PHPUnit\Framework\TestCase; use Fuse\Fuse; class SearchListTest extends TestCase { public function testSearchBogoList() { $fuse = new Fuse([ 'Borwaila hamlet', 'Bobe hamlet', 'Bo hamlet', 'Boma hamlet' ], [ 'include' => ['score'] ]); // When searching for the term "Bo hamet" $result = $fuse->search('Bo hamet'); // ...we get a list containing 4 items... $this->assertEquals(sizeof($result), 4); // ...whose first value is the index of "Bo hamlet" $this->assertEquals($result[0]['item'], 2); } public function testSearchUniversities() { $fuse = new Fuse(['FH Mannheim', 'University Mannheim']); // When searching for the term "Uni Mannheim"... $result = $fuse->search('Uni Mannheim'); // ...we get a list containing 2 items... $this->assertEquals(sizeof($result), 2); // ...whose first value is the index of "University Mannheim" // This test is disabled because it's from the official Fuse.js test suite but Fuse.js itself doesn't pass it // $this->assertEquals($result[0], 1); } }
<?php require_once __DIR__ . '/../vendor/autoload.php'; use PHPUnit\Framework\TestCase; use Fuse\Fuse; class SearchListTest extends TestCase { public function testSearchBogoList() { $fuse = new Fuse([ 'Borwaila hamlet', 'Bobe hamlet', 'Bo hamlet', 'Boma hamlet' ], [ 'include' => ['score'] ]); // When searching for the term "Bo hamet" $result = $fuse->search('Bo hamet'); // ...we get a list containing 4 items... $this->assertEquals(sizeof($result), 4); // ...whose first value is the index of "Bo hamlet" $this->assertEquals($result[0]['item'], 2); } public function testSearchUniversities() { $fuse = new Fuse(['FH Mannheim', 'University Mannheim']); // When searching for the term "Uni Mannheim"... $result = $fuse->search('Uni Mannheim'); // ...we get a list containing 2 items... $this->assertEquals(sizeof($result), 2); // ...whose first value is the index of "University Mannheim" $this->assertEquals($result[0], 1); } }
Prepare version number for upcoming release
package cgeo.geocaching.utils; import cgeo.geocaching.BuildConfig; public class BranchDetectionHelper { // should contain the version name of the last feature release public static final String FEATURE_VERSION_NAME = "2022.10.16"; // should contain version names of active bugfix releases since last feature release, oldest first // empty the part within curly brackets when creating a new release branch from master public static final String[] BUGFIX_VERSION_NAME = new String[]{ }; private BranchDetectionHelper() { // utility class } /** * @return true, if BUILD_TYPE is not a nightly or debug build (e. g.: release, rc, legacy) */ // BUILD_TYPE is detected as constant but can change depending on the build configuration @SuppressWarnings("ConstantConditions") public static boolean isProductionBuild() { return !(BuildConfig.BUILD_TYPE.equals("debug") || BuildConfig.BUILD_TYPE.equals("nightly")); } /** * @return true, if BUILD_TYPE is a debug build. Nightly builds are **not** considered as developer build! */ // BUILD_TYPE is detected as constant but can change depending on the build configuration @SuppressWarnings("ConstantConditions") public static boolean isDeveloperBuild() { return BuildConfig.BUILD_TYPE.equals("debug"); } }
package cgeo.geocaching.utils; import cgeo.geocaching.BuildConfig; public class BranchDetectionHelper { // should contain the version name of the last feature release public static final String FEATURE_VERSION_NAME = "2022.09.19-RC"; // should contain version names of active bugfix releases since last feature release, oldest first // empty the part within curly brackets when creating a new release branch from master public static final String[] BUGFIX_VERSION_NAME = new String[]{ }; private BranchDetectionHelper() { // utility class } /** * @return true, if BUILD_TYPE is not a nightly or debug build (e. g.: release, rc, legacy) */ // BUILD_TYPE is detected as constant but can change depending on the build configuration @SuppressWarnings("ConstantConditions") public static boolean isProductionBuild() { return !(BuildConfig.BUILD_TYPE.equals("debug") || BuildConfig.BUILD_TYPE.equals("nightly")); } /** * @return true, if BUILD_TYPE is a debug build. Nightly builds are **not** considered as developer build! */ // BUILD_TYPE is detected as constant but can change depending on the build configuration @SuppressWarnings("ConstantConditions") public static boolean isDeveloperBuild() { return BuildConfig.BUILD_TYPE.equals("debug"); } }
fix(backend): Fix fatal error in the websocket server
<?php /** * Created by PhpStorm. * User: stas * Date: 24.01.16 * Time: 20:26 */ namespace WebsocketServerBundle\Model\Message\Client\Call; use JMS\Serializer\Annotation as JMS; use Symfony\Component\Validator\Constraints as Assert; class ClientMessageCallSend { /** * @var string * * @JMS\Expose() * @JMS\Type("string") */ private $login; /** * @var array * * @JMS\Expose() * @JMS\Type("array") */ private $callIds = []; /** * @return string */ public function getLogin() { return $this->login; } /** * @param string $login */ public function setLogin($login) { $this->login = $login; } /** * @return array */ public function getCallIds() { return $this->callIds; } /** * @param array $callIds */ public function setCallIds($callIds) { $this->callIds = $callIds; } }
<?php /** * Created by PhpStorm. * User: stas * Date: 24.01.16 * Time: 20:26 */ namespace WebsocketServerBundle\Model\Message\Client\Call; use JMS\Serializer\Annotation as JMS; use Symfony\Component\Validator\Constraints as Assert; class ClientMessageCallSend { /** * @var string * * @JMS\Expose() * @JMS\Type("string") */ private $login; /** * @var array * * @JMS\Expose() * @JMS\Type("array") */ private $callIds; /** * @return string */ public function getLogin() { return $this->login; } /** * @param string $login */ public function setLogin($login) { $this->login = $login; } /** * @return array */ public function getCallIds() { return $this->callIds; } /** * @param array $callIds */ public function setCallIds($callIds) { $this->callIds = $callIds; } }
Switch to using container singleton in provider Laravel 5.4 depreciated the app container share function
<?php namespace Xavrsl\Cas; use Illuminate\Support\ServiceProvider; class CasServiceProvider extends ServiceProvider { /** * Bootstrap the application. * * @return void */ public function boot() { $this->publishes([ __DIR__.'/../../config/cas.php' => config_path('cas.php'), ]); } /** * Register the service provider. * * @return void */ public function register() { $this->app->singleton('cas', function() { $config = $this->app['config']->get('cas'); return new CasManager($config); }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array('cas'); } }
<?php namespace Xavrsl\Cas; use Illuminate\Support\ServiceProvider; class CasServiceProvider extends ServiceProvider { /** * Bootstrap the application. * * @return void */ public function boot() { $this->publishes([ __DIR__.'/../../config/cas.php' => config_path('cas.php'), ]); } /** * Register the service provider. * * @return void */ public function register() { $this->app['cas'] = $this->app->share(function() { $config = $this->app['config']->get('cas'); return new CasManager($config); }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array('cas'); } }
Use is_dir and add error message
<?php /** * @desc - get a plugin * @param string $name - the plugin folder name * @param string|array $options - options to give plugin */ function plugin($name, $options = false) { if (is_dir(SITE . "/plugins/$name")) { if (!file_exists(SITE . "/plugins/$name/index.php")) { die("The plugin \"$name\" does not have an index.php file"); } include SITE . "/plugins/$name/index.php"; // dash-case into camelCase $fnName = str_replace('-', '', ucwords($name, '-')); $fnName = lcfirst($fnName); if (function_exists($fnName)) { $fnName($options); } else { die("It seems like plugin '$name' misses: '$fnName()' function"); } } else { die("No plugin named $name exists in /site/plugins - should be a directory"); } } ?>
<?php /** * @desc - get a plugin * @param string $name - the plugin folder name * @param string|array $options - options to give plugin */ function plugin($name, $options = false) { if (file_exists(SITE . "/plugins/$name")) { if (!file_exists(SITE . "/plugins/$name/index.php")) { die("The plugin \"$name\" does not have an index.php file"); } include SITE . "/plugins/$name/index.php"; // dash-case into camelCase $fnName = str_replace('-', '', ucwords($name, '-')); $fnName = lcfirst($fnName); if (function_exists($fnName)) { $fnName($options); } else { die("It seems like plugin '$name' misses: '$fnName()' function"); } } } ?>
Set default_flow_style for yaml jinja filter
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import yaml __all__ = [ 'to_json_string', 'to_yaml_string', ] def to_json_string(value, indent=4, sort_keys=False, separators=(',', ':')): return json.dumps(value, indent=indent, separators=separators, sort_keys=sort_keys) def to_yaml_string(value, indent=4, allow_unicode=True): return yaml.safe_dump(value, indent=indent, allow_unicode=allow_unicode, default_flow_style=False)
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import yaml __all__ = [ 'to_json_string', 'to_yaml_string', ] def to_json_string(value, indent=4, sort_keys=False, separators=(',', ':')): return json.dumps(value, indent=indent, separators=separators, sort_keys=sort_keys) def to_yaml_string(value, indent=4, allow_unicode=True): return yaml.safe_dump(value, indent=indent, allow_unicode=allow_unicode)
Work with custom user models in django >= 1.5 Work with Custom User Models introduced in django >= 1.5 Also tries to get a AUTH_USER_ADMIN_MODEL, not only AUTH_USER_MODEL
from django.contrib import admin from django.conf import settings from django.contrib.auth.models import Group from django.contrib.auth.admin import GroupAdmin from django.contrib.auth.forms import UserChangeForm try: User = settings.AUTH_USER_MODEL except: from django.contrib.auth.models import User try: UserAdmin = settings.AUTH_USER_ADMIN_MODEL except: from django.contrib.auth.admin import UserAdmin from mptt.forms import TreeNodeMultipleChoiceField if getattr(settings, 'MPTT_USE_FEINCMS', False): from mptt.admin import FeinCMSModelAdmin class GroupMPTTModelAdmin(GroupAdmin, FeinCMSModelAdmin): pass else: from mptt.admin import MPTTModelAdmin class GroupMPTTModelAdmin(GroupAdmin, MPTTModelAdmin): pass admin.site.unregister(Group) admin.site.register(Group, GroupMPTTModelAdmin) class UserWithMPTTChangeForm(UserChangeForm): groups = TreeNodeMultipleChoiceField(queryset=Group.tree.all()) class UserWithMPTTAdmin(UserAdmin): form = UserWithMPTTChangeForm admin.site.unregister(User) admin.site.register(User, UserWithMPTTAdmin)
from django.contrib import admin from django.conf import settings from django.contrib.auth.models import Group, User from django.contrib.auth.admin import GroupAdmin, UserAdmin from django.contrib.auth.forms import UserChangeForm from mptt.forms import TreeNodeMultipleChoiceField if getattr(settings, 'MPTT_USE_FEINCMS', False): from mptt.admin import FeinCMSModelAdmin class GroupMPTTModelAdmin(GroupAdmin, FeinCMSModelAdmin): pass else: from mptt.admin import MPTTModelAdmin class GroupMPTTModelAdmin(GroupAdmin, MPTTModelAdmin): pass admin.site.unregister(Group) admin.site.register(Group, GroupMPTTModelAdmin) class UserWithMPTTChangeForm(UserChangeForm): groups = TreeNodeMultipleChoiceField(queryset=Group.tree.all()) class UserWithMPTTAdmin(UserAdmin): form = UserWithMPTTChangeForm admin.site.unregister(User) admin.site.register(User, UserWithMPTTAdmin)
Set log level for handler
from __future__ import absolute_import import logging from logging.handlers import SysLogHandler from conf.appconfig import LOG_FORMAT, LOG_DATE, LOG_ROOT_LEVEL, TOTEM_ENV, \ LOG_IDENTIFIER def init_logging(name=None): app_logger = logging.getLogger(name) app_logger.setLevel(LOG_ROOT_LEVEL) app_logger.propagate = False if TOTEM_ENV == 'local': formatter = logging.Formatter(fmt=LOG_FORMAT, datefmt=LOG_DATE) handler = logging.StreamHandler() handler.setFormatter(formatter) app_logger.addHandler(handler) else: formatter = logging.Formatter( '{0}[%(process)d]: %(name)s: %(message)s' .format(LOG_IDENTIFIER)) handler = logging.handlers.SysLogHandler( address='/dev/log', facility=SysLogHandler.LOG_DAEMON) handler.setFormatter(formatter) handler.setLevel(LOG_ROOT_LEVEL) app_logger.addHandler(handler) app_logger.info('Logger initialized') return app_logger def init_celery_logging(*args, **kwargs): init_logging('celery')
from __future__ import absolute_import import logging from logging.handlers import SysLogHandler from conf.appconfig import LOG_FORMAT, LOG_DATE, LOG_ROOT_LEVEL, TOTEM_ENV, \ LOG_IDENTIFIER def init_logging(name=None): app_logger = logging.getLogger(name) app_logger.setLevel(LOG_ROOT_LEVEL) app_logger.propagate = False if TOTEM_ENV == 'local': formatter = logging.Formatter(fmt=LOG_FORMAT, datefmt=LOG_DATE) handler = logging.StreamHandler() handler.setFormatter(formatter) app_logger.addHandler(handler) else: formatter = logging.Formatter( '{0}[%(process)d]: %(name)s: %(message)s' .format(LOG_IDENTIFIER)) handler = logging.handlers.SysLogHandler( address='/dev/log', facility=SysLogHandler.LOG_DAEMON) handler.setFormatter(formatter) handler.setLevel(logging.INFO) app_logger.addHandler(handler) app_logger.info('Logger initialized') return app_logger def init_celery_logging(*args, **kwargs): init_logging('celery')
Allow access from beta site
<?php use Symfony\Component\HttpFoundation\Request; // If you don't want to setup permissions the proper way, just uncomment the following PHP line // read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information //umask(0000); // This check prevents access to debug front controllers that are deployed by accident to production servers. // Feel free to remove this, extend it, or make something more sophisticated. if ($_SERVER['HTTP_HOST'] !== 'beta.forexcashback.com' || $_SERVER['REMOTE_ADDR'] === '127.0.0.1') { header('HTTP/1.0 403 Forbidden'); exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.'); } $loader = require_once __DIR__.'/../app/bootstrap.php.cache'; require_once __DIR__.'/../app/AppKernel.php'; $kernel = new AppKernel('dev', true); $kernel->loadClassCache(); Request::enableHttpMethodParameterOverride(); $request = Request::createFromGlobals(); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response);
<?php use Symfony\Component\HttpFoundation\Request; // If you don't want to setup permissions the proper way, just uncomment the following PHP line // read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information //umask(0000); // This check prevents access to debug front controllers that are deployed by accident to production servers. // Feel free to remove this, extend it, or make something more sophisticated. if (isset($_SERVER['HTTP_CLIENT_IP']) || isset($_SERVER['HTTP_X_FORWARDED_FOR']) || !in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1')) ) { header('HTTP/1.0 403 Forbidden'); exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.'); } $loader = require_once __DIR__.'/../app/bootstrap.php.cache'; require_once __DIR__.'/../app/AppKernel.php'; $kernel = new AppKernel('dev', true); $kernel->loadClassCache(); Request::enableHttpMethodParameterOverride(); $request = Request::createFromGlobals(); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response);
[redis] Set the encoding parameter in Redis constructor
from frasco.ext import * from redis import Redis from werkzeug.local import LocalProxy from .templating import CacheFragmentExtension class FrascoRedis(Extension): name = "frasco_redis" defaults = {"url": "redis://localhost:6379/0", "fragment_cache_timeout": 3600, "decode_responses": True, "encoding": "utf-8"} def _init_app(self, app, state): state.connection = Redis.from_url(state.options["url"], decode_responses=state.options["decode_responses"], encoding=state.options["encoding"]) app.jinja_env.add_extension(CacheFragmentExtension) def get_current_redis(): return get_extension_state('frasco_redis').connection redis = LocalProxy(get_current_redis)
from frasco.ext import * from redis import StrictRedis from werkzeug.local import LocalProxy from .templating import CacheFragmentExtension class FrascoRedis(Extension): name = "frasco_redis" defaults = {"url": "redis://localhost:6379/0", "fragment_cache_timeout": 3600, "decode_responses": True} def _init_app(self, app, state): state.connection = StrictRedis.from_url(state.options["url"], state.options["decode_responses"]) app.jinja_env.add_extension(CacheFragmentExtension) def get_current_redis(): return get_extension_state('frasco_redis').connection redis = LocalProxy(get_current_redis)
Build page refresh if in progress
import ReactDOM from 'react-dom'; import React from 'react'; import {build as fetchBuild, buildLog as fetchBuildLog,cancelBuild as cancelBuildApi} from './../api/Api.jsx'; import BuildPage from './../pages/BuildPage.jsx'; import Drawer from './../Drawer.jsx'; import page from 'page'; import autoRefreshComponent from './../components/lib/AutoRefreshComponent.js'; function dataChange(build){ const buildPage =<BuildPage build={build} subBuild={build.subBuild}/> if(build.inProgress){ const AutoRefreshBuildPage = autoRefreshComponent(buildPage,()=>{ build.actions.BuildChange({buildNumber:build.number,subBuild:build.subBuild}); }); ReactDOM.render(<AutoRefreshBuildPage/>, document.getElementById('content')); }else{ ReactDOM.render(buildPage, document.getElementById('content')); } ReactDOM.render(<Drawer menu="build" build={build}/>, document.getElementById('nav')); } async function buildChange(build){ const actions = build.actions; let query = build.query; const data =await fetchBuild(build.number); actions.BuildInfoChange(data); const logText = await fetchBuildLog(build.number,build.subBuild) actions.LogChange(logText); } async function cancelBuild(build){ await cancelBuildApi(build.cancelUrl); } function lineSelect(build){ window.location.hash =build.selectedLine; } export default function(build){ const actions = build.actions; actions.BuildInfoChange.onAction = dataChange; actions.LogChange.onAction = dataChange; actions.CancelBuild.onAction = cancelBuild; actions.BuildChange.onAction = buildChange; actions.LineSelect.onAction = lineSelect; }
import ReactDOM from 'react-dom'; import React from 'react'; import {build as fetchBuild, buildLog as fetchBuildLog,cancelBuild as cancelBuildApi} from './../api/Api.jsx'; import Build from './../components/job/build/Build.jsx'; import Drawer from './../Drawer.jsx'; import page from 'page'; function dataChange(build){ ReactDOM.render(<Build build={build} subBuild={build.subBuild}/>, document.getElementById('content')); ReactDOM.render(<Drawer menu="build" build={build}/>, document.getElementById('nav')); } async function buildChange(build){ const actions = build.actions; let query = build.query; const data =await fetchBuild(build.number); actions.BuildInfoChange(data); const logText = await fetchBuildLog(build.number,build.subBuild) actions.LogChange(logText); } async function cancelBuild(build){ await cancelBuildApi(build.cancelUrl); } function lineSelect(build){ window.location.hash =build.selectedLine; } export default function(build){ const actions = build.actions; actions.BuildInfoChange.onAction = dataChange; actions.LogChange.onAction = dataChange; actions.CancelBuild.onAction = cancelBuild; actions.BuildChange.onAction = buildChange; actions.LineSelect.onAction = lineSelect; }
Change input widths also on resize.
jQuery(document).ready(function($) { serchilo_set_input_widths($); var that = $; jQuery(window).resize(function(that) { serchilo_set_input_widths($); }); }); function serchilo_set_input_widths($) { // Set widths of text inputs. // Get current widths. var form_width = $('#serchilo-shortcut-call-form').outerWidth(); var keyword_width = $('#serchilo-shortcut-call-form div.keyword').outerWidth(); var submit_width = $('#edit-submit').outerWidth(); // Calculate with for single text input. var argument_width_total = form_width - keyword_width - submit_width - 20; var argument_count = $('#serchilo-shortcut-call-form input.form-text').length; var argument_width_single = Math.round(argument_width_total / argument_count) - 5; // Set widths for all single text inputs. $('#serchilo-shortcut-call-form input.form-text').each(function() { $(this).outerWidth(argument_width_single); }); }
jQuery(document).ready(function($) { // Set widths of text inputs. // Get current widths. var form_width = $('#serchilo-shortcut-call-form').outerWidth(); var keyword_width = $('#serchilo-shortcut-call-form div.keyword').outerWidth(); var submit_width = $('#edit-submit').outerWidth(); // Calculate with for single text input. var argument_width_total = form_width - keyword_width - submit_width - 20; var argument_count = $('#serchilo-shortcut-call-form input.form-text').length; var argument_width_single = Math.round(argument_width_total / argument_count) - 5; // Set widths for all single text inputs. $('#serchilo-shortcut-call-form input.form-text').each(function() { $(this).outerWidth(argument_width_single); }); });
Fix indentation on routes page.
var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index'); }); /* Mode selection page. */ router.get('/select', function(req, res, next) { res.render('select'); }); /* Page to start a new room with friends. */ router.get('/start-room', function(req, res, next) { res.render('start-room'); }); /* Page to join a room of friends. */ router.get('/join-room', function(req, res, next) { res.render('join-room'); }); /* Page to join a random room. */ router.get('/join-random', function(req, res, next) { res.render('join-random'); }); /* Gameplay page components. Should be called with AJAX. */ router.post('/game', function(req, res, next) { res.render('game', { playerId: req.body.playerId}); }); /* If people directly try to access /play, redirect them home. * This URL is displayed when playing the game. */ router.get('/play', function(req, res, next) { res.redirect('/'); }); module.exports = router;
var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index'); }); /* Mode selection page. */ router.get('/select', function(req, res, next) { res.render('select'); }); /* Page to start a new room with friends. */ router.get('/start-room', function(req, res, next) { res.render('start-room'); }); /* Page to join a room of friends. */ router.get('/join-room', function(req, res, next) { res.render('join-room'); }); /* Page to join a random room. */ router.get('/join-random', function(req, res, next) { res.render('join-random'); }); /* Gameplay page components. Should be called with AJAX. */ router.post('/game', function(req, res, next) { res.render('game', { playerId: req.body.playerId}); }); /* If people directly try to access /play, redirect them home. * This URL is displayed when playing the game. */ router.get('/play', function(req, res, next) { res.redirect('/'); }); module.exports = router;
Check if travis tests passed
import bot_chucky from setuptools import setup version = bot_chucky.__version__ setup_kwargs = { 'name': 'bot_chucky', 'version': version, 'url': 'https://github.com/MichaelYusko/Bot-Chucky', 'license': 'MIT', 'author': 'Frozen Monkey', 'author_email': 'freshjelly12@yahoo.com', 'description': 'Python bot which able to work with messenger of facebook', 'packages': ['bot_chucky'], 'classifiers': [ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Programming Language :: Python :: 3.6', 'License :: OSI Approved :: MIT License' ], } requirements = ['requests==2.17.3', 'facebook-sdk==2.0.0'] setup_kwargs['install_requires'] = requirements setup(**setup_kwargs) print(u"\n\n\t\t " "BotChucky version {} installation succeeded.\n".format(version))
from setuptools import setup import bot_chucky version = bot_chucky.__version__ setup_kwargs = { 'name': 'bot_chucky', 'version': version, 'url': 'https://github.com/MichaelYusko/Bot-Chucky', 'license': 'MIT', 'author': 'Frozen Monkey', 'author_email': 'freshjelly12@yahoo.com', 'description': 'Python bot which able to work with messenger of facebook', 'packages': ['bot_chucky'], 'classifiers': [ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Programming Language :: Python :: 3.6', 'License :: OSI Approved :: MIT License' ], } requirements = ['requests==2.17.3', 'facebook-sdk==2.0.0'] setup_kwargs['install_requires'] = requirements setup(**setup_kwargs) print(u"\n\n\t\t " "BotChucky version {} installation succeeded.\n".format(version))
Sort search selections by title
<?php /* * This file is part of the Integrated package. * * (c) e-Active B.V. <integrated@e-active.nl> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Integrated\Bundle\ContentBundle\Document\SearchSelection; use Doctrine\ODM\MongoDB\DocumentRepository; /** * Repository for SearchSelection. * * @author Ger Jan van den Bosch <gerjan@e-active.nl> */ class SearchSelectionRepository extends DocumentRepository { /** * @param int $id * * @return mixed * * @throws \Doctrine\ODM\MongoDB\MongoDBException */ public function findPublicByUserId($id) { $builder = $this->createQueryBuilder(); $builder->addOr($builder->expr()->field('userId')->equals($id)); $builder->addOr($builder->expr()->field('public')->equals(true)); $builder->sort('title'); return $builder->getQuery()->execute(); } }
<?php /* * This file is part of the Integrated package. * * (c) e-Active B.V. <integrated@e-active.nl> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Integrated\Bundle\ContentBundle\Document\SearchSelection; use Doctrine\ODM\MongoDB\DocumentRepository; /** * Repository for SearchSelection. * * @author Ger Jan van den Bosch <gerjan@e-active.nl> */ class SearchSelectionRepository extends DocumentRepository { /** * @param int $id * * @return mixed * * @throws \Doctrine\ODM\MongoDB\MongoDBException */ public function findPublicByUserId($id) { $builder = $this->createQueryBuilder(); $builder->addOr($builder->expr()->field('userId')->equals($id)); $builder->addOr($builder->expr()->field('public')->equals(true)); return $builder->getQuery()->execute(); } }
Return 'Bad Request' on plain HTTP/RPC when encryption is required.
// Redirect between plain HTTP and encrypted HTTPS by following rules: // - If user is logged in - force HTTPS. // - If user is visiting "users.auth.*" page - force HTTPS. // - Otherwise force HTTP. 'use strict'; var isEncryptionAllowed = require('nodeca.core/lib/system/utils/is_encryption_allowed'); module.exports = function (N) { N.wire.before('server_chain:*', { priority: -75 }, function switch_http_and_https(env) { var shouldBeEncrypted = Boolean(env.session.user_id) || 'users.auth' === env.method.slice(0, 'users.auth'.length); if (env.request.isEncrypted === shouldBeEncrypted) { return; // Redirection is not needed. Continue. } if (!isEncryptionAllowed(N, env.method)) { return; // It is not possible to encrypt current connection. } var redirectUrl = env.url_to(env.method, env.params, { protocol: shouldBeEncrypted ? 'https' : 'http' }); if (!redirectUrl) { // Can't build URL - usually RPC-only method. return { code: N.io.BAD_REQUEST, message: 'Encrypted connection is required' }; } return { code: N.io.REDIRECT, head: { Location: redirectUrl } }; }); };
// Redirect between plain HTTP and encrypted HTTPS by following rules: // - If user is logged in - force HTTPS. // - If user is visiting "users.auth.*" page - force HTTPS. // - Otherwise force HTTP. 'use strict'; var isEncryptionAllowed = require('nodeca.core/lib/system/utils/is_encryption_allowed'); module.exports = function (N) { N.wire.before('server_chain:*', { priority: -75 }, function switch_http_and_https(env) { var shouldBeEncrypted = Boolean(env.session.user_id) || 'users.auth' === env.method.slice(0, 'users.auth'.length); if (env.request.isEncrypted === shouldBeEncrypted) { return; // Redirection is not needed. Continue. } if (!isEncryptionAllowed(N, env.method)) { return; // It is not possible to encrypt current connection. } var redirectUrl = env.url_to(env.method, env.params, { protocol: shouldBeEncrypted ? 'https' : 'http' }); return { code: N.io.REDIRECT, head: { Location: redirectUrl } }; }); };
Switch $ to the correct format - {}
/** * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase); /** * This Function updates the `/lastmodified` with the timestamp of the last write to `/chat/$message`. */ exports.touch = functions.database.ref('/chat/{message}').onWrite( event => admin.database().ref('/lastmodified').set(event.timestamp));
/** * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase); /** * This Function updates the `/lastmodified` with the timestamp of the last write to `/chat/$message`. */ exports.touch = functions.database.ref('/chat/$message').onWrite( event => admin.database().ref('/lastmodified').set(event.timestamp));
Mark areas outdated when no synced
// @flow import type { State } from 'types/store.types'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import Dashboard from 'components/dashboard'; import { updateApp, setPristineCacheTooltip } from 'redux-modules/app'; import { createReport } from 'redux-modules/reports'; import { isOutdated } from 'helpers/date'; import { setAreasRefreshing, updateSelectedIndex } from 'redux-modules/areas'; import withSuccessNotification from 'components/toast-notification/with-notifications'; function mapStateToProps(state: State) { return { refreshing: state.areas.refreshing, isConnected: state.offline.online, areasOutdated: !state.areas.synced || isOutdated(state.areas.syncDate), appSyncing: (state.areas.syncing || state.layers.syncing || state.alerts.queue.length > 0), pristine: state.app.pristineCacheTooltip }; } function mapDispatchToProps(dispatch: *) { return bindActionCreators({ updateApp, createReport, setAreasRefreshing, setPristine: setPristineCacheTooltip, updateSelectedIndex }, dispatch); } export default connect( mapStateToProps, mapDispatchToProps )(withSuccessNotification(Dashboard));
// @flow import type { State } from 'types/store.types'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import Dashboard from 'components/dashboard'; import { updateApp, setPristineCacheTooltip } from 'redux-modules/app'; import { createReport } from 'redux-modules/reports'; import { isOutdated } from 'helpers/date'; import { setAreasRefreshing, updateSelectedIndex } from 'redux-modules/areas'; import withSuccessNotification from 'components/toast-notification/with-notifications'; function mapStateToProps(state: State) { return { refreshing: state.areas.refreshing, isConnected: state.offline.online, areasOutdated: isOutdated(state.areas.syncDate), appSyncing: (state.areas.syncing || state.layers.syncing || state.alerts.queue.length > 0), pristine: state.app.pristineCacheTooltip }; } function mapDispatchToProps(dispatch: *) { return bindActionCreators({ updateApp, createReport, setAreasRefreshing, setPristine: setPristineCacheTooltip, updateSelectedIndex }, dispatch); } export default connect( mapStateToProps, mapDispatchToProps )(withSuccessNotification(Dashboard));
stylelint: Replace deprecated selector-no-id with selector-max-id
module.exports = { "rules": { "max-empty-lines": 2, "indentation": 2, "length-zero-no-unit": true, "no-duplicate-selectors": true, "string-quotes": "single", "value-no-vendor-prefix": true, "property-no-vendor-prefix": true, "block-no-empty": true, "selector-max-id": 0, "rule-empty-line-before": ["always-multi-line", { "ignore": ["after-comment", "inside-block"] }], "no-extra-semicolons": true } };
module.exports = { "rules": { "max-empty-lines": 2, "indentation": 2, "length-zero-no-unit": true, "no-duplicate-selectors": true, "string-quotes": "single", "value-no-vendor-prefix": true, "property-no-vendor-prefix": true, "block-no-empty": true, "selector-no-id": true, "rule-empty-line-before": ["always-multi-line", { "ignore": ["after-comment", "inside-block"] }], "no-extra-semicolons": true } };
Remove package list on confirmation
var _atom = require('atom'); var SelectListView = _atom.SelectListView; var helpers = require('atom-helpers'); function PackageListView() { SelectListView.__super__.constructor.apply(this, arguments); } helpers.extends(PackageListView, SelectListView); PackageListView.prototype.currentInstall; PackageListView.prototype.initialize = function() { PackageListView.__super__.initialize.apply(this, arguments); return this; }; PackageListView.prototype.destroy = function() { this.currentCommand = null; return PackageListView.__super__.detach.apply(this, arguments); }; PackageListView.prototype.viewForItem = function(item) { return '<li class="two-lines">' + item + '</li>'; }; PackageListView.prototype.confirmed = function(packageListName) { var utils = require('./Utils.js'); utils.loadPackageList(packageListName); this.remove(); }; PackageListView.prototype.showPackageList = function(item) { var items = ['PHP', 'Javascript']; this.addClass('overlay from-top'); this.setItems(items); atom.workspaceView.append(this); this.focusFilterEditor(); }; module.exports = PackageListView;
var _atom = require('atom'); var SelectListView = _atom.SelectListView; var helpers = require('atom-helpers'); function PackageListView() { SelectListView.__super__.constructor.apply(this, arguments); } helpers.extends(PackageListView, SelectListView); PackageListView.prototype.currentInstall; PackageListView.prototype.initialize = function() { PackageListView.__super__.initialize.apply(this, arguments); return this; }; PackageListView.prototype.destroy = function() { this.currentCommand = null; return PackageListView.__super__.detach.apply(this, arguments); }; PackageListView.prototype.viewForItem = function(item) { return '<li class="two-lines">' + item + '</li>'; }; PackageListView.prototype.confirmed = function(packageListName) { var utils = require('./Utils.js'); utils.loadPackageList(packageListName); }; PackageListView.prototype.showPackageList = function(item) { var items = ['PHP', 'Javascript']; this.addClass('overlay from-top'); this.setItems(items); atom.workspaceView.append(this); this.focusFilterEditor(); }; module.exports = PackageListView;
Fix React warning regarding 'key' prop in render.
/* @flow */ import React from 'react' import type { MessageResult } from 'types' import styles from './style.css' type RollsProps = { rolls: Array<number> } const Rolls = (props: RollsProps) => { return <span> {props.rolls.map((roll, i, arr) => ( <span key={i}> <span className={styles.roll}> { roll } </span> {(i + 1 !== arr.length) ? ' + ' : null} </span> ))} </span> } type ModProps = { mod: number } const Mod = (props: ModProps) => { if (props.mod == 0) { return null } return <span> {' + '} <span className={styles.mod}>{props.mod}</span> </span> } type Props = { result: ?MessageResult } const Result = (props: Props) => { if (!props.result) { return null } let { mod, rolls, total } = props.result return ( <div className={styles.result}> <Rolls rolls={rolls} /> <Mod mod={mod} /> {' = '} <span className={styles.total}>{total}</span> </div> ) } export default Result
/* @flow */ import React from 'react' import type { MessageResult } from 'types' import styles from './style.css' type RollsProps = { rolls: Array<number> } const Rolls = (props: RollsProps) => { return <span> {props.rolls.map((roll, i, arr) => ( <span> <span className={styles.roll}> { roll } </span> {(i + 1 !== arr.length) ? ' + ' : null} </span> ))} </span> } type ModProps = { mod: number } const Mod = (props: ModProps) => { if (props.mod == 0) { return null } return <span> {' + '} <span className={styles.mod}>{props.mod}</span> </span> } type Props = { result: ?MessageResult } const Result = (props: Props) => { if (!props.result) { return null } let { mod, rolls, total } = props.result return ( <div className={styles.result}> <Rolls rolls={rolls} /> <Mod mod={mod} /> {' = '} <span className={styles.total}>{total}</span> </div> ) } export default Result
Test the alerting system on pages new
/*****************************************************************************/ /* PagesNew: Event Handlers and Helpersss .js*/ /*****************************************************************************/ Template.PagesNew.events({ /* * Example: * 'click .selector': function (e, tmpl) { * * } */ 'submit form': function (e, tmpl) { e.preventDefault(); var title = tmpl.find('#pageTitle').value; var pageId = Pages.insert({ title: title }); App.setAlert('New page created.', 'success'); Router.go('pages.show', { _id: pageId}); } }); Template.PagesNew.helpers({ /* * Example: * items: function () { * return Items.find(); * } */ }); /*****************************************************************************/ /* PagesNew: Lifecycle Hooks */ /*****************************************************************************/ Template.PagesNew.created = function () { }; Template.PagesNew.rendered = function () { }; Template.PagesNew.destroyed = function () { };
/*****************************************************************************/ /* PagesNew: Event Handlers and Helpersss .js*/ /*****************************************************************************/ Template.PagesNew.events({ /* * Example: * 'click .selector': function (e, tmpl) { * * } */ 'submit form': function (e, tmpl) { e.preventDefault(); var title = tmpl.find('#pageTitle').value; var pageId = Pages.insert({ title: title }); Router.go('pages.show', { _id: pageId}); } }); Template.PagesNew.helpers({ /* * Example: * items: function () { * return Items.find(); * } */ }); /*****************************************************************************/ /* PagesNew: Lifecycle Hooks */ /*****************************************************************************/ Template.PagesNew.created = function () { }; Template.PagesNew.rendered = function () { }; Template.PagesNew.destroyed = function () { };
Add index on patient id
from sqlalchemy import Column, Integer, ForeignKey, String from sqlalchemy.orm import relationship from sqlalchemy.dialects import postgresql from radar.database import db from radar.models.common import uuid_pk_column, MetaModelMixin, patient_id_column, patient_relationship from radar.models.logs import log_changes class Form(db.Model): __tablename__ = 'forms' id = Column(Integer, primary_key=True) name = Column(String, nullable=False) data = Column(postgresql.JSONB, nullable=False) @log_changes class Entry(db.Model, MetaModelMixin): __tablename__ = 'entries' id = uuid_pk_column() patient_id = patient_id_column() patient = patient_relationship('entries') form_id = Column(Integer, ForeignKey('forms.id'), nullable=False) form = relationship('Form') data = Column(postgresql.JSONB, nullable=False) Index('entries_patient_idx', Entry.patient_id) class GroupForm(db.Model): __tablename__ = 'group_forms' id = Column(Integer, primary_key=True) group_id = Column(Integer, ForeignKey('groups.id'), nullable=False) group = relationship('Group') form_id = Column(Integer, ForeignKey('forms.id'), nullable=False) form = relationship('Form')
from sqlalchemy import Column, Integer, ForeignKey, String from sqlalchemy.orm import relationship from sqlalchemy.dialects import postgresql from radar.database import db from radar.models.common import uuid_pk_column, MetaModelMixin, patient_id_column, patient_relationship from radar.models.logs import log_changes class Form(db.Model): __tablename__ = 'forms' id = Column(Integer, primary_key=True) name = Column(String, nullable=False) data = Column(postgresql.JSONB, nullable=False) @log_changes class Entry(db.Model, MetaModelMixin): __tablename__ = 'entries' id = uuid_pk_column() patient_id = patient_id_column() patient = patient_relationship('entries') form_id = Column(Integer, ForeignKey('forms.id'), nullable=False) form = relationship('Form') data = Column(postgresql.JSONB, nullable=False) class GroupForm(db.Model): __tablename__ = 'group_forms' id = Column(Integer, primary_key=True) group_id = Column(Integer, ForeignKey('groups.id'), nullable=False) group = relationship('Group') form_id = Column(Integer, ForeignKey('forms.id'), nullable=False) form = relationship('Form')
Fix for RPC calls in Kafka actions
/** * Copyright © 2016-2018 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.thingsboard.server.common.msg.core; import lombok.Data; import org.thingsboard.server.common.msg.session.FromDeviceRequestMsg; import org.thingsboard.server.common.msg.session.MsgType; /** * @author Andrew Shvayka */ @Data public class ToServerRpcRequestMsg implements FromDeviceRequestMsg { private final Integer requestId; private final String method; private final String params; @Override public MsgType getMsgType() { return MsgType.TO_SERVER_RPC_REQUEST; } }
/** * Copyright © 2016-2018 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.thingsboard.server.common.msg.core; import lombok.Data; import org.thingsboard.server.common.msg.session.FromDeviceMsg; import org.thingsboard.server.common.msg.session.MsgType; /** * @author Andrew Shvayka */ @Data public class ToServerRpcRequestMsg implements FromDeviceMsg { private final int requestId; private final String method; private final String params; @Override public MsgType getMsgType() { return MsgType.TO_SERVER_RPC_REQUEST; } }
Fix GhostTab and GhostTabPane array dependencies No issue - TabPanes weren't finding their tab due to not listing all their dependencies in Ember.computed
//See gh-tabs-manager.js for use var TabPane = Ember.Component.extend({ classNameBindings: ['active'], tabsManager: Ember.computed(function () { return this.nearestWithProperty('isTabsManager'); }), tab: Ember.computed('tabsManager.tabs.[]', 'tabsManager.tabPanes.[]', function () { var index = this.get('tabsManager.tabPanes').indexOf(this), tabs = this.get('tabsManager.tabs'); return tabs && tabs.objectAt(index); }), active: Ember.computed.alias('tab.active'), // Register with the tabs manager registerWithTabs: function () { this.get('tabsManager').registerTabPane(this); }.on('didInsertElement'), unregisterWithTabs: function () { this.get('tabsManager').unregisterTabPane(this); }.on('willDestroyElement') }); export default TabPane;
//See gh-tabs-manager.js for use var TabPane = Ember.Component.extend({ classNameBindings: ['active'], tabsManager: Ember.computed(function () { return this.nearestWithProperty('isTabsManager'); }), tab: Ember.computed('tabsManager.tabs.@each', function () { var index = this.get('tabsManager.tabPanes').indexOf(this), tabs = this.get('tabsManager.tabs'); return tabs && tabs.objectAt(index); }), active: Ember.computed.alias('tab.active'), // Register with the tabs manager registerWithTabs: function () { this.get('tabsManager').registerTabPane(this); }.on('didInsertElement'), unregisterWithTabs: function () { this.get('tabsManager').unregisterTabPane(this); }.on('willDestroyElement') }); export default TabPane;
Fix to javascript file. Did not pass callback
function IntentPlugin() { 'use strict'; } IntentPlugin.prototype.getCordovaIntent = function(successCallback, failureCallback) { 'use strict'; return cordova.exec ( successCallback, failureCallback, "IntentPlugin", "getCordovaIntent", [] ); }; IntentPlugin.prototype.setNewIntentHandler = function(method) { 'use strict'; cordova.exec ( method, null, "IntentPlugin", "setNewIntentHandler", [] ); }; var intentInstance = new IntentPlugin(); module.exports = intentInstance; // Make plugin work under window.plugins if (!window.plugins) { window.plugins = {}; } if (!window.plugins.intent) { window.plugins.intent = intentInstance; }
function IntentPlugin() { 'use strict'; } IntentPlugin.prototype.getCordovaIntent = function(successCallback, failureCallback) { 'use strict'; return cordova.exec ( successCallback, failureCallback, "IntentPlugin", "getCordovaIntent", [] ); }; IntentPlugin.prototype.setNewIntentHandler = function(method) { 'use strict'; var defaults = { method: method }; cordova.exec ( null, null, "IntentPlugin", "setNewIntentHandler", [defaults] ); }; var intentInstance = new IntentPlugin(); module.exports = intentInstance; // Make plugin work under window.plugins if (!window.plugins) { window.plugins = {}; } if (!window.plugins.intent) { window.plugins.intent = intentInstance; }
Add "String" as allowed property
'use strict'; var utils = require('./utils/utils'); //------------------------------------------------------------------------------ // General rule - Create local version of Ember.* and DS.* //------------------------------------------------------------------------------ module.exports = function(context) { var message = 'Create local version of '; var report = function(node, name) { var msg = message + name + '.' + node.property.name; context.report(node, msg); }; var allowedEmberProperties = ['$', 'Object', 'Router', 'String']; var allowedDSProperties = []; var isExpressionForbidden = function (objectName, node, allowedProperties) { return node.object.name === objectName && node.property.name.length && allowedProperties.indexOf(node.property.name) === -1; }; return { CallExpression: function(node) { var callee = node.callee; var obj = utils.isMemberExpression(callee.object) ? callee.object : callee; if ( utils.isIdentifier(obj.object) && utils.isIdentifier(obj.property) ) { if (isExpressionForbidden('Ember', obj, allowedEmberProperties)) { report(obj, 'Ember'); } if (isExpressionForbidden('DS', obj, allowedDSProperties)) { report(obj, 'DS'); } } } }; };
'use strict'; var utils = require('./utils/utils'); //------------------------------------------------------------------------------ // General rule - Create local version of Ember.* and DS.* //------------------------------------------------------------------------------ module.exports = function(context) { var message = 'Create local version of '; var report = function(node, name) { var msg = message + name + '.' + node.property.name; context.report(node, msg); }; var allowedEmberProperties = ['$', 'Object', 'Router']; var allowedDSProperties = []; var isExpressionForbidden = function (objectName, node, allowedProperties) { return node.object.name === objectName && node.property.name.length && allowedProperties.indexOf(node.property.name) === -1; }; return { CallExpression: function(node) { var callee = node.callee; var obj = utils.isMemberExpression(callee.object) ? callee.object : callee; if ( utils.isIdentifier(obj.object) && utils.isIdentifier(obj.property) ) { if (isExpressionForbidden('Ember', obj, allowedEmberProperties)) { report(obj, 'Ember'); } if (isExpressionForbidden('DS', obj, allowedDSProperties)) { report(obj, 'DS'); } } } }; };
Add test for failing get_application_access_token
"""Tests for the ``utils`` module.""" from mock import patch, Mock as mock from nose.tools import * from facepy import * patch = patch('requests.session') def mock(): global mock_request mock_request = patch.start()().request def unmock(): patch.stop() @with_setup(mock, unmock) def test_get_application_access_token(): mock_request.return_value.content = 'access_token=...' access_token = get_application_access_token('<application id>', '<application secret key>') mock_request.assert_called_with('GET', 'https://graph.facebook.com/oauth/access_token', allow_redirects = True, params = { 'client_id': '<application id>', 'client_secret': '<application secret key>', 'grant_type': 'client_credentials' } ) assert access_token == '...' @with_setup(mock, unmock) def test_get_application_access_token_raises_error(): mock_request.return_value.content = 'An unknown error occurred' with assert_raises(GraphAPI.FacebookError): get_application_access_token('<application id>', '<application secret key>')
"""Tests for the ``utils`` module.""" from mock import patch, Mock as mock from nose.tools import * from facepy import * patch = patch('requests.session') def setup_module(): global mock_request mock_request = patch.start()().request def teardown_module(): patch.stop() def test_get_application_access_token(): mock_request.return_value.content = 'access_token=...' access_token = get_application_access_token('<application id>', '<application secret key>') mock_request.assert_called_with('GET', 'https://graph.facebook.com/oauth/access_token', allow_redirects = True, params = { 'client_id': '<application id>', 'client_secret': '<application secret key>', 'grant_type': 'client_credentials' } ) assert access_token == '...'
Check user role in policy. If a user is an admin or staff, we want to allow them to see/edit everything!
<?php namespace Northstar\Policies; use Illuminate\Auth\Access\HandlesAuthorization; use Northstar\Models\User; class UserPolicy { use HandlesAuthorization; /** * Determine if the authorized user can see full profile details * for the given user account. * * @param User $user * @param User $profile * @return bool */ public function viewFullProfile(User $user, User $profile) { if (in_array($user->role, ['admin', 'staff'])) { return true; } return $user->id === $profile->id; } /** * Determine if the authorized user can edit the profile details * for the given user account. * * @param User $user * @param User $profile * @return bool */ public function editProfile(User $user, User $profile) { if (in_array($user->role, ['admin', 'staff'])) { return true; } return $user->id === $profile->id; } }
<?php namespace Northstar\Policies; use Illuminate\Auth\Access\HandlesAuthorization; use Northstar\Models\User; class UserPolicy { use HandlesAuthorization; /** * Determine if the authorized user can see full profile details * for the given user account. * * @param User $user * @param User $profile * @return bool */ public function viewFullProfile(User $user, User $profile) { return $user->id === $profile->id; } /** * Determine if the authorized user can edit the profile details * for the given user account. * * @param User $user * @param User $profile * @return bool */ public function editProfile(User $user, User $profile) { return $user->id === $profile->id; } }
Add button type to select
var $ = require('jquery'); module.exports = { $doc: $(document), setupDom: function () { this.$el = $(this.element); this.$el.addClass(this.options.classes.originalSelect); // Setup wrapper this.$wrapper = $('<div />', { 'class': this.options.classes.wrapper }); // Setup select this.$select = $('<button />', { type: 'button', 'class': this.options.classes.select }); // Setup option list this.$optionList = $('<ul />', { 'class': [this.options.classes.optionList, this.options.classes.isHidden].join(' ') }); this.renderOptions(); this.renderSelect(this.getContent()); this.setActiveOption(this.getValue(), true); // Go! this.$wrapper .insertBefore(this.$el) .append(this.$el, this.$select, this.$optionList); }, destroyDom: function () { this.$el .removeClass(this.options.classes.originalSelect) .insertBefore(this.$wrapper); this.$wrapper.remove(); } };
var $ = require('jquery'); module.exports = { $doc: $(document), setupDom: function () { this.$el = $(this.element); this.$el.addClass(this.options.classes.originalSelect); // Setup wrapper this.$wrapper = $('<div />', { 'class': this.options.classes.wrapper }); // Setup select this.$select = $('<button />', { 'class': this.options.classes.select }); // Setup option list this.$optionList = $('<ul />', { 'class': [this.options.classes.optionList, this.options.classes.isHidden].join(' ') }); this.renderOptions(); this.renderSelect(this.getContent()); this.setActiveOption(this.getValue(), true); // Go! this.$wrapper .insertBefore(this.$el) .append(this.$el, this.$select, this.$optionList); }, destroyDom: function () { this.$el .removeClass(this.options.classes.originalSelect) .insertBefore(this.$wrapper); this.$wrapper.remove(); } };
Use default avatar also when loading
import {Emitter} from 'event-kit'; const LOADING_AVATAR_URL = 'atom://github/img/avatar.svg'; export default class AvatarCache { constructor(request) { this.byEmail = new Map(); this.emitter = new Emitter(); this.request = request; } avatarsForEmails(emails) { const requests = []; const responses = emails.map(email => { let response = this.byEmail.get(email); if (response === undefined) { requests.push(email); response = LOADING_AVATAR_URL; } return response; }); if (requests.length) { this.request(requests); } return responses; } addAll(byEmail) { for (const email in byEmail) { this.byEmail.set(email, byEmail[email]); } this.emitter.emit('did-update'); } onDidUpdate(callback) { return this.emitter.on('did-update', callback); } }
import {Emitter} from 'event-kit'; const LOADING_AVATAR_URL = 'https://github.com/simurai.png'; export default class AvatarCache { constructor(request) { this.byEmail = new Map(); this.emitter = new Emitter(); this.request = request; } avatarsForEmails(emails) { const requests = []; const responses = emails.map(email => { let response = this.byEmail.get(email); if (response === undefined) { requests.push(email); response = LOADING_AVATAR_URL; } return response; }); if (requests.length) { this.request(requests); } return responses; } addAll(byEmail) { for (const email in byEmail) { this.byEmail.set(email, byEmail[email]); } this.emitter.emit('did-update'); } onDidUpdate(callback) { return this.emitter.on('did-update', callback); } }
Compress even if payload is small
const Promise = require('bluebird'); const pathLib = require('path'); const express = require('express'); const compression = require('compression'); const tiles = require('./tiles'); const info = require('./info'); module.exports.init = function init(opts) { return Promise.try(() => { const router = express.Router(); const handlers = opts.requestHandlers || []; handlers.unshift(tiles, info); return Promise.mapSeries(handlers, reqHandler => reqHandler(opts.core, router)).return(router); }).then((router) => { // Add before static to prevent disk IO on each tile request const { app } = opts; const staticOpts = { setHeaders(res) { if (app.conf.cache) { res.header('Cache-Control', app.conf.cache); } if (res.req.originalUrl.endsWith('.pbf')) { res.header('Content-Encoding', 'gzip'); } }, }; app.use('/', router); // Compression is nativelly handled by the tiles, so only statics need its app.use(compression({ threshold: 0 })); app.use('/', express.static(pathLib.resolve(__dirname, '../static'), staticOpts)); app.use('/leaflet', express.static(pathLib.dirname(require.resolve('leaflet')), staticOpts)); opts.core.metrics.increment('init'); }); };
const Promise = require('bluebird'); const pathLib = require('path'); const express = require('express'); const compression = require('compression'); const tiles = require('./tiles'); const info = require('./info'); module.exports.init = function init(opts) { return Promise.try(() => { const router = express.Router(); const handlers = opts.requestHandlers || []; handlers.unshift(tiles, info); return Promise.mapSeries(handlers, reqHandler => reqHandler(opts.core, router)).return(router); }).then((router) => { // Add before static to prevent disk IO on each tile request const { app } = opts; const staticOpts = { setHeaders(res) { if (app.conf.cache) { res.header('Cache-Control', app.conf.cache); } if (res.req.originalUrl.endsWith('.pbf')) { res.header('Content-Encoding', 'gzip'); } }, }; app.use('/', router); // Compression is nativelly handled by the tiles, so only statics need its app.use(compression()); app.use('/', express.static(pathLib.resolve(__dirname, '../static'), staticOpts)); app.use('/leaflet', express.static(pathLib.dirname(require.resolve('leaflet')), staticOpts)); opts.core.metrics.increment('init'); }); };
Check for ping when connecting to postgresql db
// 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/. // // Contributor: Julien Vehent jvehent@mozilla.com [:ulfr] package database /* import "github.com/mozilla/mig/database" */ import ( "database/sql" "fmt" _ "github.com/lib/pq" ) type DB struct { c *sql.DB } // Connect opens a connection to the database and returns a handler func Open(dbname, user, password, host string, port int, sslmode string) (db DB, err error) { url := fmt.Sprintf("postgres://%s:%s@%s:%d/%s?sslmode=%s", user, password, host, port, dbname, sslmode) db.c, err = sql.Open("postgres", url) if err != nil { return } err = db.c.Ping() return } func (db *DB) Close() { db.c.Close() } func (db *DB) SetMaxOpenConns(n int) { db.c.SetMaxOpenConns(n) }
// 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/. // // Contributor: Julien Vehent jvehent@mozilla.com [:ulfr] package database /* import "github.com/mozilla/mig/database" */ import ( "database/sql" "fmt" _ "github.com/lib/pq" ) type DB struct { c *sql.DB } // Connect opens a connection to the database and returns a handler func Open(dbname, user, password, host string, port int, sslmode string) (db DB, err error) { url := fmt.Sprintf("postgres://%s:%s@%s:%d/%s?sslmode=%s", user, password, host, port, dbname, sslmode) db.c, err = sql.Open("postgres", url) return } func (db *DB) Close() { db.c.Close() } func (db *DB) SetMaxOpenConns(n int) { db.c.SetMaxOpenConns(n) }
feat(admin): Add more information to docs detail form The new form `DmsResource_detail` contains display expressions instead of legacy custom data providers, so they will be rendered in the new client, too. See https://git.tocco.ch/c/nice2/+/39800 Refs: TOCDEV-3120
import React from 'react' import PropTypes from 'prop-types' import EntityDetailApp from 'tocco-entity-detail/src/main' import Action from '../Action/' const DocumentView = ({match, history, breadcrumbs, emitAction}) => { const handleEntityDeleted = () => { const lastList = breadcrumbs.slice().reverse() .find(breadcrumb => breadcrumb.type === 'list') const lastListUrl = `/docs/${lastList.path}` history.push(lastListUrl) } return ( <EntityDetailApp entityName="Resource" entityId={match.params.key} formName="DmsResource" mode="update" actionAppComponent={Action} emitAction={emitAction} onEntityDeleted={handleEntityDeleted} /> ) } DocumentView.propTypes = { match: PropTypes.shape({ params: PropTypes.shape({ key: PropTypes.string.isRequired }).isRequired }).isRequired, history: PropTypes.shape({ push: PropTypes.func.isRequired }).isRequired, breadcrumbs: PropTypes.arrayOf(PropTypes.shape({ path: PropTypes.string.isRequired, type: PropTypes.string.isRequired })).isRequired, emitAction: PropTypes.func.isRequired } export default DocumentView
import React from 'react' import PropTypes from 'prop-types' import EntityDetailApp from 'tocco-entity-detail/src/main' import Action from '../Action/' const DocumentView = ({match, history, breadcrumbs, emitAction}) => { const handleEntityDeleted = () => { const lastList = breadcrumbs.slice().reverse() .find(breadcrumb => breadcrumb.type === 'list') const lastListUrl = `/docs/${lastList.path}` history.push(lastListUrl) } return ( <EntityDetailApp entityName="Resource" entityId={match.params.key} formName="Resource" mode="update" actionAppComponent={Action} emitAction={emitAction} onEntityDeleted={handleEntityDeleted} /> ) } DocumentView.propTypes = { match: PropTypes.shape({ params: PropTypes.shape({ key: PropTypes.string.isRequired }).isRequired }).isRequired, history: PropTypes.shape({ push: PropTypes.func.isRequired }).isRequired, breadcrumbs: PropTypes.arrayOf(PropTypes.shape({ path: PropTypes.string.isRequired, type: PropTypes.string.isRequired })).isRequired, emitAction: PropTypes.func.isRequired } export default DocumentView
Use API route in promotion tests
import os import pytest import requests @pytest.fixture def url(): return os.getenv("SITE", "http://localhost:5000") def test_post_images(expect, url): params = {"key": "iw", "lines": ["test", "deployment"]} response = requests.post(f"{url}/api/images", json=params) expect(response.status_code) == 201 expect(response.json()["url"]).endswith("/api/images/iw/test/deployment.png") def test_get_image(expect, url): response = requests.get(f"{url}/api/images/iw/tests_code/in_production.jpg") expect(response.status_code) == 200 expect(response.headers["Content-Type"]) == "image/jpeg" def test_get_image_custom(expect, url): response = requests.get( f"{url}/api/images/custom/test.png" "?alt=https://www.gstatic.com/webp/gallery/1.jpg" ) expect(response.status_code) == 200 expect(response.headers["Content-Type"]) == "image/png"
import os import pytest import requests @pytest.fixture def url(): return os.getenv("SITE", "http://localhost:5000") def test_post_images(expect, url): params = {"key": "iw", "lines": ["test", "deployment"]} response = requests.post(f"{url}/api/images", json=params) expect(response.status_code) == 201 expect(response.json()["url"]).endswith("/api/images/iw/test/deployment.png") def test_get_image(expect, url): response = requests.get(f"{url}/iw/tests_code/in_production.jpg") expect(response.status_code) == 200 expect(response.headers["Content-Type"]) == "image/jpeg" def test_get_image_custom(expect, url): response = requests.get( f"{url}/custom/test.png?alt=https://www.gstatic.com/webp/gallery/1.jpg" ) expect(response.status_code) == 200 expect(response.headers["Content-Type"]) == "image/png"
Correct typo; commandOptions are a local var
module.exports = { name: 'deploy', description: 'Deploys an ember-cli app', works: 'insideProject', anonymousOptions: [ '<deployTarget>' ], availableOptions: [ { name: 'deploy-config-file', type: String, default: 'config/deploy.js' }, { name: 'activate', type: Boolean } ], run: function(commandOptions, rawArgs) { commandOptions.deployTarget = rawArgs.shift(); process.env.DEPLOY_TARGET = commandOptions.deployTarget; var DeployTask = require('../tasks/deploy'); var deploy = new DeployTask({ project: this.project, ui: this.ui, deployTarget: commandOptions.deployTarget, deployConfigFile: commandOptions.deployConfigFile, commandOptions: commandOptions }); return deploy.run(); }, };
module.exports = { name: 'deploy', description: 'Deploys an ember-cli app', works: 'insideProject', anonymousOptions: [ '<deployTarget>' ], availableOptions: [ { name: 'deploy-config-file', type: String, default: 'config/deploy.js' }, { name: 'activate', type: Boolean } ], run: function(commandOptions, rawArgs) { commandOptions.deployTarget = rawArgs.shift(); process.env.DEPLOY_TARGET = commandOptions.deployTarget; var DeployTask = require('../tasks/deploy'); var deploy = new DeployTask({ project: this.project, ui: this.ui, deployTarget: commandOptions.deployTarget, deployConfigFile: commandOptions.deployConfigFile, commandOptions: this.commandOptions }); return deploy.run(); }, };
Comment for *=1 in controller
var Promise = require('bluebird'); var User = require('../models').User; module.exports = Promise.method(function getAllUsersPublic(offset, limit, desc) { offset*=1; // ensure value is a number in the case where it is not automatically limit*=1; // ^ var idOrder = (desc) ? ['id', 'DESC'] : ['id', 'ASC']; return User.findAll({order: [idOrder], offset: offset, limit:limit}).then(function(users) { for (var i = 0; i < users.length; ++i) { users[i] = { "name": users[i].name, "username": users[i].username, "profile_picture": users[i].profile_picture, "last_active": users[i].last_active }; } console.log(users); return users; }).catch(function(error) { console.log(error); return error; }); });
var Promise = require('bluebird'); var User = require('../models').User; module.exports = Promise.method(function getAllUsersPublic(offset, limit, desc) { offset*=1; limit*=1; var idOrder = (desc) ? ['id', 'DESC'] : ['id', 'ASC']; return User.findAll({order: [idOrder], offset: offset, limit:limit}).then(function(users) { for (var i = 0; i < users.length; ++i) { users[i] = { "name": users[i].name, "username": users[i].username, "profile_picture": users[i].profile_picture, "last_active": users[i].last_active }; } console.log(users); return users; }).catch(function(error) { console.log(error); return error; }); });
Bump version to 1.3.0-dev after releasing 1.2
__version_info__ = (1, 3, 0, 'dev') # Dot-connect all but the last. Last is dash-connected if not None. __version__ = '.'.join([str(i) for i in __version_info__[:-1]]) if __version_info__[-1] is not None: __version__ += ('-%s' % (__version_info__[-1],)) # context processor to add version to the template environment def context_extras(request): return { # software version 'SW_VERSION': __version__, # Alternate names for social-auth backends, # to be used for display and font-awesome icon (lowercased) # If not entered here, backend name will be used as-is for # icon and title-cased for display (i.e., twitter / Twitter). 'backend_names': { 'github': 'GitHub', 'google-oauth2': 'Google', }, }
from django.conf import settings __version_info__ = (1, 2, 0, 'dev') # Dot-connect all but the last. Last is dash-connected if not None. __version__ = '.'.join([str(i) for i in __version_info__[:-1]]) if __version_info__[-1] is not None: __version__ += ('-%s' % (__version_info__[-1],)) # context processor to add version to the template environment def context_extras(request): return { # software version 'SW_VERSION': __version__, # Alternate names for social-auth backends, # to be used for display and font-awesome icon (lowercased) # If not entered here, backend name will be used as-is for # icon and title-cased for display (i.e., twitter / Twitter). 'backend_names': { 'github': 'GitHub', 'google-oauth2': 'Google', }, }
Fix NPE in Log4j SessionListener
package de.chandre.admintool.log4j2; import java.io.IOException; import javax.servlet.annotation.WebListener; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * Session listener to remove unused outputstream appender to free resources * you may have to configure @ServletComponentScan * @author André * */ @WebListener @Component public class AdminToolLog4jSessionListener implements HttpSessionListener { private static final Log LOGGER = LogFactory.getLog(AdminToolLog4jSessionListener.class); public AdminToolLog4jSessionListener() { LOGGER.debug("Session listener to remove useless outputstreams has been initialiezed"); } @Autowired private AdminToolLog4j2Util log4jUtil; @Override public void sessionCreated(HttpSessionEvent sessionEvent) {} @Override public void sessionDestroyed(HttpSessionEvent sessionEvent) { String appenderName = (String) sessionEvent.getSession().getAttribute(AdminToolLog4j2Util.SESSION_APPENDER_NAME); try { if (null != log4jUtil) { log4jUtil.closeOutputStreamAppender(appenderName); } } catch (IOException e) { LOGGER.error(e.getMessage(), e); } } }
package de.chandre.admintool.log4j2; import java.io.IOException; import javax.servlet.annotation.WebListener; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @WebListener @Component public class AdminToolLog4jSessionListener implements HttpSessionListener { private static final Log LOGGER = LogFactory.getLog(AdminToolLog4jSessionListener.class); public AdminToolLog4jSessionListener() { LOGGER.debug("Session listener to remove useless outputstreams has been initialiezed"); } @Autowired private AdminToolLog4j2Util log4jUtil; @Override public void sessionCreated(HttpSessionEvent sessionEvent) {} @Override public void sessionDestroyed(HttpSessionEvent sessionEvent) { String appenderName = (String) sessionEvent.getSession().getAttribute(AdminToolLog4j2Util.SESSION_APPENDER_NAME); try { log4jUtil.closeOutputStreamAppender(appenderName); } catch (IOException e) { LOGGER.error(e.getMessage(), e); } } }
Add active_url to URL validation
<?php namespace Screeenly\Http\Requests; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Contracts\Validation\Validator; class CreateScreenshotRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'key' => ['required', 'exists:api_keys,key'], 'url' => ['required', 'url', 'active_url'], 'width' => ['sometimes', 'required', 'integer', 'max:2000', 'min:10'], 'height' => ['sometimes', 'required', 'integer', 'min:10'], 'delay' => ['sometimes', 'required', 'integer', 'max:10', 'min:0'], ]; } }
<?php namespace Screeenly\Http\Requests; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Contracts\Validation\Validator; class CreateScreenshotRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'key' => ['required', 'exists:api_keys,key'], 'url' => ['required', 'url'], // Is 'active_url' reliable enough? 'width' => ['sometimes', 'required', 'integer', 'max:2000', 'min:10'], 'height' => ['sometimes', 'required', 'integer', 'min:10'], 'delay' => ['sometimes', 'required', 'integer', 'max:10', 'min:0'], ]; } }
Make it as a subclass. as advised by termie make it as a subclass instead of patching the method.
# vim: tabstop=4 shiftwidth=4 softtabstop=4 """Main entry point into the S3 Credentials service. TODO-DOCS """ import base64 import hmac from hashlib import sha1 from keystone import config from keystone.common import wsgi from keystone.contrib import ec2 CONF = config.CONF class S3Extension(wsgi.ExtensionRouter): def add_routes(self, mapper): controller = S3Controller() # validation mapper.connect('/s3tokens', controller=controller, action='authenticate', conditions=dict(method=['POST'])) class S3Controller(ec2.Ec2Controller): def check_signature(self, creds_ref, credentials): msg = base64.urlsafe_b64decode(str(credentials['token'])) key = str(creds_ref['secret']) signed = base64.encodestring(hmac.new(key, msg, sha1).digest()).strip() if credentials['signature'] != signed: raise Exception("Not Authorized")
# vim: tabstop=4 shiftwidth=4 softtabstop=4 """Main entry point into the S3 Credentials service. TODO-DOCS """ import base64 import hmac from hashlib import sha1 from keystone import config from keystone.common import wsgi from keystone.contrib import ec2 CONF = config.CONF def check_signature(creds_ref, credentials): signature = credentials['signature'] msg = base64.urlsafe_b64decode(str(credentials['token'])) key = str(creds_ref['secret']) signed = base64.encodestring(hmac.new(key, msg, sha1).digest()).strip() if signature == signed: pass else: raise Exception("Not Authorized") class S3Extension(wsgi.ExtensionRouter): def add_routes(self, mapper): controller = ec2.Ec2Controller() controller.check_signature = check_signature # validation mapper.connect('/s3tokens', controller=controller, action='authenticate', conditions=dict(method=['POST'])) # No need CRUD stuff since we are sharing keystone.contrib.ec2 # infos.
Update version app to v0.2.0
<?php namespace Cffie\Console; use Cffie\Command\QueryCommand; use Symfony\Component\Console\Application as BaseApplication; class Application extends BaseApplication { private $logo = ' ____ _____ _____ _ / ___| ___| ___(_) ___ | | | |_ | |_ | |/ _ \ | |___| _| | _| | | __/ \____|_| |_| |_|\___| '; public function __construct() { parent::__construct('CFFie', '0.2.0'); } protected function getDefaultCommands() { $commands = parent::getDefaultCommands(); $commands[] = new QueryCommand(); return $commands; } public function getHelp() { return $this->logo.parent::getHelp(); } public function getLongVersion() { return parent::getLongVersion().' by <comment>Dany Maillard</comment>'; } }
<?php namespace Cffie\Console; use Cffie\Command\QueryCommand; use Symfony\Component\Console\Application as BaseApplication; class Application extends BaseApplication { private $logo = ' ____ _____ _____ _ / ___| ___| ___(_) ___ | | | |_ | |_ | |/ _ \ | |___| _| | _| | | __/ \____|_| |_| |_|\___| '; public function __construct() { parent::__construct('CFFie', '0.1.1'); } protected function getDefaultCommands() { $commands = parent::getDefaultCommands(); $commands[] = new QueryCommand(); return $commands; } public function getHelp() { return $this->logo.parent::getHelp(); } }
Add a fallback for older Django versions that doesn't come with "six"
from rq.decorators import job as _rq_job from .queues import get_queue def job(func_or_queue, connection=None, *args, **kwargs): """ The same as RQ's job decorator, but it works automatically works out the ``connection`` argument from RQ_QUEUES. And also, it allows simplified ``@job`` syntax to put job into default queue. """ if callable(func_or_queue): func = func_or_queue queue = 'default' else: func = None queue = func_or_queue try: from django.utils import six string_type = six.string_types except ImportError: # for django lt v1.5 and python 2 string_type = basestring if isinstance(queue, string_type): try: queue = get_queue(queue) if connection is None: connection = queue.connection except KeyError: pass decorator = _rq_job(queue, connection=connection, *args, **kwargs) if func: return decorator(func) return decorator
from django.utils import six from rq.decorators import job as _rq_job from .queues import get_queue def job(func_or_queue, connection=None, *args, **kwargs): """ The same as RQ's job decorator, but it works automatically works out the ``connection`` argument from RQ_QUEUES. And also, it allows simplified ``@job`` syntax to put job into default queue. """ if callable(func_or_queue): func = func_or_queue queue = 'default' else: func = None queue = func_or_queue if isinstance(queue, six.string_types): try: queue = get_queue(queue) if connection is None: connection = queue.connection except KeyError: pass decorator = _rq_job(queue, connection=connection, *args, **kwargs) if func: return decorator(func) return decorator
Resolve tsx and jsx extentions for SSR
const path = require('path') const nodeExternals = require('webpack-node-externals') const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin') const ROOT = path.join(__dirname, '/../../') const config = { mode: process.env.NODE_ENV, target: 'node', node: { __dirname: true, __filename: true, }, externals: [nodeExternals()], entry: path.join(ROOT, 'lib/app.ts'), output: { path: path.join(ROOT, 'dist/server'), filename: 'app.js', }, resolve: { plugins: [new TsconfigPathsPlugin({ configFile: path.join(ROOT, 'tsconfig.server.json') })], modules: ['./node_modules'], extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'], }, module: { rules: [ { test: /.(ts|js)x?$/, exclude: /node_modules/, loader: 'ts-loader', options: { configFile: path.join(ROOT, 'tsconfig.server.json'), }, }, ], }, // plugins: [new webpack.ContextReplacementPlugin(/local_modules/, (context) => { // console.log(context) // })], stats: { colors: true, errorDetails: true, }, } module.exports = config
const path = require('path') const nodeExternals = require('webpack-node-externals') const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin') const ROOT = path.join(__dirname, '/../../') const config = { mode: process.env.NODE_ENV, target: 'node', node: { __dirname: true, __filename: true, }, externals: [nodeExternals()], entry: path.join(ROOT, 'lib/app.ts'), output: { path: path.join(ROOT, 'dist/server'), filename: 'app.js', }, resolve: { plugins: [new TsconfigPathsPlugin({ configFile: path.join(ROOT, 'tsconfig.server.json') })], modules: ['./node_modules'], extensions: ['.ts', '.js', '.json'], }, module: { rules: [ { test: /\.(js|ts)$/, exclude: /node_modules/, loader: 'ts-loader', options: { configFile: path.join(ROOT, 'tsconfig.server.json'), }, }, ], }, // plugins: [new webpack.ContextReplacementPlugin(/local_modules/, (context) => { // console.log(context) // })], stats: { colors: true, errorDetails: true, }, } module.exports = config
Add routing for facebook auth
var express = require('express'); var router = express.Router(); require('dotenv').config() const passport = require('passport') const FacebookStrategy = require('passport-facebook').Strategy passport.use(new FacebookStrategy({ clientID: process.env.APP_ID, clientSecret: process.env.APP_SECRET, callbackURL: "https://age-guess-api.herokuapp.com" }, function(accessToken, refreshToken, profile, done) { User.findOrCreate(function(err, user) { if (err) { return done(err); } done(null, user); }); } )); /* GET entries */ router.get('/', function(req, res) { res.render('login') }); router.get('/auth/facebook', passport.authenticate('facebook')) router.get('/auth/facebook/callback', passport.authenticate('facbeook', { successRedirect: '/', failureRedirect: '/login' }) ) router.get( '/auth/facebook/secret', passport.authenticate('facebook', { failureRedirect: '/login' }), (req, res) => { res.send('Hello This is A Secret!') } ) module.exports = router;
var express = require('express'); var router = express.Router(); const passport = require('passport') const FacebookStrategy = require('passport-facebook').Strategy passport.use(new FacebookStrategy({ clientID: 'fsddf', clientSecret: 'FACEBOOK_APP_SECRET', callbackURL: "https://age-guess-api.herokuapp.com" }, function(accessToken, refreshToken, profile, done) { User.findOrCreate(function(err, user) { if (err) { return done(err); } done(null, user); }); } )); /* GET entries */ router.get('/', function(req, res) { res.render('login') }); router.get('/auth/facebook', passport.authenticate('facebook')) router.get('/auth/facebook/callback', passport.authenticate('facbeook', { successRedirect: '/', failureRedirect: '/login' }) ) module.exports = router;
Drop old names from v0
#!/usr/bin/env python import sys import h5py infiles = sys.argv[1:] for infile in infiles: with h5py.File(infile, 'a') as h5: print(infile) if 'format-version' in h5.attrs and h5.attrs['format-version'] < 1: if 'matrix' in h5 and not 'pixels' in h5: print('renaming matrix --> pixels') h5['pixels'] = h5['matrix'] del h5['matrix'] if 'scaffolds' in h5 and not 'chroms' in h5: print('renaming scaffolds --> chroms') h5['chroms'] = h5['scaffolds'] del h5['scaffolds'] h5.attrs['format-version'] = 1
#!/usr/bin/env python import sys import h5py infiles = sys.argv[1:] for infile in infiles: with h5py.File(infile, 'a') as h5: print(infile) if 'format-version' in h5.attrs and h5.attrs['format-version'] < 1: if 'matrix' in h5 and not 'pixels' in h5: print('renaming matrix --> pixels') h5['pixels'] = h5['matrix'] if 'scaffolds' in h5 and not 'chroms' in h5: print('renaming scaffolds --> chroms') h5['chroms'] = h5['scaffolds'] h5.attrs['format-version'] = 1
Update released_test to use v1.3.0
package integration import ( "os" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) const previousKismaticVersion = "v1.3.0" // Test a specific released version of Kismatic var _ = Describe("Installing with previous version of Kismatic", func() { BeforeEach(func() { // setup previous version of Kismatic tmp := setupTestWorkingDirWithVersion(previousKismaticVersion) os.Chdir(tmp) }) installOpts := installOptions{ allowPackageInstallation: true, } Context("using Ubuntu 16.04 LTS", func() { ItOnAWS("should install successfully [slow]", func(aws infrastructureProvisioner) { WithInfrastructure(NodeCount{1, 1, 1, 0, 0}, Ubuntu1604LTS, aws, func(nodes provisionedNodes, sshKey string) { err := installKismatic(nodes, installOpts, sshKey) Expect(err).ToNot(HaveOccurred()) }) }) }) Context("using CentOS", func() { ItOnAWS("should install successfully [slow]", func(aws infrastructureProvisioner) { WithInfrastructure(NodeCount{1, 1, 1, 0, 0}, CentOS7, aws, func(nodes provisionedNodes, sshKey string) { err := installKismatic(nodes, installOpts, sshKey) Expect(err).ToNot(HaveOccurred()) }) }) }) })
package integration import ( "os" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) const previousKismaticVersion = "v1.2.0" // Test a specific released version of Kismatic var _ = Describe("Installing with previous version of Kismatic", func() { BeforeEach(func() { // setup previous version of Kismatic tmp := setupTestWorkingDirWithVersion(previousKismaticVersion) os.Chdir(tmp) }) installOpts := installOptions{ allowPackageInstallation: true, } Context("using Ubuntu 16.04 LTS", func() { ItOnAWS("should install successfully [slow]", func(aws infrastructureProvisioner) { WithInfrastructure(NodeCount{1, 1, 1, 0, 0}, Ubuntu1604LTS, aws, func(nodes provisionedNodes, sshKey string) { err := installKismatic(nodes, installOpts, sshKey) Expect(err).ToNot(HaveOccurred()) }) }) }) Context("using CentOS", func() { ItOnAWS("should install successfully [slow]", func(aws infrastructureProvisioner) { WithInfrastructure(NodeCount{1, 1, 1, 0, 0}, CentOS7, aws, func(nodes provisionedNodes, sshKey string) { err := installKismatic(nodes, installOpts, sshKey) Expect(err).ToNot(HaveOccurred()) }) }) }) })
[MIFOS-3150] Add sections to Question Group
/* * Copyright (c) 2005-2010 Grameen Foundation USA * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * * See also http://www.apache.org/licenses/LICENSE-2.0.html for an * explanation of the license and how it is applied. */ package org.mifos.ui.core.controller; import java.io.Serializable; public class SectionForm implements Serializable { private static final long serialVersionUID = 4707282409987816335L; private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
/* * Copyright (c) 2005-2010 Grameen Foundation USA * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * * See also http://www.apache.org/licenses/LICENSE-2.0.html for an * explanation of the license and how it is applied. */ package org.mifos.ui.core.controller; public class SectionForm { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
Fix the API/CLIENT API keys.
// Copyright (c) 2015, Wojciech Adam Koszek <wojciech@koszek.com> // All rights reserved. package com.barvoy.sensorama; import com.barvoy.sensorama.BuildConfig; import android.app.Application; import android.content.Context; import com.parse.Parse; import com.parse.ParseCrashReporting; public class SRApp extends Application { private static Context context; public void onCreate(){ super.onCreate(); ParseCrashReporting.enable(this); Parse.enableLocalDatastore(this); Parse.initialize(this, BuildConfig.PARSE_API_ID, BuildConfig.PARSE_API_ID ); SRApp.context = getApplicationContext(); } public static Context getAppContext() { return SRApp.context; } }
// Copyright (c) 2015, Wojciech Adam Koszek <wojciech@koszek.com> // All rights reserved. package com.barvoy.sensorama; import android.app.Application; import android.content.Context; import com.parse.Parse; import com.parse.ParseAnalytics; import com.parse.ParseCrashReporting; import com.barvoy.sensorama.SRAPIPerms; public class SRApp extends Application { private static Context context; public void onCreate(){ super.onCreate(); ParseCrashReporting.enable(this); Parse.enableLocalDatastore(this); Parse.initialize(this, SRAPIPerms.parseAPIID, SRAPIPerms.parseCLIID ); SRApp.context = getApplicationContext(); } public static Context getAppContext() { return SRApp.context; } }
Add default values to the TalksMeta model
<?php namespace OpenCFP\Domain\Model; class TalkMeta extends Eloquent { protected $table = 'talk_meta'; const CREATED_AT = 'created'; const UPDATED_AT = null; const DEFAULT_RATING = 0; const DEFAULT_VIEWED = 0; protected $attributes = [ 'rating' => self::DEFAULT_RATING, 'viewed' => self::DEFAULT_VIEWED, ]; public function talk() { return $this->belongsTo(Talk::class, 'talk_id'); } public function user() { return $this->belongsTo(User::class, 'admin_user_id'); } public function setUpdatedAt($value) { /** * This is the dirty way to tell Illuminate that we don't have an updated at field * while still having a created_at field. */ } }
<?php namespace OpenCFP\Domain\Model; class TalkMeta extends Eloquent { protected $table = 'talk_meta'; const CREATED_AT = 'created'; const UPDATED_AT = null; /** * The attributes that aren't mass assignable. * * @var array */ protected $guarded = []; public function talk() { return $this->belongsTo(Talk::class, 'talk_id'); } public function user() { return $this->belongsTo(User::class, 'admin_user_id'); } public function setUpdatedAt($value) { /** * This is the dirty way to tell Illuminate that we don't have an updated at field * while still having a created_at field. */ } }
Add 'today' to bulgarian locale
/** * Bulgarian translation for bootstrap-datepicker * Apostol Apostolov <apostol.s.apostolov@gmail.com> */ ;(function($){ $.fn.datepicker.dates['bg'] = { days: ["Неделя", "Понеделник", "Вторник", "Сряда", "Четвъртък", "Петък", "Събота", "Неделя"], daysShort: ["Нед", "Пон", "Вто", "Сря", "Чет", "Пет", "Съб", "Нед"], daysMin: ["Н", "П", "В", "С", "Ч", "П", "С", "Н"], months: ["Януари", "Февруари", "Март", "Април", "Май", "Юни", "Юли", "Август", "Септември", "Октомври", "Ноември", "Декември"], monthsShort: ["Ян", "Фев", "Мар", "Апр", "Май", "Юни", "Юли", "Авг", "Сеп", "Окт", "Ное", "Дек"], today: "днес" }; }(jQuery));
/** * Bulgarian translation for bootstrap-datepicker * Apostol Apostolov <apostol.s.apostolov@gmail.com> */ ;(function($){ $.fn.datepicker.dates['bg'] = { days: ["Неделя", "Понеделник", "Вторник", "Сряда", "Четвъртък", "Петък", "Събота", "Неделя"], daysShort: ["Нед", "Пон", "Вто", "Сря", "Чет", "Пет", "Съб", "Нед"], daysMin: ["Н", "П", "В", "С", "Ч", "П", "С", "Н"], months: ["Януари", "Февруари", "Март", "Април", "Май", "Юни", "Юли", "Август", "Септември", "Октомври", "Ноември", "Декември"], monthsShort: ["Ян", "Фев", "Мар", "Апр", "Май", "Юни", "Юли", "Авг", "Сеп", "Окт", "Ное", "Дек"] }; }(jQuery));