text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add flatpickr widget to activityDate field
import SlimSelect from 'slim-select'; import 'slim-select/dist/slimselect.min.css'; import flatpickr from "flatpickr"; import 'flatpickr/dist/flatpickr.min.css'; import moment from 'moment'; AutoForm.addHooks(['activityForm'], { 'onSuccess': function (formType) { // Hide the modal dialogue Modal.hide('activityForm'); // placeholder for success message text let successMessage; // Get relevant success message for form type if (formType === 'update') { successMessage = TAPi18n.__("activityForm-update-success"); } else { successMessage = TAPi18n.__("activityForm-add-success"); } const successMessageWithIcon = '<i class="fa fa-check"></i> ' + successMessage // Alert user that activity was added FlashMessages.sendSuccess(successMessageWithIcon); } }); Template.autoForm.onRendered(function () { const instance = this; // Make sure the new activity form is being rendered if (instance.data.id === "activityForm") { // Get localized placeholder text const placeholder = TAPi18n.__('activityForm-residentSelect-placeholder'); // Render multi-select widget on 'select residents' field new SlimSelect({ select: '[name=residentIds]', closeOnSelect: false, placeholder, }); // Render cross-platform date picker on date field flatpickr("#activityDate", { minDate: moment().subtract(7, 'days').startOf('day').toDate(), maxDate: moment().endOf('day').toDate(), }); } });
import SlimSelect from 'slim-select'; import 'slim-select/dist/slimselect.min.css'; AutoForm.addHooks(['activityForm'], { 'onSuccess': function (formType) { // Hide the modal dialogue Modal.hide('activityForm'); // placeholder for success message text let successMessage; // Get relevant success message for form type if (formType === 'update') { successMessage = TAPi18n.__("activityForm-update-success"); } else { successMessage = TAPi18n.__("activityForm-add-success"); } const successMessageWithIcon = '<i class="fa fa-check"></i> ' + successMessage // Alert user that activity was added FlashMessages.sendSuccess(successMessageWithIcon); } }); Template.autoForm.onRendered(function () { const instance = this; // Make sure the new activity form is being rendered if (instance.data.id === "activityForm") { // Get localized placeholder text const placeholder = TAPi18n.__('activityForm-residentSelect-placeholder'); // Render multi-select widget on 'select residents' field new SlimSelect({ select: '[name=residentIds]', closeOnSelect: false, placeholder, }); } });
Move public compilation folder back to frontend/ This is done because Express throws a bunch of errors if the destination path contains '../'.
exports.config = { // See http://brunch.io/#documentation for docs. conventions: { assets: /^app\/assets/ }, modules: { definition: false, wrapper: false }, files: { javascripts: { joinTo: { 'javascripts/app.js': /^app/, 'javascripts/vendor.js': /^vendor/, }, order: { before: [ 'vendor/ghetto-bower/jquery-2.0.3.min.js', ] }, }, stylesheets: { joinTo: { 'css/app.css': /^(app|vendor)/ } }, templates: { joinTo: { 'js/templates.js': /.+\.jade$/ } } }, plugins: { jade: { pretty: true } }, paths:{ public: 'public/' } }
exports.config = { // See http://brunch.io/#documentation for docs. conventions: { assets: /^app\/assets/ }, modules: { definition: false, wrapper: false }, files: { javascripts: { joinTo: { 'javascripts/app.js': /^app/, 'javascripts/vendor.js': /^vendor/, }, order: { before: [ 'vendor/ghetto-bower/jquery-2.0.3.min.js', ] }, }, stylesheets: { joinTo: { 'css/app.css': /^(app|vendor)/ } }, templates: { joinTo: { 'js/templates.js': /.+\.jade$/ } } }, plugins: { jade: { pretty: true } }, paths:{ public: '../backend/public/' } }
Use correct default SSH port
from shlex import quote import click @click.command() @click.option('-p', '--print/--exec', 'print_cmd', default=False, help='Print the command instead of executing it.') @click.argument('environment') @click.pass_obj def ssh(lancet, print_cmd, environment): """ SSH into the given environment, based on the dploi configuration. """ namespace = {} with open('deployment.py') as fh: code = compile(fh.read(), 'deployment.py', 'exec') exec(code, {}, namespace) config = namespace['settings'][environment] host = '{}@{}'.format(config['user'], config['hosts'][0]) cmd = ['ssh', '-p', str(config.get('port', 22)), host] if print_cmd: click.echo(' '.join(quote(s) for s in cmd)) else: lancet.defer_to_shell(*cmd)
from shlex import quote import click @click.command() @click.option('-p', '--print/--exec', 'print_cmd', default=False, help='Print the command instead of executing it.') @click.argument('environment') @click.pass_obj def ssh(lancet, print_cmd, environment): """ SSH into the given environment, based on the dploi configuration. """ namespace = {} with open('deployment.py') as fh: code = compile(fh.read(), 'deployment.py', 'exec') exec(code, {}, namespace) config = namespace['settings'][environment] host = '{}@{}'.format(config['user'], config['hosts'][0]) cmd = ['ssh', '-p', str(config.get('port', 20)), host] if print_cmd: click.echo(' '.join(quote(s) for s in cmd)) else: lancet.defer_to_shell(*cmd)
Make detect stop sign function for Henry to add into class
import SimpleCV as scv from SimpleCV import Image import cv2 import time from start_camera import start_camera import threading def take_50_pictures(): camera_thread = threading.Thread(target=start_camera) camera_thread.start() from get_images_from_pi import get_image, valid_image time.sleep(2) count = 0 while (count < 50): get_image(count) count += 1 def detect_stop_sign(image): reds = image.hueDistance(color=scv.Color.RED) stretched_image = reds.stretch(20,21) inverted_image = stretched_image.invert() blobs = inverted_image.findBlobs(minsize=3500) if blobs: return True #means there is an obstruction return False image = Image('images/0.jpg') x = 5 while (x < 7): print x image = Image('images/stop'+ str(x) + '.jpg') detect_stop_sign(image) x +=1 exit()
import SimpleCV as scv from SimpleCV import Image import cv2 import time from start_camera import start_camera import threading def take_50_pictures(): camera_thread = threading.Thread(target=start_camera) camera_thread.start() from get_images_from_pi import get_image, valid_image time.sleep(2) count = 0 while (count < 50): get_image(count) count += 1 def detect_stop_sign(image): reds = image.hueDistance(color=scv.Color.RED) stretch = reds.stretch(20,21) invert = stretch.invert() blobs = invert.findBlobs(minsize=2000) if blobs: for blob in blobs: print blob.area() blob.draw(color=(0, 128, 0)) invert.show() invert.show() time.sleep(3) image = Image('images/0.jpg') x = 0 while (x < 40): image = Image('images/'+ str(x) + '.jpg') detect_stop_sign(image) print x x +=1 exit()
Update headings to match new tab title
module.exports = { pageTitle: 'Review your application', eligibilityInfo: 'Financial info', netAnnualIncomeLabel: 'Your net annual income:', minAgeOrOlderLabel: '65 or older:', hasSpouseLabel: 'Spouse/common-law partner:', spouseIncomeLabel: 'Spouse\'s annual income:', numberOfKidsLabel: 'Kids:', childcareExpensesLabel: 'Childcare expenses:', ucbAmountLabel: 'Universal childcare benefit amount:', rdspAmountLabel: 'Registered Disability Savings Plan amount:', changeEligibilityInfoButton: 'Edit Financial Info', personalInfo: 'Your information', spouseInfo: 'Your spouse or common-law partner\'s information', nameLabel: 'Name:', birthDateLabel: 'Birthdate:', phnLabel: 'Personal Health Number (PHN):', sinLabel: 'Social Insurance Number (SIN):', changePersonalInfoButton: 'Edit Personal Info', changeSpouseInfoButton: 'Edit Spouse Info', contactInfo: 'Contact information', phoneNumberLabel: 'Phone number:', mailingAddressLabel: 'Mailing Address:', changeContactInfoButton: 'Edit Contact Info', continueButton: 'Continue', }
module.exports = { pageTitle: 'Review your application', eligibilityInfo: 'Eligibility information', netAnnualIncomeLabel: 'Your net annual income:', minAgeOrOlderLabel: '65 or older:', hasSpouseLabel: 'Spouse/common-law partner:', spouseIncomeLabel: 'Spouse\'s annual income:', numberOfKidsLabel: 'Kids:', childcareExpensesLabel: 'Childcare expenses:', ucbAmountLabel: 'Universal childcare benefit amount:', rdspAmountLabel: 'Registered Disability Savings Plan amount:', changeEligibilityInfoButton: 'Edit Eligibility Information', personalInfo: 'Your information', spouseInfo: 'Your spouse or common-law partner\'s information', nameLabel: 'Name:', birthDateLabel: 'Birthdate:', phnLabel: 'Personal Health Number (PHN):', sinLabel: 'Social Insurance Number (SIN):', changePersonalInfoButton: 'Edit Personal Info', changeSpouseInfoButton: 'Edit Spouse Info', contactInfo: 'Contact information', phoneNumberLabel: 'Phone number:', mailingAddressLabel: 'Mailing Address:', changeContactInfoButton: 'Edit Contact Info', continueButton: 'Continue', }
Call ob_end_flush instead of sending 2 KiB padding
<?php namespace HomoChecker\View; class ServerSentEventView implements ViewInterface { public $event; public function __construct($event) { $this->event = $event; header('Content-Type: text/event-stream'); // 2 KiB padding echo ":" . str_repeat(" ", 2048) . "\n"; $this->flush(); } public function render($data) { echo "event: {$this->event}\n"; echo "data: " . json_encode($data) . "\n\n"; $this->flush(); } public function flush() { ob_end_flush(); flush(); } public function close() { echo "event: close\n"; echo "data: end\n\n"; } }
<?php namespace HomoChecker\View; class ServerSentEventView implements ViewInterface { public $event; public function __construct($event) { $this->event = $event; header('Content-Type: text/event-stream'); flush(); } public function render($data) { // 2 KiB padding echo ":" . str_repeat(" ", 2048) . "\n"; echo "event: {$this->event}\n"; echo "data: " . json_encode($data) . "\n\n"; flush(); } public function close() { echo "event: close\n"; echo "data: end\n\n"; } }
Remove unused function call in order to make updating of projects pass
<?php namespace AppBundle\API\Edit; use AppBundle\API\Webservice; use AppBundle\Entity\FennecUser; use Symfony\Component\HttpFoundation\ParameterBag; class UpdateProject extends Webservice { /** * @inheritdoc */ public function execute(ParameterBag $query, FennecUser $user = null) { $em = $this->getManagerFromQuery($query); if(!$query->has('biom') || !$query->has('project_id')){ return array('error' => 'Missing parameter "biom" or "project_id"'); } if($user == null){ return array('error' => 'User not logged in'); } $webuser = $user; if($webuser === null){ return array('error' => 'Could not update project. Not found for user.'); } $project = $em->getRepository('AppBundle:WebuserData')->findOneBy(array('webuser' => $webuser, 'webuserDataId' => $query->get('project_id'))); if($project === null){ return array('error' => 'Could not update project. Not found for user.'); } $project->setProject(json_decode($query->get('biom'), true)); $em->flush(); return array('error' => null); } }
<?php namespace AppBundle\API\Edit; use AppBundle\API\Webservice; use AppBundle\Entity\FennecUser; use Symfony\Component\HttpFoundation\ParameterBag; class UpdateProject extends Webservice { /** * @inheritdoc */ public function execute(ParameterBag $query, FennecUser $user = null) { $em = $this->getManagerFromQuery($query); if(!$query->has('biom') || !$query->has('project_id')){ return array('error' => 'Missing parameter "biom" or "project_id"'); } if($user == null){ return array('error' => 'User not logged in'); } $webuser = $user->getWebuser($em); if($webuser === null){ return array('error' => 'Could not update project. Not found for user.'); } $project = $em->getRepository('AppBundle:WebuserData')->findOneBy(array('webuser' => $webuser, 'webuserDataId' => $query->get('project_id'))); if($project === null){ return array('error' => 'Could not update project. Not found for user.'); } $project->setProject(json_decode($query->get('biom'), true)); $em->flush(); return array('error' => null); } }
Improve log message for invalid example id
package com.testedminds.template.handlers; import com.google.gson.Gson; import com.testedminds.template.db.ExampleDao; import com.testedminds.template.models.Example; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import spark.Request; import spark.Response; import spark.Route; public class GetExampleHandler implements Route { private final static Logger logger = LoggerFactory.getLogger(GetExampleHandler.class); private final ExampleDao dao; public GetExampleHandler(ExampleDao dao) { this.dao = dao; } @Override public Object handle(Request req, Response res) throws Exception { long id; Object requestId = req.params(":id"); try { id = Long.parseLong(requestId.toString()); logger.info(String.format("retrieving an example with id: %d", id)); } catch (Exception ex) { String message = String.format("example id must be a numeric value: '%s'", requestId); logger.warn(message); res.status(400); return message; } Example example = dao.get(id); if (example == null) { res.status(404); return String.format("Example with id %d does not exist.", id); } res.status(200); res.type("application/json"); return new Gson().toJson(example); } }
package com.testedminds.template.handlers; import com.google.gson.Gson; import com.testedminds.template.db.ExampleDao; import com.testedminds.template.models.Example; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import spark.Request; import spark.Response; import spark.Route; public class GetExampleHandler implements Route { private final static Logger logger = LoggerFactory.getLogger(GetExampleHandler.class); private final ExampleDao dao; public GetExampleHandler(ExampleDao dao) { this.dao = dao; } @Override public Object handle(Request req, Response res) throws Exception { long id; Object requestId = req.params(":id"); try { id = Long.parseLong(requestId.toString()); logger.info(String.format("retrieving an example with id: %d", id)); } catch (Exception ex) { logger.warn(ex.getMessage()); res.status(400); return String.format("%s is not a valid numeric value.", requestId); } Example example = dao.get(id); if (example == null) { res.status(404); return String.format("Example with id %d does not exist.", id); } res.status(200); res.type("application/json"); return new Gson().toJson(example); } }
Add the api_key to the query only if we're not authenticated some other way
App.Store = DS.Store.extend({ findQuery: function(type, query){ query = query || {}; if (!this.container.lookup('router:main').namespace.AuthManager.isAuthenticated()){ query.api_key = 'a3yqP8KA1ztkIbq4hpokxEOwnUkleu2AMv0XsBWC0qLBKVL7pA'; } return this._super(type, query); }, allRecords: function(){ var typeMaps = this.get('typeMaps'), records = []; for (var key in typeMaps){ records = records.concat(typeMaps[key].records); } return records; }, unloadAllRecords: function(){ var records = this.allRecords(), record; while (record = records.pop()){ record.unloadRecord(); } }, modelFor: function(type){ if (type === 'post'){ this.Post.typeKey = 'post'; return this.Post; } else { return this._super(type); } }, Post: DS.Model.extend(App.PostMixin) });
App.Store = DS.Store.extend({ findQuery: function(type, id){ id = id || {}; id.api_key = App.API_KEY; return this._super(type, id); }, allRecords: function(){ var typeMaps = this.get('typeMaps'), records = []; for (var key in typeMaps){ records = records.concat(typeMaps[key].records); } return records; }, unloadAllRecords: function(){ var records = this.allRecords(), record; while (record = records.pop()){ record.unloadRecord(); } }, modelFor: function(type){ if (type === 'post'){ this.Post.typeKey = 'post'; return this.Post; } else { return this._super(type); } }, Post: DS.Model.extend(App.PostMixin) });
Remove settings & update shrinkwrap
import React from 'react'; import Router, { Route, DefaultRoute } from 'react-router'; import App from './views/app'; import ProductSelector from './views/pages/product-selector'; import Items from './views/pages/items'; import ItemDetail from './views/pages/item-detail'; import Search from './views/pages/search'; var routes = ( <Route name="app" path="/" handler={App}> <Route name="product" path="product/:id" handler={Items} > <Route name="item/:number" handler={ItemDetail} /> </Route> <Route name="search" path="search" handler={Search} /> <DefaultRoute handler={ProductSelector} /> </Route> ); function analytics(state) { if (typeof ga !== 'undefined') { window.ga('send', 'pageview', { 'page': state.path }); } } export default function(sprintlyClient) { sprintlyClient.router = Router.run(routes, Router.HistoryLocation, function(Handler, state) { React.render(<Handler user={sprintlyClient.user} />, document.getElementById('manifold')); analytics(state); }); return sprintlyClient; }
import React from 'react'; import Router, { Route, DefaultRoute } from 'react-router'; import App from './views/app'; import ProductSelector from './views/pages/product-selector'; import Items from './views/pages/items'; import ItemDetail from './views/pages/item-detail'; import Settings from './views/pages/settings'; import Search from './views/pages/search'; var routes = ( <Route name="app" path="/" handler={App}> <Route name="product" path="product/:id" handler={Items} > <Route name="item/:number" handler={ItemDetail} /> </Route> <Route name="search" path="search" handler={Search} /> <DefaultRoute handler={ProductSelector} /> </Route> ); function analytics(state) { if (typeof ga !== 'undefined') { window.ga('send', 'pageview', { 'page': state.path }); } } export default function(sprintlyClient) { sprintlyClient.router = Router.run(routes, Router.HistoryLocation, function(Handler, state) { React.render(<Handler user={sprintlyClient.user} />, document.getElementById('manifold')); analytics(state); }); return sprintlyClient; }
Use git describe --always in _get_version() Travis CI does a truncated clone and causes 'git describe' to fail if the version tag is not part of the truncated history.
"""Adaptive configuration dialogs. Attributes: __version__: The current version string. """ import os import subprocess def _get_version(version=None): # overwritten by setup.py if version is None: pkg_dir = os.path.dirname(__file__) src_dir = os.path.abspath(os.path.join(pkg_dir, os.pardir)) git_dir = os.path.join(src_dir, ".git") git_args = ("git", "--work-tree", src_dir, "--git-dir", git_dir, "describe", "--tags", "--always") output = subprocess.check_output(git_args) version = output.decode("utf-8").strip() if version.rfind("-") >= 0: version = version[:version.rfind("-")] # strip SHA1 hash version = version.replace("-", ".post") # PEP 440 compatible return version __version__ = _get_version()
"""Adaptive configuration dialogs. Attributes: __version__: The current version string. """ import os import subprocess def _get_version(version=None): # overwritten by setup.py if version is None: pkg_dir = os.path.dirname(__file__) src_dir = os.path.abspath(os.path.join(pkg_dir, os.pardir)) git_dir = os.path.join(src_dir, ".git") git_args = ("git", "--work-tree", src_dir, "--git-dir", git_dir, "describe", "--tags") output = subprocess.check_output(git_args) version = output.decode("utf-8").strip() if version.rfind("-") >= 0: version = version[:version.rfind("-")] # strip SHA1 hash version = version.replace("-", ".post") # PEP 440 compatible return version __version__ = _get_version()
Change presentation for primitive values in collection view
package com.intellij.debugger.streams.ui; import com.intellij.debugger.DebuggerContext; import com.intellij.debugger.engine.ContextUtil; import com.intellij.debugger.engine.evaluation.EvaluateException; import com.intellij.debugger.memory.utils.InstanceValueDescriptor; import com.intellij.openapi.project.Project; import com.intellij.psi.JavaPsiFacade; import com.intellij.psi.PsiElementFactory; import com.intellij.psi.PsiExpression; import com.sun.jdi.ObjectReference; import com.sun.jdi.Value; import org.jetbrains.annotations.NotNull; /** * @author Vitaliy.Bibaev */ public class PrimitiveValueDescriptor extends InstanceValueDescriptor { PrimitiveValueDescriptor(@NotNull Project project, @NotNull Value value) { super(project, value); } @Override public String calcValueName() { final Value value = getValue(); if (value instanceof ObjectReference) { return super.calcValueName(); } return value.type().name(); } @Override public boolean isShowIdLabel() { return true; } @Override public PsiExpression getDescriptorEvaluation(DebuggerContext debuggerContext) throws EvaluateException { final Value value = getValue(); if (value instanceof ObjectReference) { return super.getDescriptorEvaluation(debuggerContext); } final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(myProject).getElementFactory(); return elementFactory.createExpressionFromText("", ContextUtil.getContextElement(debuggerContext)); } }
package com.intellij.debugger.streams.ui; import com.intellij.debugger.DebuggerContext; import com.intellij.debugger.engine.ContextUtil; import com.intellij.debugger.engine.evaluation.EvaluateException; import com.intellij.debugger.memory.utils.InstanceValueDescriptor; import com.intellij.openapi.project.Project; import com.intellij.psi.JavaPsiFacade; import com.intellij.psi.PsiElementFactory; import com.intellij.psi.PsiExpression; import com.sun.jdi.ObjectReference; import com.sun.jdi.Value; /** * @author Vitaliy.Bibaev */ public class PrimitiveValueDescriptor extends InstanceValueDescriptor { PrimitiveValueDescriptor(Project project, Value value) { super(project, value); } @Override public String calcValueName() { final Value value = getValue(); if (value instanceof ObjectReference) { return super.calcValueName(); } return value.toString(); } @Override public PsiExpression getDescriptorEvaluation(DebuggerContext debuggerContext) throws EvaluateException { final Value value = getValue(); if (value instanceof ObjectReference) { return super.getDescriptorEvaluation(debuggerContext); } final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(myProject).getElementFactory(); return elementFactory.createExpressionFromText("", ContextUtil.getContextElement(debuggerContext)); } }
Prepend logs with date timestamp
'use strict'; /** * Imports. */ const express = require('express'); const winston = require('winston'); /** * Constants declarations. */ const LISTEN_PORT = process.env.LISTEN_PORT || 5050; const LOGGER_LEVEL = process.env.LOGGER_LEVEL || 'info'; const LOGGER_TIMESTAMP = !(process.env.LOGGER_TIMESTAMP === 'false'); /** * Dependencies initializations. */ const app = express(); // Logger: app.locals.logger = new winston.Logger({ transports: [ new winston.transports.Console({ prettyPrint: true, colorize: true, level: LOGGER_LEVEL, timestamp: LOGGER_TIMESTAMP, }), ], exceptionHandlers: [ new winston.transports.Console({ prettyPrint: true, colorize: true }), ], }); // Just a shortcut. const logger = app.locals.logger; app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(LISTEN_PORT, () => { logger.info(`Blink is listening on port:${LISTEN_PORT} env:${app.get('env')}`); }); module.exports = app;
'use strict'; /** * Imports. */ const express = require('express'); const winston = require('winston'); /** * Constants declarations. */ const LISTEN_PORT = process.env.LISTEN_PORT || 5050; const LOGGING_LEVEL = process.env.LOGGING_LEVEL || 'info'; /** * Dependencies initializations. */ const app = express(); // Logger: app.locals.logger = new winston.Logger({ transports: [ new winston.transports.Console({ prettyPrint: true, colorize: true, level: LOGGING_LEVEL }), ], exceptionHandlers: [ new winston.transports.Console({ prettyPrint: true, colorize: true }), ], }); // Just a shortcut. const logger = app.locals.logger; app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(LISTEN_PORT, () => { logger.info(`Blink is listening on port:${LISTEN_PORT} env:${app.get('env')}`); }); module.exports = app;
Refactor to use Java 8 stream
package main.doge.service; import main.doge.service.domain.Todo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; @Service public class TodoService { private final RestTemplate restTemplate; private final String uri; @Autowired public TodoService(RestTemplate restTemplate, @Value("${doge.service.uri}") String uri) { this.restTemplate = restTemplate; this.uri = uri; } public List<Todo> getTodos() { return Arrays.stream(callService(uri + "/todos", Todo[].class)).collect(Collectors.toList()); } public Todo getSingleTodo(int todoId) { return callService(uri + "/todo/" + Integer.toString(todoId), Todo.class); } private <T> T callService(String uri, Class<T> type) { return restTemplate.getForObject(uri, type); } }
package main.doge.service; import main.doge.service.domain.Todo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import java.util.Arrays; import java.util.List; @Service public class TodoService { private final RestTemplate restTemplate; private final String uri; @Autowired public TodoService(RestTemplate restTemplate, @Value("${doge.service.uri}") String uri) { this.restTemplate = restTemplate; this.uri = uri; } public List<Todo> getTodos() { return Arrays.asList(callService(uri + "/todos", Todo[].class)); } public Todo getSingleTodo(int todoId) { return callService(uri + "/todo/" + Integer.toString(todoId), Todo.class); } private <T> T callService(String uri, Class<T> type) { return restTemplate.getForObject(uri, type); } }
Fix for import error with matplotlib Qt4Agg backend
# # Plot.py -- Plotting function for Ginga FITS viewer. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # # GUI imports from ginga.qtw.QtHelp import QtGui, QtCore from ginga.qtw import QtHelp from ginga.toolkit import toolkit import matplotlib if toolkit == 'qt5': # qt5 backend is not yet released in matplotlib stable from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg \ as FigureCanvas else: from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg \ as FigureCanvas from ginga.base.PlotBase import PlotBase, HistogramMixin, CutsMixin class Plot(PlotBase): def __init__(self, logger, width=300, height=300, dpi=100): PlotBase.__init__(self, logger, FigureCanvas, width=width, height=height, dpi=dpi) class Histogram(Plot, HistogramMixin): pass class Cuts(Plot, CutsMixin): pass #END
# # Plot.py -- Plotting function for Ginga FITS viewer. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # # GUI imports from ginga.qtw.QtHelp import QtGui, QtCore from ginga.qtw import QtHelp from ginga.toolkit import toolkit import matplotlib if toolkit in ('qt', 'qt4'): from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg \ as FigureCanvas elif toolkit == 'qt5': # qt5 backend is not yet released in matplotlib stable from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg \ as FigureCanvas from ginga.base.PlotBase import PlotBase, HistogramMixin, CutsMixin class Plot(PlotBase): def __init__(self, logger, width=300, height=300, dpi=100): PlotBase.__init__(self, logger, FigureCanvas, width=width, height=height, dpi=dpi) class Histogram(Plot, HistogramMixin): pass class Cuts(Plot, CutsMixin): pass #END
Allow slug to be passed directly into the view
from django.views.generic import ListView, DetailView from .models import Post class PostListView(ListView): context_object_name = 'posts' model = Post template_name = 'hermes/post_list.html' def get_queryset(self): return self.model.objects.order_by('created_on') class CategoryPostListView(PostListView): slug = None def get_queryset(self): category_slug = self.kwargs.get('slug', None) if category_slug is None: category_slug = self.slug return self.model.objects.in_category(category_slug) class ArchivePostListView(PostListView): def get_queryset(self): year = self.kwargs.get('year', None) month = self.kwargs.get('month', None) day = self.kwargs.get('day', None) return self.model.objects.created_on(year=year, month=month, day=day) class PostDetail(DetailView): context_object_name = 'post' model = Post template_name = "hermes/post_detail.html"
from django.views.generic import ListView, DetailView from .models import Post class PostListView(ListView): context_object_name = 'posts' model = Post template_name = 'hermes/post_list.html' def get_queryset(self): return self.model.objects.order_by('created_on') class CategoryPostListView(PostListView): slug = None def get_queryset(self): category_slug = self.kwargs.get('slug', '') return self.model.objects.in_category(category_slug) class ArchivePostListView(PostListView): def get_queryset(self): year = self.kwargs.get('year', None) month = self.kwargs.get('month', None) day = self.kwargs.get('day', None) return self.model.objects.created_on(year=year, month=month, day=day) class PostDetail(DetailView): context_object_name = 'post' model = Post template_name = "hermes/post_detail.html"
Test properties from originalObj, not newObj
jest.dontMock('../Util'); var Util = require('../Util'); describe('Util', function() { describe('#extend', function () { beforeEach(function () { this.originalObj = { a: 5, b: 10, c: 15 }; }); it('should not change any properties if passed a single argument', function () { var newObj = Util.extend(this.originalObj); for (var key in this.originalObj) { expect(newObj[key]).toEqual(this.originalObj[key]); } }); it('should combine properties with the source', function () { var source = { a: 'changed prop' }; var newObj = Util.extend(this.originalObj, source); expect(newObj.a).toEqual('changed prop'); }); it('should handle multiple arguments', function () { var obj1 = { a: 'changed prop', b: 'changed prop' }; var obj2 = { a: 'overrode prop' }; var newObj = Util.extend(this.originalObj, obj1, obj2); expect(newObj.a).toEqual('overrode prop'); expect(newObj.b).toEqual('changed prop'); }); }); });
jest.dontMock('../Util'); var Util = require('../Util'); describe('Util', function() { describe('#extend', function () { beforeEach(function () { this.originalObj = { a: 5, b: 10, c: 15 }; }); it('should not change any properties if passed a single argument', function () { var newObj = Util.extend(this.originalObj); for (var key in newObj) { expect(newObj[key]).toEqual(this.originalObj[key]); } }); it('should combine properties with the source', function () { var source = { a: 'changed prop' }; var newObj = Util.extend(this.originalObj, source); expect(newObj.a).toEqual('changed prop'); }); it('should handle multiple arguments', function () { var obj1 = { a: 'changed prop', b: 'changed prop' }; var obj2 = { a: 'overrode prop' }; var newObj = Util.extend(this.originalObj, obj1, obj2); expect(newObj.a).toEqual('overrode prop'); expect(newObj.b).toEqual('changed prop'); }); }); });
tornado: Remove a misleading comment and reformat. tornado.web.Application does not share any inheritance with Django at all; it has a similar router interface, but tornado.web.Application is not an instance of Django anything. Refold the long lines that follow it.
import atexit import tornado.web from django.conf import settings from zerver.lib.queue import get_queue_client from zerver.tornado import autoreload from zerver.tornado.handlers import AsyncDjangoHandler def setup_tornado_rabbitmq() -> None: # nocoverage # When tornado is shut down, disconnect cleanly from rabbitmq if settings.USING_RABBITMQ: queue_client = get_queue_client() atexit.register(lambda: queue_client.close()) autoreload.add_reload_hook(lambda: queue_client.close()) def create_tornado_application() -> tornado.web.Application: urls = ( r"/notify_tornado", r"/json/events", r"/api/v1/events", r"/api/v1/events/internal", ) return tornado.web.Application( [(url, AsyncDjangoHandler) for url in urls], debug=settings.DEBUG, autoreload=False, # Disable Tornado's own request logging, since we have our own log_function=lambda x: None )
import atexit import tornado.web from django.conf import settings from zerver.lib.queue import get_queue_client from zerver.tornado import autoreload from zerver.tornado.handlers import AsyncDjangoHandler def setup_tornado_rabbitmq() -> None: # nocoverage # When tornado is shut down, disconnect cleanly from rabbitmq if settings.USING_RABBITMQ: queue_client = get_queue_client() atexit.register(lambda: queue_client.close()) autoreload.add_reload_hook(lambda: queue_client.close()) def create_tornado_application() -> tornado.web.Application: urls = ( r"/notify_tornado", r"/json/events", r"/api/v1/events", r"/api/v1/events/internal", ) # Application is an instance of Django's standard wsgi handler. return tornado.web.Application([(url, AsyncDjangoHandler) for url in urls], debug=settings.DEBUG, autoreload=False, # Disable Tornado's own request logging, since we have our own log_function=lambda x: None)
Fix long description loading on python 2.7
#!/usr/bin/env python from setuptools.depends import get_module_constant from setuptools import setup with open("README.md", "r") as fh: long_description = fh.read() setup( name = 'detectlanguage', packages = ['detectlanguage'], version = get_module_constant('detectlanguage', '__version__'), description = 'Language Detection API Client', long_description=long_description, long_description_content_type="text/markdown", author = 'Laurynas Butkus', author_email = 'info@detectlanguage.com', url = 'https://github.com/detectlanguage/detectlanguage-python', download_url = 'https://github.com/detectlanguage/detectlanguage-python', keywords = ['language', 'identification', 'detection', 'api', 'client'], install_requires= ['requests>=2.4.2'], classifiers = [], license = 'MIT', )
#!/usr/bin/env python from setuptools.depends import get_module_constant from setuptools import setup with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() setup( name = 'detectlanguage', packages = ['detectlanguage'], version = get_module_constant('detectlanguage', '__version__'), description = 'Language Detection API Client', long_description=long_description, long_description_content_type="text/markdown", author = 'Laurynas Butkus', author_email = 'info@detectlanguage.com', url = 'https://github.com/detectlanguage/detectlanguage-python', download_url = 'https://github.com/detectlanguage/detectlanguage-python', keywords = ['language', 'identification', 'detection', 'api', 'client'], install_requires= ['requests>=2.4.2'], classifiers = [], license = 'MIT', )
INF-155: Allow multiple arguments to be passed to phapp exec.
<?php namespace drunomics\Phapp\Commands; use League\Container\ContainerAwareTrait; use Robo\Common\IO; use Robo\LoadAllTasks; use Symfony\Component\Console\Question\ChoiceQuestion; /** * Class ExecCommand. */ class ExecCommand { use ContainerAwareTrait; use LoadAllTasks; use IO; /** * Executes commands based on the environment. * * @param string $exec_command The command to execute. * @param string[] $arguments The command arguments. * * @command exec */ public function execCommand($exec_command, array $arguments) { $currentpath = realpath(getcwd()); if ($strpos = strpos($currentpath, "vcs/web")) { $projectpath = substr($currentpath, 0, $strpos); $project = basename($projectpath); // Detect vagrant environment if (file_exists($projectpath . '.vagrant')) { $exec_command = "docker exec " . $project . " " . $exec_command; } else { // Use the wrapper script for drush. if ($exec_command == "drush") { $exec_command = $projectpath . "/vcs/web/drush.wrapper"; } } $this->_exec($exec_command . ' ' . implode(' ', $arguments)); } else { print("You need to be in the web directory to execute this command.\n"); } } }
<?php namespace drunomics\Phapp\Commands; use League\Container\ContainerAwareTrait; use Robo\Common\IO; use Robo\LoadAllTasks; use Symfony\Component\Console\Question\ChoiceQuestion; /** * Class ExecCommand. */ class ExecCommand { use ContainerAwareTrait; use LoadAllTasks; use IO; /** * Executes commands based on the environment. * * @command exec */ public function execCommand($name) { $currentpath = realpath(getcwd()); if ($strpos = strpos($currentpath, "vcs/web")) { $projectpath = substr($currentpath, 0, $strpos); $project = basename($projectpath); // Detect vagrant environment if (file_exists($projectpath . '.vagrant')) { $command = "docker exec " . $project . " " . $name; } else { // Use the wrapper script for drush. if ($name == "drush") { $command = $projectpath . "/vcs/web/drush.wrapper"; } else { $command = $name; } } $this->_exec($command); } else { print("You need to be in the web directory to execute this command.\n"); } } }
Add python compatibility tags for 2.7 and 3.6
from setuptools import setup, find_packages requirements = [ 'boto>=2.8.0,<3.0', ] setup( name='celery-s3', version='0.1', description='An S3 result store backend for Celery', long_description=open('README.md').read(), author='Rob Golding', author_email='rob@robgolding.com', license='BSD', url='https://github.com/robgolding63/celery-s3', download_url='https://github.com/robgolding63/celery-s3/downloads', packages=find_packages(), include_package_data=True, install_requires=requirements, tests_require=requirements + [ 'celery==4.1.0', ], test_suite='celery_s3.tests', classifiers=[ 'Development Status :: 3 - Alpha', 'Programming Language :: Python', "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.6", 'License :: OSI Approved :: BSD License', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: System :: Distributed Computing', 'Programming Language :: Python', 'Operating System :: OS Independent', ], )
from setuptools import setup, find_packages requirements = [ 'boto>=2.8.0,<3.0', ] setup( name='celery-s3', version='0.1', description='An S3 result store backend for Celery', long_description=open('README.md').read(), author='Rob Golding', author_email='rob@robgolding.com', license='BSD', url='https://github.com/robgolding63/celery-s3', download_url='https://github.com/robgolding63/celery-s3/downloads', packages=find_packages(), include_package_data=True, install_requires=requirements, tests_require=requirements + [ 'celery==4.1.0', ], test_suite='celery_s3.tests', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: BSD License', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: System :: Distributed Computing', 'Programming Language :: Python', 'Operating System :: OS Independent', ], )
Add comment for graphql fragment
/* global window */ import ApolloClient from 'apollo-client'; import { withClientState } from 'apollo-link-state'; import { from } from 'apollo-link'; import getGraphqlFragments from './getGraphqlFragments'; import buildNetworkComponents from './buildNetworkComponents'; import buildCache from './buildCache'; import Config from 'lib/Config'; const buildClient = async (baseUrl) => { const graphQLConfig = Config.getSection('SilverStripe\\Admin\\LeftAndMain').graphql; const cachedTypenames = graphQLConfig && graphQLConfig.cachedTypenames; let fragmentData; // GraphQL may not return what we want (e.g. if schema is empty, so fail gracefully) try { fragmentData = await getGraphqlFragments(baseUrl, cachedTypenames); } catch (e) { fragmentData = null; } const cache = buildCache(fragmentData); const components = buildNetworkComponents(baseUrl); const stateLink = withClientState({ cache, resolvers: {} }); const link = from([stateLink, ...components]); return new ApolloClient({ cache, link }); }; export default buildClient;
/* global window */ import ApolloClient from 'apollo-client'; import { withClientState } from 'apollo-link-state'; import { from } from 'apollo-link'; import getGraphqlFragments from './getGraphqlFragments'; import buildNetworkComponents from './buildNetworkComponents'; import buildCache from './buildCache'; import Config from 'lib/Config'; const buildClient = async (baseUrl) => { const graphQLConfig = Config.getSection('SilverStripe\\Admin\\LeftAndMain').graphql; const cachedTypenames = graphQLConfig && graphQLConfig.cachedTypenames; let fragmentData; try { fragmentData = await getGraphqlFragments(baseUrl, cachedTypenames); } catch (e) { fragmentData = null; } const cache = buildCache(fragmentData); const components = buildNetworkComponents(baseUrl); const stateLink = withClientState({ cache, resolvers: {} }); const link = from([stateLink, ...components]); return new ApolloClient({ cache, link }); }; export default buildClient;
Write a function to update data
/* * Cepat Sembuh v1.0 * Copyright 2016 Cepat Sembuh */ // Firebase go online whenever the application is open document.addEventListener("deviceready", function () { Firebase.goOnline(); }); // Not available faskes $('#not-available').on('click', function() { alert("Faskes is not available") }) // Get no antrian function function getNoAntri(tipe, username, name) { var faskesRef = new Firebase("https://cepatsembuh.firebaseio.com/" + tipe + "/faskes/" + username + '/antrian'); console.log('Url :' + "https://cepatsembuh.firebaseio.com/" + tipe + "/faskes/" + username + '/antrian'); alert('Fitur ini membutuhkan internet untuk mengambil data'); faskesRef.on("value", function(snapshot) { alert('No antrian: ' + snapshot.val()); }); } function updateData(tipe, username, name) { var faskesRef = new Firebase("https://cepatsembuh.firebaseio.com/" + tipe + "/faskes/" + username + '/antrian'); faskesRef.on("value", function(snapshot) { data = snapshot.val().antrian; plus = 1; glee = data + plus console.log('Updating data.. '); kelapa_gading.set({ antrian: glee, nama: name }); }) }
/* * Cepat Sembuh v1.0 * Copyright 2016 Cepat Sembuh */ // Firebase go online whenever the application is open document.addEventListener("deviceready", function () { Firebase.goOnline(); }); // Not available faskes $('#not-available').on('click', function() { alert("Faskes is not available") }) // Get no antrian function function getNoAntri(tipe, username, name) { var faskesRef = new Firebase("https://cepatsembuh.firebaseio.com/" + tipe + "/faskes/" + username + '/antrian'); console.log('Url :' + "https://cepatsembuh.firebaseio.com/" + tipe + "/faskes/" + username + '/antrian'); alert('Fitur ini membutuhkan internet untuk mengambil data'); faskesRef.on("value", function(snapshot) { alert('No antrian: ' + snapshot.val()); var data = snapshot.val().antrian; var plus = 1; var glee = data + plus console.log('Updating data.. '); username.set({ antrian: glee, nama: name }); }); }
Fix validate DB when DB is disabled and not connected
# TODO: Add private API with Redis Cache and PostgreSQL (or any SQL DB with SQLAlchemy) from api import api, cache, ENABLE_DB, db from flask import abort, Flask from flask_restful import Resource from os import getenv from api.resources.market import Data from api.resources.trend import Predict def setup_app(): app = Flask(__name__) if ENABLE_DB: db_uri = getenv('SQLALCHEMY_DATABASE_URI') # format: postgresql://user:pw@host:port/db if db_uri: app.config['SQLALCHEMY_DATABASE_URI'] = db_uri else: abort(401) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False with app.app_context(): api.init_app(app) return app def setup_db(application, sqlalchemy_bind, mem_cache=None): with application.app_context(): if mem_cache is not None: mem_cache.init_app(app) sqlalchemy_bind.init_app(app) sqlalchemy_bind.create_all() if __name__=='__main__': app = setup_app() if ENABLE_DB: from api.models import * # Load all DB models setup_db(app, db, mem_cache=cache) app.run(debug=True)
# TODO: Add private API with Redis Cache and PostgreSQL (or any SQL DB with SQLAlchemy) from api import api, cache, db from flask import abort, Flask from flask_restful import Resource from os import getenv from api.resources.market import Data from api.resources.trend import Predict def setup_app(): db_uri = getenv('SQLALCHEMY_DATABASE_URI') # format: postgresql://user:pw@host:port/db if not db_uri: abort(401) app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = db_uri app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False with app.app_context(): api.init_app(app) return app def setup_db(application, sqlalchemy_bind, mem_cache=None): with application.app_context(): if mem_cache is not None: mem_cache.init_app(app) sqlalchemy_bind.init_app(app) sqlalchemy_bind.create_all() if __name__=='__main__': app = setup_app() from api.models import * # Load all DB models setup_db(app, db, mem_cache=cache) app.run(debug=True)
Make this no-op migration be a true no-op.
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('student', '0009_auto_20170111_0422'), ] # This migration was to add a constraint that we lost in the Django # 1.4->1.8 upgrade. But since the constraint used to be created, production # would already have the constraint even before running the migration, and # running the migration would fail. We needed to make the migration # idempotent. Instead of reverting this migration while we did that, we # edited it to be a SQL no-op, so that people who had already applied it # wouldn't end up with a ghost migration. # It had been: # # migrations.RunSQL( # "create unique index email on auth_user (email);", # "drop index email on auth_user;" # ) operations = [ # Nothing to do. ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('student', '0009_auto_20170111_0422'), ] # This migration was to add a constraint that we lost in the Django # 1.4->1.8 upgrade. But since the constraint used to be created, production # would already have the constraint even before running the migration, and # running the migration would fail. We needed to make the migration # idempotent. Instead of reverting this migration while we did that, we # edited it to be a SQL no-op, so that people who had already applied it # wouldn't end up with a ghost migration. # It had been: # # migrations.RunSQL( # "create unique index email on auth_user (email);", # "drop index email on auth_user;" # ) operations = [ migrations.RunSQL( # Do nothing: "select 1", "select 1" ) ]
MOVE hooks to core group
import React from 'react'; import { useEffect, useRef, useState } from '@storybook/client-api'; export default { title: 'Core/Hooks', }; export const Checkbox = () => { const [on, setOn] = useState(false); return ( <label> <input type="checkbox" checked={on} onChange={(e) => setOn(e.target.checked)} /> On </label> ); }; export const Input = () => { const [text, setText] = useState('foo'); return <input value={text} onChange={(e) => setText(e.target.value)} />; }; export const Effect = () => { const ref = useRef(); useEffect(() => { if (ref.current != null) { ref.current.style.backgroundColor = 'yellow'; } }); return ( <button type="button" ref={ref}> I should be yellow </button> ); }; export const ReactHookCheckbox = () => { const [on, setOn] = React.useState(false); return ( <label> <input type="checkbox" checked={on} onChange={(e) => setOn(e.target.checked)} /> On </label> ); };
import React from 'react'; import { useEffect, useRef, useState } from '@storybook/client-api'; export default { title: 'Hooks', }; export const Checkbox = () => { const [on, setOn] = useState(false); return ( <label> <input type="checkbox" checked={on} onChange={(e) => setOn(e.target.checked)} /> On </label> ); }; export const Input = () => { const [text, setText] = useState('foo'); return <input value={text} onChange={(e) => setText(e.target.value)} />; }; export const Effect = () => { const ref = useRef(); useEffect(() => { if (ref.current != null) { ref.current.style.backgroundColor = 'yellow'; } }); return ( <button type="button" ref={ref}> I should be yellow </button> ); }; export const ReactHookCheckbox = () => { const [on, setOn] = React.useState(false); return ( <label> <input type="checkbox" checked={on} onChange={(e) => setOn(e.target.checked)} /> On </label> ); };
Add polyfill for older browsers, so Opera 12 works
<section id="loading-shadow" hidden="hidden"> <div class="loading-wrapper"> <div class="loading-content"> <h3>Updating List Item...</h3> <div class="cssload-loader"> <div class="cssload-inner cssload-one"></div> <div class="cssload-inner cssload-two"></div> <div class="cssload-inner cssload-three"></div> </div> </div> </div> </section> <script nomodule src="https://polyfill.io/v3/polyfill.min.js?features=es5%2CObject.assign"></script> <?php if ($auth->isAuthenticated()): ?> <script nomodule async="async" defer="defer" src="<?= $urlGenerator->assetUrl('js/scripts-authed.min.js') ?>"></script> <script type="module" src="<?= $urlGenerator->assetUrl('js/src/index-authed.js') ?>"></script> <?php else: ?> <script nomodule async="async" defer="defer" src="<?= $urlGenerator->assetUrl('js/scripts.min.js') ?>"></script> <script type="module" src="<?= $urlGenerator->assetUrl('js/src/index.js') ?>"></script> <?php endif ?> </body> </html>
<section id="loading-shadow" hidden="hidden"> <div class="loading-wrapper"> <div class="loading-content"> <h3>Updating List Item...</h3> <div class="cssload-loader"> <div class="cssload-inner cssload-one"></div> <div class="cssload-inner cssload-two"></div> <div class="cssload-inner cssload-three"></div> </div> </div> </div> </section> <?php if ($auth->isAuthenticated()): ?> <script nomodule async="async" defer="defer" src="<?= $urlGenerator->assetUrl('js/scripts-authed.min.js') ?>"></script> <script type="module" src="<?= $urlGenerator->assetUrl('js/src/index-authed.js') ?>"></script> <?php else: ?> <script nomodule async="async" defer="defer" src="<?= $urlGenerator->assetUrl('js/scripts.min.js') ?>"></script> <script type="module" src="<?= $urlGenerator->assetUrl('js/src/index.js') ?>"></script> <?php endif ?> </body> </html>
dblog: Allow event saving by id
# -*- coding: utf-8 -*- from logging import Handler from datetime import datetime class DBLogHandler(Handler, object): def __init__(self): super(DBLogHandler, self).__init__() def emit(self, record): from models import DBLogEntry as _LogEntry entry = _LogEntry() entry.level = record.levelname entry.message = self.format(record) entry.module = record.name try: entry.event = record.event except: try: entry.event_id = record.event_id except: pass try: entry.user = record.user except: pass entry.save()
# -*- coding: utf-8 -*- from logging import Handler from datetime import datetime class DBLogHandler(Handler, object): def __init__(self): super(DBLogHandler, self).__init__() def emit(self, record): from models import DBLogEntry as _LogEntry entry = _LogEntry() entry.level = record.levelname entry.message = self.format(record) entry.module = record.name try: entry.event = record.event except: pass try: entry.user = record.user except: pass entry.save()
Fix directory "Copy name" function
'use babel'; const init = () => { const contextMenu = { '.remote-ftp-view .entries.list-tree:not(.multi-select) .directory': { enabled: atom.config.get('remote-ftp.context.enableCopyFilename'), command: [{ label: 'Copy name', command: 'remote-ftp:copy-name', }, { type: 'separator', }], }, '.remote-ftp-view .entries.list-tree:not(.multi-select) .file': { enabled: atom.config.get('remote-ftp.context.enableCopyFilename'), command: [{ label: 'Copy filename', command: 'remote-ftp:copy-name', }, { type: 'separator', }], }, }; return contextMenu; }; export default init;
'use babel'; const init = () => { const copyEnabled = () => atom.config.get('remote-ftp.context.enableCopyFilename'); const contextMenu = { '.remote-ftp-view .entries.list-tree:not(.multi-select) .directory .header': { enabled: copyEnabled(), command: [{ label: 'Copy name', command: 'remote-ftp:copy-name', }, { type: 'separator', }], }, '.remote-ftp-view .entries.list-tree:not(.multi-select) .file': { enabled: copyEnabled(), command: [{ label: 'Copy filename', command: 'remote-ftp:copy-name', }, { type: 'separator', }], }, }; return contextMenu; }; export default init;
Change how weather forcast is inserted into the page
import { chainableClassList } from './libs/helpers'; import purify from './libs/purify-dom'; import { initializeSearch } from './modules/search'; import initializeHistory from './modules/history'; import loadOptions from './modules/options'; import loadNextImage from './modules/load-next-image'; import weatherInfo from './components/weather-info'; import main from './components/main'; import loader from './components/loader'; import footer from './components/footer'; import header from './components/header'; const body = document.getElementById('app'); body.insertAdjacentHTML('afterbegin', purify.sanitize(` ${loader()} ${header()} ${main()} ${footer()} `)); loadNextImage(); loadOptions(); initializeHistory(); initializeSearch(); chrome.storage.local.get('forecast', (result) => { const { forecast } = result; const weatherArea = document.getElementById('s-footer .weather'); if (forecast) { weatherArea.insertAdjacentHTML('afterbegin', purify.sanitize(weatherInfo(forecast), { ADD_TAGS: ['use'] })); } }); const uiElements = document.querySelectorAll('.s-ui'); uiElements.forEach(element => chainableClassList(element).remove('hidden')); document.addEventListener('click', (node) => { if (node.target.matches('.popover *')) return; const popover = document.querySelectorAll('.popover .popover-content'); popover.forEach(e => e.classList.remove('popover-content--is-visible')); });
import { chainableClassList } from './libs/helpers'; import purify from './libs/purify-dom'; import { initializeSearch } from './modules/search'; import initializeHistory from './modules/history'; import loadOptions from './modules/options'; import loadNextImage from './modules/load-next-image'; import weatherInfo from './components/weather-info'; import main from './components/main'; import loader from './components/loader'; import footer from './components/footer'; import header from './components/header'; const body = document.getElementById('app'); body.insertAdjacentHTML('afterbegin', purify.sanitize(` ${loader()} ${header()} ${main()} ${footer()} `)); loadNextImage(); loadOptions(); initializeHistory(); initializeSearch(); chrome.storage.local.get('forecast', (result) => { const { forecast } = result; if (forecast) { const footerComponent = document.getElementById('s-footer'); footerComponent.insertAdjacentHTML('afterbegin', purify.sanitize(weatherInfo(forecast), { ADD_TAGS: ['use'] })); } }); const uiElements = document.querySelectorAll('.s-ui'); uiElements.forEach(element => chainableClassList(element).remove('hidden')); document.addEventListener('click', (node) => { if (node.target.matches('.popover *')) return; const popover = document.querySelectorAll('.popover .popover-content'); popover.forEach(e => e.classList.remove('popover-content--is-visible')); });
Fix text for repeated events.
from django.db import models from django.utils.translation import ugettext_lazy as _ from mezzanine.core.models import Displayable, RichText class RepeatType(models.Model): DAILY = 'daily' WEEKLY = 'weekly', MONTHLY = 'monthly' REPEAT_CHOICES = ( (DAILY, _('Daily')), (WEEKLY, _('Weekly')), (MONTHLY, _('Monthly')) ) repeat_type = models.CharField(max_length=10, choices=REPEAT_CHOICES) class Event(Displayable, RichText): """ Main object for each event. Derives from Displayable, which by default - it is related to a certain Site object - it has a title and a slug - it has SEO metadata - it gets automated timestamps when the object is updated Besides that, it derives from RichText, which provides a WYSIWYG field. """ class Occurence(models.Model): """ Represents an occurence of an event. Can be automatically repeated """ start = models.DateTimeField() end = models.DateTimeField() repeat = models.ForeignKey(RepeatType, default=None, blank=True)
from django.db import models from mezzanine.core.models import Displayable, RichText class RepeatType(models.Model): DAILY = 'daily' WEEKLY = 'weekly', MONTHLY = 'monthly' REPEAT_CHOICES = ( (DAILY, 'REPEAT_DAILY'), (WEEKLY, 'REPEAT_WEEKLY'), (MONTHLY, 'REPEAT_MONTHLY') ) repeat_type = models.CharField(max_length=10, choices=REPEAT_CHOICES) class Event(Displayable, RichText): """ Main object for each event. Derives from Displayable, which by default - it is related to a certain Site object - it has a title and a slug - it has SEO metadata - it gets automated timestamps when the object is updated Besides that, it derives from RichText, which provides a WYSIWYG field. """ class Occurence(models.Model): """ Represents an occurence of an event. Can be automatically repeated """ start = models.DateTimeField() end = models.DateTimeField() repeat = models.ForeignKey(RepeatType, default=None, blank=True)
Check if input exists before remove
import PropertyIntegerView from './PropertyIntegerView'; import InputColor from 'domain_abstract/ui/InputColor'; export default PropertyIntegerView.extend({ setValue(value, opts = {}) { opts = { ...opts, silent: 1 }; this.inputInst.setValue(value, opts); }, remove() { PropertyIntegerView.prototype.remove.apply(this, arguments); const inp = this.inputInst; inp && inp.remove(); ['inputInst', '$color'].forEach(i => (this[i] = {})); }, onRender() { if (!this.input) { const ppfx = this.ppfx; const inputColor = new InputColor({ target: this.target, model: this.model, ppfx }); const input = inputColor.render(); this.el.querySelector(`.${ppfx}fields`).appendChild(input.el); this.$input = input.inputEl; this.$color = input.colorEl; this.input = this.$input.get(0); this.inputInst = input; } } });
import PropertyIntegerView from './PropertyIntegerView'; import InputColor from 'domain_abstract/ui/InputColor'; export default PropertyIntegerView.extend({ setValue(value, opts = {}) { opts = { ...opts, silent: 1 }; this.inputInst.setValue(value, opts); }, remove() { PropertyIntegerView.prototype.remove.apply(this, arguments); this.inputInst.remove(); ['inputInst', '$color'].forEach(i => (this[i] = {})); }, onRender() { if (!this.input) { const ppfx = this.ppfx; const inputColor = new InputColor({ target: this.target, model: this.model, ppfx }); const input = inputColor.render(); this.el.querySelector(`.${ppfx}fields`).appendChild(input.el); this.$input = input.inputEl; this.$color = input.colorEl; this.input = this.$input.get(0); this.inputInst = input; } } });
Hide category when not specified
{{-- Copyright 2015-2017 ppy Pty. Ltd. This file is part of osu!web. osu!web is distributed with the hope of attracting more community contributions to the core ecosystem of osu!. osu!web is free software: you can redistribute it and/or modify it under the terms of the Affero GNU General Public License version 3 as published by the Free Software Foundation. osu!web is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with osu!web. If not, see <http://www.gnu.org/licenses/>. --}} <div class="changelog__change changelog-change"> <div class="changelog-change__left"> <span class="changelog-change__icon fa fa-{{ build_icon($log->prefix) }}" title={{ trans('changelog.prefixes.'.$log->prefix) }}></span> <a href="{{route('users.show', ['user' => $log->user_id])}}" class="changelog-change__username">{{ $log->user->username }}</a> </div> <div class="changelog-change__right {{ $log->major === 1 ? 'changelog-change__right--major' : '' }}"> @if(presence($log->category) === true) {{ $log->category }}: @endif {{ $log->message }} </div> </div>
{{-- Copyright 2015-2017 ppy Pty. Ltd. This file is part of osu!web. osu!web is distributed with the hope of attracting more community contributions to the core ecosystem of osu!. osu!web is free software: you can redistribute it and/or modify it under the terms of the Affero GNU General Public License version 3 as published by the Free Software Foundation. osu!web is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with osu!web. If not, see <http://www.gnu.org/licenses/>. --}} <div class="changelog__change changelog-change"> <div class="changelog-change__left"> <span class="changelog-change__icon fa fa-{{ build_icon($log->prefix) }}" title={{ trans('changelog.prefixes.'.$log->prefix) }}></span> <a href="{{route('users.show', ['user' => $log->user_id])}}" class="changelog-change__username">{{ $log->user->username }}</a> </div> <div class="changelog-change__right {{ $log->major === 1 ? 'changelog-change__right--major' : '' }}"> {{ $log->category }}: {{ $log->message }} </div> </div>
Correct operation. Now to fix panda warnings
import json import pandas as pd def fn(row): if row['Type'] == 'DIRECT DEBIT': return 'DD' if row['Type'] == 'DIRECT CREDIT' or row['Spending Category'] == 'INCOME': return 'BP' if row['Amount (GBP)'] < 0: return 'SO' raise Exception('Unintended state') df = pd.read_csv('statement.csv') conversions = json.load(open('description_conversion.json')) output = df[['Date']] output['Type'] = df.apply(fn, axis=1) output['Description'] = (df['Counter Party'] + ' ' + df['Reference']).replace(conversions) output['Paid Out'] = df['Amount (GBP)'].copy() output['Paid In'] = df['Amount (GBP)'].copy() output['Paid Out'] = output['Paid Out'] * -1 output['Paid Out'][output['Paid Out'] < 0] = None output['Paid In'][output['Paid In'] < 0] = None output['Balance'] = df['Balance (GBP)'] output.to_csv('output.csv', index=False)
import pandas as pd def fn(row): if row['Type'] == 'DIRECT DEBIT': return 'DD' if row['Type'] == 'DIRECT CREDIT' or row['Spending Category'] == 'INCOME': return 'BP' if row['Amount (GBP)'] < 0: return 'SO' raise Exception('Unintended state') df = pd.read_csv('statement.csv') output = df[['Date']] output['Type'] = df.apply(fn, axis=1) output['Description'] = df['Reference'] output['Paid Out'] = df['Amount (GBP)'].copy() output['Paid In'] = df['Amount (GBP)'].copy() output['Paid Out'] = output['Paid Out'] * -1 output['Paid Out'][output['Paid Out'] < 0] = None output['Paid In'][output['Paid In'] < 0] = None output['Balance'] = df['Balance (GBP)'] print(output) output.to_csv('output.csv', index=False)
Switch doc to closure compiler templating
// http://stackoverflow.com/questions/11935175/sampling-a-random-subset-from-an-array var featureCollection = require('turf-featurecollection'); /** * Takes a {@link FeatureCollection} and returns a FeatureCollection with given number of {@link Feature|features} at random. * * @module turf/sample * @category data * @param {FeatureCollection<(Point|LineString|Polygon)>} features a FeatureCollection of any type * @param {Number} n number of features to select * @return {FeatureCollection<(Point|LineString|Polygon)>} a FeatureCollection with `n` features * @example * var points = turf.random('points', 1000); * * //=points * * var sample = turf.sample(points, 10); * * //=sample */ module.exports = function(fc, num){ var outFC = featureCollection(getRandomSubarray(fc.features, num)); return outFC; }; function getRandomSubarray(arr, size) { var shuffled = arr.slice(0), i = arr.length, min = i - size, temp, index; while (i-- > min) { index = Math.floor((i + 1) * Math.random()); temp = shuffled[index]; shuffled[index] = shuffled[i]; shuffled[i] = temp; } return shuffled.slice(min); }
// http://stackoverflow.com/questions/11935175/sampling-a-random-subset-from-an-array var featureCollection = require('turf-featurecollection'); /** * Takes a {@link FeatureCollection} and returns a FeatureCollection with given number of {@link Feature|features} at random. * * @module turf/sample * @category data * @param {FeatureCollection} features a FeatureCollection of any type * @param {number} n number of features to select * @return {FeatureCollection} a FeatureCollection with `n` features * @example * var points = turf.random('points', 1000); * * //=points * * var sample = turf.sample(points, 10); * * //=sample */ module.exports = function(fc, num){ var outFC = featureCollection(getRandomSubarray(fc.features, num)); return outFC; }; function getRandomSubarray(arr, size) { var shuffled = arr.slice(0), i = arr.length, min = i - size, temp, index; while (i-- > min) { index = Math.floor((i + 1) * Math.random()); temp = shuffled[index]; shuffled[index] = shuffled[i]; shuffled[i] = temp; } return shuffled.slice(min); }
Add license and remove comment in output files
var fs = require("fs"); var path = require("path"); var babel = require("babel"); var uglify = require("uglify-js"); var sourceDir = "src/"; var outputDir = "js/"; fs.readdir(sourceDir, function(err, files){ if(err){ throw err; } console.log("Packing code ..."); var license = "/** @license\n" + fs.readFileSync("LICENSE") + "*/\n\n"; var packedCode = ""; packedCode += "(window)=>{"; files.forEach(function(file, index, files){ console.log("Reading " + file + " ..."); packedCode += fs.readFileSync(path.join(sourceDir, file)); }); packedCode += "}(window);"; console.log("Compiling code ..."); var result = babel.transform(packedCode, {comments: false}); var outputPath = path.join(outputDir, "vnwe"); fs.writeFile(outputPath+".js", license+result.code, function(err){ if(err){ throw err; } console.log("Code has been compiled into vnwe.js !"); }); var minifiedCode = uglify.minify(result.code, {fromString: true}).code; fs.writeFile(outputPath+".min.js", license+minifiedCode, function(err){ if(err){ throw err; } console.log("Code has been minified into vnwe.min.js !"); }); });
var fs = require("fs"); var path = require("path"); var babel = require("babel"); var uglify = require("uglify-js"); var sourceDir = "src/"; var outputDir = "js/"; fs.readdir(sourceDir, function(err, files){ if(err){ throw err; } console.log("Packing code ..."); var packedCode = ""; packedCode += "(window)=>{"; files.forEach(function(file, index, files){ console.log("Reading " + file + " ..."); packedCode += fs.readFileSync(path.join(sourceDir, file)); }); packedCode += "}(window);"; console.log("Compiling code ..."); var result = babel.transform(packedCode); var outputPath = path.join(outputDir, "vnwe"); fs.writeFile(outputPath+".js", result.code, function(err){ if(err){ throw err; } console.log("Code has been compiled into vnwe.js !"); }); var minifiedCode = uglify.minify(result.code, {fromString: true}).code; fs.writeFile(outputPath+".min.js", minifiedCode, function (err) { if(err){ throw err; } console.log("Code has been minified into vnwe.min.js !"); }); });
Add note about default constructor
/* * Copyright 2014 Cask, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package co.cask.cdap.api.service; import co.cask.cdap.internal.service.DefaultServiceSpecification; /** * An abstract implementation of {@link Service}. Users may extend this to write a {@link Service}. * * The default no-op constructor must be implemented. */ public abstract class AbstractService implements Service { protected ServiceConfigurer configurer; @Override public final ServiceSpecification configure(ServiceConfigurer serviceConfigurer) { this.configurer = serviceConfigurer; configure(); return new DefaultServiceSpecification(getClass().getSimpleName(), configurer.getName(), configurer.getDescription(), configurer.getProperties(), configurer.getWorkers(), configurer.getHandlers()); } /** * Implement this method and use a {@link ServiceConfigurer} to add a request handler * and workers. */ protected abstract void configure(); }
/* * Copyright 2014 Cask, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package co.cask.cdap.api.service; import co.cask.cdap.internal.service.DefaultServiceSpecification; /** * An abstract implementation of {@link Service}. Users may extend this to write their own * custom service. */ public abstract class AbstractService implements Service { protected ServiceConfigurer configurer; @Override public final ServiceSpecification configure(ServiceConfigurer serviceConfigurer) { this.configurer = serviceConfigurer; configure(); return new DefaultServiceSpecification(getClass().getSimpleName(), configurer.getName(), configurer.getDescription(), configurer.getProperties(), configurer.getWorkers(), configurer.getHandlers()); } /** * Implement this method and use a {@link ServiceConfigurer} to add a request handler * and workers. */ protected abstract void configure(); }
Remove deprecated --optipng from glue options Optipng is now deprecated in glue, so including that option in Cactus doesn't really make sense. https://github.com/jorgebastida/glue/blob/master/docs/changelog.rst#09
import os import sys import pipes import shutil import subprocess """ This plugin uses glue to sprite images: http://glue.readthedocs.org/en/latest/quickstart.html Install: (Only if you want to sprite jpg too) brew install libjpeg sudo easy_install pip sudo pip uninstall pil sudo pip install pil sudo pip install glue """ try: import glue except Exception, e: sys.exit('Could not use glue: %s\nMaybe install: sudo easy_install glue' % e) IMG_PATH = 'static/img/sprites' CSS_PATH = 'static/css/sprites' KEY = '_PREV_CHECKSUM' def checksum(path): command = 'md5 `find %s -type f`' % pipes.quote(IMG_PATH) return subprocess.check_output(command, shell=True) def preBuild(site): currChecksum = checksum(IMG_PATH) prevChecksum = getattr(site, KEY, None) # Don't run if none of the images has changed if currChecksum == prevChecksum: return if os.path.isdir(CSS_PATH): shutil.rmtree(CSS_PATH) os.mkdir(CSS_PATH) os.system('glue --cachebuster --crop "%s" "%s" --project' % (IMG_PATH, CSS_PATH)) setattr(site, KEY, currChecksum)
import os import sys import pipes import shutil import subprocess """ This plugin uses glue to sprite images: http://glue.readthedocs.org/en/latest/quickstart.html Install: (Only if you want to sprite jpg too) brew install libjpeg (Only if you want to optimize pngs with optipng) brew install optipng sudo easy_install pip sudo pip uninstall pil sudo pip install pil sudo pip install glue """ try: import glue except Exception, e: sys.exit('Could not use glue: %s\nMaybe install: sudo easy_install glue' % e) IMG_PATH = 'static/img/sprites' CSS_PATH = 'static/css/sprites' KEY = '_PREV_CHECKSUM' def checksum(path): command = 'md5 `find %s -type f`' % pipes.quote(IMG_PATH) return subprocess.check_output(command, shell=True) def preBuild(site): currChecksum = checksum(IMG_PATH) prevChecksum = getattr(site, KEY, None) # Don't run if none of the images has changed if currChecksum == prevChecksum: return if os.path.isdir(CSS_PATH): shutil.rmtree(CSS_PATH) os.mkdir(CSS_PATH) os.system('glue --cachebuster --crop --optipng "%s" "%s" --project' % (IMG_PATH, CSS_PATH)) setattr(site, KEY, currChecksum)
Include 'scripts' as module in package.
from distutils.core import setup setup( name='Decouple', version='1.2.2', packages=['Decouple', 'Decouple.BatchPlugins', 'scripts'], license='LICENSE', description='Decouple and recouple.', long_description=open('README.md').read(), author='Sven Kreiss, Kyle Cranmer', author_email='sk@svenkreiss.com', install_requires= [ 'BatchLikelihoodScan', 'LHCHiggsCouplings', 'numpy', 'scipy', 'multiprocessing', 'progressbar', ], entry_points={ 'console_scripts': [ 'decouple = scripts.decouple:main', 'recouple = scripts.recouple:main', # decouple tools 'decouple_obtain_etas = Decouple.obtainEtas:main', # recouple tools 'recouple_mutmuw = Decouple.muTmuW:main', 'recouple_kvkf = Decouple.kVkF:main', 'recouple_kglukgamma = Decouple.kGlukGamma:main', ] } )
from distutils.core import setup setup( name='Decouple', version='1.2.1', packages=['Decouple', 'Decouple.BatchPlugins'], license='LICENSE', description='Decouple and recouple.', long_description=open('README.md').read(), author='Sven Kreiss, Kyle Cranmer', author_email='sk@svenkreiss.com', install_requires= [ 'BatchLikelihoodScan', 'LHCHiggsCouplings', 'numpy', 'scipy', 'multiprocessing', 'progressbar', ], entry_points={ 'console_scripts': [ 'decouple = scripts.decouple:main', 'recouple = scripts.recouple:main', # decouple tools 'decouple_obtain_etas = Decouple.obtainEtas:main', # recouple tools 'recouple_mutmuw = Decouple.muTmuW:main', 'recouple_kvkf = Decouple.kVkF:main', 'recouple_kglukgamma = Decouple.kGlukGamma:main', ] } )
Refactor `requireStrictEqualityOperators` to handle new token structure
var utils = require('../utils') module.exports = function () {} module.exports.prototype = { name: 'requireStrictEqualityOperators' , configure: function (options) { utils.validateTrueOptions(this.name, options) } , lint: function (file, errors) { file.iterateTokensByType([ 'if', 'else-if' ], function (token) { var regex = /([!=]=)(.)/ , match = token.val.match(regex) , operator if (match !== null) { operator = match[1] if (match[2] !== '=') { errors.add('Expected \'' + operator + '=\' and instead saw \'' + operator + '\'', token.line) } } }) } }
var utils = require('../utils') module.exports = function () {} module.exports.prototype = { name: 'requireStrictEqualityOperators' , configure: function (options) { utils.validateTrueOptions(this.name, options) } , lint: function (file, errors) { file.iterateTokensByFilter(function (token) { return token.type === 'code' && token.requiresBlock }, function (token) { var regex = /([!=]=)(.)/ , match = token.val.match(regex) , operator if (match !== null) { operator = match[1] if (match[2] !== '=') { errors.add('Expected \'' + operator + '=\' and instead saw \'' + operator + '\'', token.line) } } }) } }
BAP-8170: Use cron instead of buttons for synchronization
<?php namespace Oro\Bundle\LDAPBundle\DependencyInjection; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader; use Symfony\Component\HttpKernel\DependencyInjection\Extension; class OroLDAPExtension extends Extension { /** * {@inheritdoc} */ public function load(array $configs, ContainerBuilder $container) { $config = $this->processConfiguration(new Configuration(), $configs); $serviceLoader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); $serviceLoader->load('services.yml'); $serviceLoader->load('form.yml'); $serviceLoader->load('importexport.yml'); $container->prependExtensionConfig($this->getAlias(), array_intersect_key($config, array_flip(['settings']))); } /** * {@inheritdoc} */ public function getAlias() { return 'oro_ldap'; } }
<?php namespace Oro\Bundle\LDAPBundle\DependencyInjection; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader; use Symfony\Component\HttpKernel\DependencyInjection\Extension; class OroLDAPExtension extends Extension { /** * {@inheritdoc} */ public function load(array $configs, ContainerBuilder $container) { $config = $this->processConfiguration(new Configuration(), $configs); $serviceLoader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); $serviceLoader->load('services.yml'); $serviceLoader->load('form.yml'); $container->prependExtensionConfig($this->getAlias(), array_intersect_key($config, array_flip(['settings']))); } /** * {@inheritdoc} */ public function getAlias() { return 'oro_ldap'; } }
Handle 0 download counts in CLI
#!/usr/bin/env node var addCommas = require('add-commas') var columnify = require('columnify') var minimist = require('minimist') var npmme = require('./') var argv = minimist(process.argv.slice(2), { boolean: 'p' }) if (!argv._[0]) return console.error([ 'Usage:' , ' npm-me <username>' , ' npm-me -p <package>' ].join('\n')) // Individal package download counts if (argv.p) return npmme.pkg(argv._[0], function(err, count) { console.log() console.log(argv._[0] + ' ' + addCommas(count)) console.log() }) // Username package download counts npmme(argv._[0], function(err, downloads) { if (err) throw err downloads = downloads .filter(Boolean) .map(function(dl) { dl.count = Number(dl.count) || 0 return dl }) .sort(function(a, b) { return a.count - b.count }) console.log() console.log(columnify(downloads.map(function(dl) { return { name: dl.name , count: addCommas(dl.count) } }), {config: {count: {align: 'right'}}})) var total = downloads.reduce(function(total, dl) { return total + dl.count }, 0) console.log() console.log('Total ', addCommas(total)) })
#!/usr/bin/env node var addCommas = require('add-commas') var columnify = require('columnify') var minimist = require('minimist') var npmme = require('./') var argv = minimist(process.argv.slice(2), { boolean: 'p' }) if (!argv._[0]) return console.error([ 'Usage:' , ' npm-me <username>' , ' npm-me -p <package>' ].join('\n')) // Individal package download counts if (argv.p) return npmme.pkg(argv._[0], function(err, count) { console.log() console.log(argv._[0] + ' ' + addCommas(count)) console.log() }) // Username package download counts npmme(argv._[0], function(err, downloads) { if (err) throw err downloads = downloads .filter(Boolean) .map(function(dl) { dl.count = Number(dl.count) return dl }) .sort(function(a, b) { return a.count - b.count }) console.log() console.log(columnify(downloads.map(function(dl) { return { name: dl.name , count: addCommas(dl.count) } }), {config: {count: {align: 'right'}}})) var total = downloads.reduce(function(total, dl) { return total + dl.count }, 0) console.log() console.log('Total ', addCommas(total)) })
Use "Border Patrol" in the title
package uk.co.alynn.games.ld30.desktop; import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; import uk.co.alynn.games.ld30.SpaceHams; import uk.co.alynn.games.ld30.world.Constants; public class DesktopLauncher { public static void main (String[] arg) { LwjglApplicationConfiguration config = new LwjglApplicationConfiguration(); config.width = Constants.STANDARD_RES_WIDTH; config.height = Constants.STANDARD_RES_HEIGHT; config.samples = 2; config.vSyncEnabled = true; config.title = "Border Patrol"; config.resizable = true; config.fullscreen = false; new LwjglApplication(new SpaceHams(), config); } }
package uk.co.alynn.games.ld30.desktop; import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; import uk.co.alynn.games.ld30.SpaceHams; import uk.co.alynn.games.ld30.world.Constants; public class DesktopLauncher { public static void main (String[] arg) { LwjglApplicationConfiguration config = new LwjglApplicationConfiguration(); config.width = Constants.STANDARD_RES_WIDTH; config.height = Constants.STANDARD_RES_HEIGHT; config.samples = 2; config.vSyncEnabled = true; config.title = "Space Hams"; config.resizable = true; config.fullscreen = false; new LwjglApplication(new SpaceHams(), config); } }
Allow to pass null for cache handler
<?php namespace Tmdb\SymfonyBundle; use Doctrine\Common\Cache\Cache; use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\HttpFoundation\ParameterBag; use Tmdb\ConfigurationInterface; class ClientConfiguration extends ParameterBag implements ConfigurationInterface { /** * @param EventDispatcherInterface $eventDispatcher * @param array $options */ public function __construct( EventDispatcherInterface $eventDispatcher, array $options = [] ){ $this->parameters = $options; $this->parameters['event_dispatcher'] = $eventDispatcher; } public function setCacheHandler(Cache $handler = null) { $this->parameters['cache']['handler'] = $handler; } /** * @return array */ public function all() { return $this->parameters; } }
<?php namespace Tmdb\SymfonyBundle; use Doctrine\Common\Cache\Cache; use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\HttpFoundation\ParameterBag; use Tmdb\ConfigurationInterface; class ClientConfiguration extends ParameterBag implements ConfigurationInterface { /** * @param EventDispatcherInterface $eventDispatcher * @param array $options */ public function __construct( EventDispatcherInterface $eventDispatcher, array $options = [] ){ $this->parameters = $options; $this->parameters['event_dispatcher'] = $eventDispatcher; } public function setCacheHandler(Cache $handler) { $this->parameters['cache']['handler'] = $handler; } /** * @return array */ public function all() { return $this->parameters; } }
feat(Lazyload): Append alt to large image from small image.
(function () { var ctrl = new ScrollMagic.Controller(); $(document).ready(function () { $('.lazyload-wrapper').each(function () { var wrapper = this, small = wrapper.querySelector('.lazyload-small'); var img = new Image(); img.src = small.src; img.onload = function () { small.classList.add('loaded'); }; }); $('.lazyload-wrapper .lazyload-small').each(function () { var currentImage = this; new ScrollMagic.Scene( { triggerElement: currentImage, offset: (-document.documentElement.clientHeight / 2) }) .on('enter', function () { var wrapper = this.triggerElement().parentElement; var alt = this.triggerElement().getAttribute('alt'); var imgLarge = new Image(); imgLarge.src = wrapper.dataset.srcLg; imgLarge.alt = alt; imgLarge.onload = function () { imgLarge.classList.add('loaded'); }; wrapper.appendChild(imgLarge); }) .addTo(ctrl); }); }); })();
(function () { var ctrl = new ScrollMagic.Controller(); $(document).ready(function () { $('.lazyload-wrapper').each(function () { var wrapper = this, small = wrapper.querySelector('.lazyload-small'); var img = new Image(); img.src = small.src; img.onload = function () { small.classList.add('loaded'); }; }); $('.lazyload-wrapper .lazyload-small').each(function () { var currentImage = this; new ScrollMagic.Scene( { triggerElement: currentImage, offset: (-document.documentElement.clientHeight / 2) }) .on('enter', function () { var wrapper = this.triggerElement().parentElement; var imgLarge = new Image(); imgLarge.src = wrapper.dataset.srcLg; imgLarge.onload = function () { imgLarge.classList.add('loaded'); }; wrapper.appendChild(imgLarge); }) .addTo(ctrl); }); }); })();
Fix so that onClick in adapters get the correct item
package io.blushine.android.ui.list; import android.support.v7.widget.RecyclerView; /** * Edit an item by long clicking on it */ class ClickFunctionality<T> implements PostBindFunctionality<T> { private ClickListener<T> mListener; ClickFunctionality(ClickListener<T> listener) { if (listener == null) { throw new IllegalArgumentException("listener is null"); } mListener = listener; } @Override public void applyFunctionality(AdvancedAdapter<T, ?> adapter, RecyclerView recyclerView) { // Does nothing } @Override public void onPostBind(final AdvancedAdapter<T, ?> adapter, RecyclerView.ViewHolder viewHolder, int position) { viewHolder.itemView.setOnClickListener(view -> { int adapterPosition = viewHolder.getAdapterPosition(); T item = adapter.getItem(adapterPosition); mListener.onClick(item); }); } }
package io.blushine.android.ui.list; import android.support.v7.widget.RecyclerView; import android.view.View; /** * Edit an item by long clicking on it */ class ClickFunctionality<T> implements PostBindFunctionality<T> { private ClickListener<T> mListener; public ClickFunctionality(ClickListener<T> listener) { if (listener == null) { throw new IllegalArgumentException("listener is null"); } mListener = listener; } @Override public void applyFunctionality(AdvancedAdapter<T, ?> adapter, RecyclerView recyclerView) { // Does nothing } @Override public void onPostBind(final AdvancedAdapter<T, ?> adapter, RecyclerView.ViewHolder viewHolder, final int position) { viewHolder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { T item = adapter.getItem(position); mListener.onClick(item); } }); } }
Allow dots as well :rocket:
// Dependencies var types = require("./core") , constructors = require("./constructors") , iterateObject = require("iterate-object") , ul = require("ul") , typpy = require("typpy") , regexEscape = require("regex-escape") ; // Initialize the Engine Types object var EngineTypes = module.exports = {}; EngineTypes._prefixes = {}; // Add the constructors iterateObject(types, (value, name) => { var t = EngineTypes[value.constructor_name] = constructors[value.constructor_name]; if (!t) { throw new Error("There is no constructor with this name: " + name); } // Append the _prefixes iterateObject(value.types, (cType, typeName) => { if (!cType.char) { return; } EngineTypes._prefixes[cType.char] = { func: t , type: typeName }; }); iterateObject(ul.merge({ name: name }, value), function (v, n) { if (n === "chars" && typpy(v, String)) { v = { normal: v }; } t[n] = v; }); }); EngineTypes._prefixesRegex = new RegExp( `^(${Object.keys(EngineTypes._prefixes).map(regexEscape).join("|")})[A-Za-z0-9_\.]` , "i" );
// Dependencies var types = require("./core") , constructors = require("./constructors") , iterateObject = require("iterate-object") , ul = require("ul") , typpy = require("typpy") , regexEscape = require("regex-escape") ; // Initialize the Engine Types object var EngineTypes = module.exports = {}; EngineTypes._prefixes = {}; // Add the constructors iterateObject(types, (value, name) => { var t = EngineTypes[value.constructor_name] = constructors[value.constructor_name]; if (!t) { throw new Error("There is no constructor with this name: " + name); } // Append the _prefixes iterateObject(value.types, (cType, typeName) => { if (!cType.char) { return; } EngineTypes._prefixes[cType.char] = { func: t , type: typeName }; }); iterateObject(ul.merge({ name: name }, value), function (v, n) { if (n === "chars" && typpy(v, String)) { v = { normal: v }; } t[n] = v; }); }); EngineTypes._prefixesRegex = new RegExp( `^(${Object.keys(EngineTypes._prefixes).map(regexEscape).join("|")})[A-Za-z0-9_]` , "i" );
Fix bling() and add in info function to report target & sender.
import pyrc import pyrc.utils.hooks as hooks class GangstaBot(pyrc.Bot): @hooks.command() def info(self, target, sender): "will print the target and sender to the console" print("target: %s, sender: %s" % (target, sender)) @hooks.command() def bling(self, target, sender): "will print yo" if target.startswith("#"): self.message(target, "%s: yo" % sender) else: self.message(sender, "yo") @hooks.command("^repeat\s+(?P<msg>.+)$") def repeat(self, target, sender, **kwargs): "will repeat whatever yo say" if target.startswith("#"): self.message(target, kwargs["msg"]) else: self.message(sender, kwargs["msg"]) @hooks.privmsg("(lol|lmao|rofl(mao)?)") def stopword(self, target, sender, *args): """ will repeat 'lol', 'lmao, 'rofl' or 'roflmao' when seen in a message only applies to channel messages """ if target.startswith("#"): self.message(target, args[0]) @hooks.interval(10000) def keeprepeating(self): "will say something" self.message("#turntechgodhead", "stop repeating myself") if __name__ == '__main__': bot = GangstaBot('irc.freenode.net', channels = ['#turntechgodhead']) bot.connect()
import pyrc import pyrc.utils.hooks as hooks class GangstaBot(pyrc.Bot): @hooks.command() def bling(self, target, sender): "will print yo" if target.startswith("#"): self.message(target, "%s: yo" % sender) else: self.message(target, "yo") @hooks.command("^repeat\s+(?P<msg>.+)$") def repeat(self, target, sender, **kwargs): "will repeat whatever yo say" if target.startswith("#"): self.message(target, kwargs["msg"]) else: self.message(sender, kwargs["msg"]) @hooks.privmsg("(lol|lmao|rofl(mao)?)") def stopword(self, target, sender, *args): """ will repeat 'lol', 'lmao, 'rofl' or 'roflmao' when seen in a message only applies to channel messages """ if target.startswith("#"): self.message(target, args[0]) @hooks.interval(10000) def keeprepeating(self): "will say something" self.message("#turntechgodhead", "stop repeating myself") if __name__ == '__main__': bot = GangstaBot('irc.freenode.net', channels = ['#turntechgodhead']) bot.connect()
utils: Implement utils.List type with a Contains() method
package utils import "sync" // ConcurrentSlice type that can be safely shared between goroutines type ConcurrentSlice struct { sync.RWMutex items []interface{} } // ConcurrentSliceItem contains the index/value pair of an item in a // concurrent slice type ConcurrentSliceItem struct { Index int Value interface{} } // NewConcurrentSlice creates a new concurrent slice func NewConcurrentSlice() *ConcurrentSlice { cs := &ConcurrentSlice{ items: make([]interface{}, 0), } return cs } // Append adds an item to the concurrent slice func (cs *ConcurrentSlice) Append(item interface{}) { cs.Lock() defer cs.Unlock() cs.items = append(cs.items, item) } // Iter iterates over the items in the concurrent slice // Each item is sent over a channel, so that // we can iterate over the slice using the builin range keyword func (cs *ConcurrentSlice) Iter() <-chan ConcurrentSliceItem { c := make(chan ConcurrentSliceItem) f := func() { cs.Lock() defer cs.Lock() for index, value := range cs.items { c <- ConcurrentSliceItem{index, value} } close(c) } go f() return c } // List type represents a slice of strings type List []string // Contains returns a boolean indicating whether the list // contains the given string. func (l List) Contains(x string) bool { for _, v := range l { if v == x { return true } } return false }
package utils import "sync" // ConcurrentSlice type that can be safely shared between goroutines type ConcurrentSlice struct { sync.RWMutex items []interface{} } // ConcurrentSliceItem contains the index/value pair of an item in a // concurrent slice type ConcurrentSliceItem struct { Index int Value interface{} } // NewConcurrentSlice creates a new concurrent slice func NewConcurrentSlice() *ConcurrentSlice { cs := &ConcurrentSlice{ items: make([]interface{}, 0), } return cs } // Append adds an item to the concurrent slice func (cs *ConcurrentSlice) Append(item interface{}) { cs.Lock() defer cs.Unlock() cs.items = append(cs.items, item) } // Iter iterates over the items in the concurrent slice // Each item is sent over a channel, so that // we can iterate over the slice using the builin range keyword func (cs *ConcurrentSlice) Iter() <-chan ConcurrentSliceItem { c := make(chan ConcurrentSliceItem) f := func() { cs.Lock() defer cs.Lock() for index, value := range cs.items { c <- ConcurrentSliceItem{index, value} } close(c) } go f() return c }
Use json and not simplejson
import json from django import http class JSONResponseMixin(object): context_variable = 'object_list' def render_to_response(self, context): "Returns a JSON response containing 'context' as payload" return self.get_json_response(self.convert_context_to_json(context)) def dispatch(self, *args, **kwargs): return super(JSONResponseMixin, self).dispatch(*args, **kwargs) def post(self, *args, **kwargs): return self.get(self, *args, **kwargs) def get_json_response(self, content, **httpresponse_kwargs): "Construct an `HttpResponse` object." return http.HttpResponse(content, content_type='application/json', **httpresponse_kwargs) def convert_context_to_json(self, context): "Convert the context dictionary into a JSON object" # Note: This is *EXTREMELY* naive; in reality, you'll need # to do much more complex handling to ensure that arbitrary # objects -- such as Django model instances or querysets # -- can be serialized as JSON. if self.context_variable is not None: return json.dumps(context.get(self.context_variable, None)) return json.dumps(context)
from django import http from django.utils import simplejson as json class JSONResponseMixin(object): context_variable = 'object_list' def render_to_response(self, context): "Returns a JSON response containing 'context' as payload" return self.get_json_response(self.convert_context_to_json(context)) def dispatch(self, *args, **kwargs): return super(JSONResponseMixin, self).dispatch(*args, **kwargs) def post(self, *args, **kwargs): return self.get(self, *args, **kwargs) def get_json_response(self, content, **httpresponse_kwargs): "Construct an `HttpResponse` object." return http.HttpResponse(content, content_type='application/json', **httpresponse_kwargs) def convert_context_to_json(self, context): "Convert the context dictionary into a JSON object" # Note: This is *EXTREMELY* naive; in reality, you'll need # to do much more complex handling to ensure that arbitrary # objects -- such as Django model instances or querysets # -- can be serialized as JSON. if self.context_variable is not None: return json.dumps(context.get(self.context_variable, None)) return json.dumps(context)
Use `login_required` decorator on `switch_builder` view
from .models import FormBuilderPreference from django.http import HttpResponseRedirect from django.core.management import call_command from django.contrib.auth.decorators import login_required @login_required def switch_builder(request): ''' very un-restful, but for ease of testing, a quick 'GET' is hard to beat ''' if 'beta' in request.GET: beta_val = request.GET.get('beta') == '1' (pref, created) = FormBuilderPreference.objects.get_or_create( user=request.user) pref.preferred_builder = FormBuilderPreference.KPI if beta_val \ else FormBuilderPreference.DKOBO pref.save() if 'migrate' in request.GET: call_command( 'import_survey_drafts_from_dkobo', username=request.user.username) return HttpResponseRedirect('/')
from rest_framework.decorators import api_view from rest_framework.response import Response from .models import FormBuilderPreference from django.http import HttpResponseRedirect from django.core.management import call_command @api_view(['GET']) def switch_builder(request): ''' very un-restful, but for ease of testing, a quick 'GET' is hard to beat ''' if not request.user.is_authenticated(): raise exceptions.NotAuthenticated() if 'beta' in request.GET: beta_val = request.GET.get('beta') == '1' (pref, created) = FormBuilderPreference.objects.get_or_create( user=request.user) pref.preferred_builder = FormBuilderPreference.KPI if beta_val \ else FormBuilderPreference.DKOBO pref.save() if 'migrate' in request.GET: call_command( 'import_survey_drafts_from_dkobo', username=request.user.username) return HttpResponseRedirect('/')
Modify output on index page
$(function () { $('#search_movie').submit(function(){ var $form = $(this); var movieName = $form.children('#movie_name_input').val(); var movieYear = $form.children('#movie_year_input').val(); var apiUrl = $form.attr('action') + "/" + movieYear + "/" + movieName; $.get(apiUrl, function(movie){ var movie_html = ""; movie_html += "<h3>" + movie.name + " (" + movie.info.year + ")</h3>"; movie_html += '<img src="' + movie.info.poster + '">'; movie_html += "<h4>Combined Rating: " + movie.combined_rating + "</h4>"; var movie_ratings = "<h4>Ratings: </h4>"; $.each(movie.ratings, function(rating_site, rating) { movie_ratings += '<h4><a href="' + rating.url + '">'; movie_ratings += rating_site + '</a>:</h4> ' + rating.score; }); movie_html += movie_ratings; $('#result').html(movie_html); }); return false; }); });
$(function () { $('#search_movie').submit(function(){ var $form = $(this); var movieName = $form.children('#movie_name_input').val(); var movieYear = $form.children('#movie_year_input').val(); var apiUrl = $form.attr('action') + "/" + movieYear + "/" + movieName; $.get(apiUrl, function(movie){ var movie_html = ""; movie_html += "<h3>" + movie.name + "(" + movie.info.year + ")</h3>"; movie_html += '<img src="' + movie.info.poster + '">'; movie_html += "<h4>Combined Rating: " + movie.combined_rating + "</h4>"; var movie_ratings = "<h4>Ratings: </h4>"; $.each(movie.ratings, function(rating_site, rating) { movie_ratings += "<h4>" + rating_site + ":</h4>"; $.each(rating, function(key, value) { movie_ratings += "<p>"; movie_ratings += "<b>" + key + "</b>: " + value; }); }); movie_html += movie_ratings; $('#result').html(movie_html); }); return false; }); });
Use "Français" instead of "French".
<?php namespace Qia; use Flarum\Support\Extension as BaseExtension; use Illuminate\Events\Dispatcher; use Flarum\Events\RegisterLocales; class Extension extends BaseExtension { public function listen(Dispatcher $events) { $events->listen(RegisterLocales::class, function (RegisterLocales $event) { $event->manager->addLocale('fr', 'Français'); $event->manager->addJsFile('fr', __DIR__.'/../locale/core.js'); $event->manager->addConfig('fr', __DIR__.'/../locale/core.php'); $event->addTranslations('fr', __DIR__.'/../locale/core.yml'); $event->addTranslations('fr', __DIR__.'/../locale/likes.yml'); $event->addTranslations('fr', __DIR__.'/../locale/lock.yml'); $event->addTranslations('fr', __DIR__.'/../locale/mentions.yml'); $event->addTranslations('fr', __DIR__.'/../locale/pusher.yml'); $event->addTranslations('fr', __DIR__.'/../locale/sticky.yml'); $event->addTranslations('fr', __DIR__.'/../locale/subscriptions.yml'); $event->addTranslations('fr', __DIR__.'/../locale/tags.yml'); }); } }
<?php namespace Qia; use Flarum\Support\Extension as BaseExtension; use Illuminate\Events\Dispatcher; use Flarum\Events\RegisterLocales; class Extension extends BaseExtension { public function listen(Dispatcher $events) { $events->listen(RegisterLocales::class, function (RegisterLocales $event) { $event->manager->addLocale('fr', 'French'); $event->addTranslations('fr', __DIR__.'/../locale/core.yml'); $event->manager->addJsFile('fr', __DIR__.'/../locale/core.js'); $event->manager->addConfig('fr', __DIR__.'/../locale/core.php'); $event->addTranslations('fr', __DIR__.'/../locale/likes.yml'); $event->addTranslations('fr', __DIR__.'/../locale/lock.yml'); $event->addTranslations('fr', __DIR__.'/../locale/mentions.yml'); $event->addTranslations('fr', __DIR__.'/../locale/pusher.yml'); $event->addTranslations('fr', __DIR__.'/../locale/sticky.yml'); $event->addTranslations('fr', __DIR__.'/../locale/subscriptions.yml'); $event->addTranslations('fr', __DIR__.'/../locale/tags.yml'); }); } }
Revert "Create a Serializer in the Constructor of Persistent Drivers" This reverts commit f7f1c77fdf40c1fafa69a80195a19ef932949f8b.
<?php /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Driver; use PMG\Queue\Envelope; use PMG\Queue\Serializer\Serializer; use PMG\Queue\Serializer\NativeSerializer; /** * Base class for drivers that deal with persistent backends. This provides * some utilities for serialization. * * @since 2.0 */ abstract class AbstractPersistanceDriver implements \PMG\Queue\Driver { /** * @var Serializer */ private $serializer; public function __construct(Serializer $serializer=null) { $this->serializer = $serializer; } protected function serialize(Envelope $env) { return $this->getSerializer()->serialize($env); } protected function unserialize($data) { return $this->getSerializer()->unserialize($data); } protected function getSerializer() { if (!$this->serializer) { $this->serializer = new NativeSerializer(); } return $this->serializer; } }
<?php /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Driver; use PMG\Queue\Envelope; use PMG\Queue\Serializer\Serializer; use PMG\Queue\Serializer\NativeSerializer; /** * Base class for drivers that deal with persistent backends. This provides * some utilities for serialization. * * @since 2.0 */ abstract class AbstractPersistanceDriver implements \PMG\Queue\Driver { /** * @var Serializer */ private $serializer; public function __construct(Serializer $serializer=null) { $this->serializer = $serializer ?: static::createDefaultSerializer(); } protected function serialize(Envelope $env) { return $this->getSerializer()->serialize($env); } protected function unserialize($data) { return $this->getSerializer()->unserialize($data); } protected function getSerializer() { return $this->serializer; } protected static function createDefaultSerializer() { return new NativeSerializer(); } }
Fix for the api at root url.
from django.conf.urls import url, include from rest_framework import routers from api import views router = routers.DefaultRouter() router.register(r'categories', views.CategoryViewSet) router.register(r'commodities', views.CommodityViewSet) router.register(r'economies', views.EconomyViewSet) router.register(r'factions', views.FactionViewSet) router.register(r'governments', views.GovernmentViewSet) router.register(r'allegiances', views.AllegianceViewSet) router.register(r'states', views.StateViewSet) router.register(r'securities', views.SecurityViewSet) router.register(r'systems', views.SystemViewSet) router.register(r'station_types', views.StationTypeViewSet) router.register(r'stations', views.StationViewSet) router.register(r'listings', views.ListingViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ]
from django.conf.urls import url, include from rest_framework import routers from api import views router = routers.DefaultRouter() router.register(r'categories', views.CategoryViewSet) router.register(r'commodities', views.CommodityViewSet) router.register(r'economies', views.EconomyViewSet) router.register(r'factions', views.FactionViewSet) router.register(r'governments', views.GovernmentViewSet) router.register(r'allegiances', views.AllegianceViewSet) router.register(r'states', views.StateViewSet) router.register(r'securities', views.SecurityViewSet) router.register(r'systems', views.SystemViewSet) router.register(r'station_types', views.StationTypeViewSet) router.register(r'stations', views.StationViewSet) router.register(r'listings', views.ListingViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ url(r'^/', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ]
Simplify initialization function of bytes.Buffer
/* Copyright 2017 The Kubernetes 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 template import ( "bytes" "sync" ) // BufferPool defines a Pool of Buffers type BufferPool struct { sync.Pool } // NewBufferPool creates a new BufferPool with a custom buffer size func NewBufferPool(s int) *BufferPool { return &BufferPool{ Pool: sync.Pool{ New: func() interface{} { b := bytes.NewBuffer(make([]byte, 0, s)) return b }, }, } } // Get returns a Buffer from the pool func (bp *BufferPool) Get() *bytes.Buffer { return bp.Pool.Get().(*bytes.Buffer) } // Put resets ans returns a Buffer to the pool func (bp *BufferPool) Put(b *bytes.Buffer) { b.Reset() bp.Pool.Put(b) }
/* Copyright 2017 The Kubernetes 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 template import ( "bytes" "sync" ) // BufferPool defines a Pool of Buffers type BufferPool struct { sync.Pool } // NewBufferPool creates a new BufferPool with a custom buffer size func NewBufferPool(s int) *BufferPool { return &BufferPool{ Pool: sync.Pool{ New: func() interface{} { b := bytes.NewBuffer(make([]byte, s)) b.Reset() return b }, }, } } // Get returns a Buffer from the pool func (bp *BufferPool) Get() *bytes.Buffer { return bp.Pool.Get().(*bytes.Buffer) } // Put resets ans returns a Buffer to the pool func (bp *BufferPool) Put(b *bytes.Buffer) { b.Reset() bp.Pool.Put(b) }
:art: Set a more verbose key in transformText
'use babel' import {transform as babelTransform} from 'flint-babel-core' import {Parser} from '../compiler' import {transformPlugin, getBabelConfig} from '../helpers' const NEWLINE_REGEX = /\r\n|\n|\r/g export const POSITION_TYPE = { VIEW_TOP: 'VIEW_TOP', VIEW_JSX: 'VIEW_JSX', STYLE: 'STYLE' } export function transformText(text, { log = null, writeStyle = null, onMeta = null, onImports = null, onExports = null }) { let toReturn = '' // Setting this key so it's easier to distinguish in debug output Parser.pre('__editor__', text, function(text) { toReturn = babelTransform(text, getBabelConfig({ log, writeStyle, onMeta, onImports, onExports })) }) transformPlugin.disposeLast() return toReturn } export function pointWithinRange(point, range) { return point.isGreaterThan(range[0]) && point.isLessThan(range[1]) } export function getObjectAtPosition(objects, position) { for (const key in objects) { const value = objects[key] if (pointWithinRange(position, value.location)) { return value } } return null } export function getRowFromText(text, row) { const rowText = text.split(NEWLINE_REGEX)[row] return rowText || '' }
'use babel' import {transform as babelTransform} from 'flint-babel-core' import {Parser} from '../compiler' import {transformPlugin, getBabelConfig} from '../helpers' const NEWLINE_REGEX = /\r\n|\n|\r/g export const POSITION_TYPE = { VIEW_TOP: 'VIEW_TOP', VIEW_JSX: 'VIEW_JSX', STYLE: 'STYLE' } export function transformText(text, { log = null, writeStyle = null, onMeta = null, onImports = null, onExports = null }) { let toReturn = '' Parser.pre('unknown', text, function(text) { toReturn = babelTransform(text, getBabelConfig({ log, writeStyle, onMeta, onImports, onExports })) }) transformPlugin.disposeLast() return toReturn } export function pointWithinRange(point, range) { return point.isGreaterThan(range[0]) && point.isLessThan(range[1]) } export function getObjectAtPosition(objects, position) { for (const key in objects) { const value = objects[key] if (pointWithinRange(position, value.location)) { return value } } return null } export function getRowFromText(text, row) { const rowText = text.split(NEWLINE_REGEX)[row] return rowText || '' }
Improve smoke test coverage for the logger.
""" Test the logger module. """ # Author: Gael Varoquaux <gael dot varoquaux at normalesup dot org> # Copyright (c) 2009 Gael Varoquaux # License: BSD Style, 3 clauses. import shutil import os from tempfile import mkdtemp import nose from ..logger import PrintTime ################################################################################ # Test fixtures def setup(): """ Test setup. """ global cachedir cachedir = mkdtemp() #cachedir = 'foobar' if os.path.exists(cachedir): shutil.rmtree(cachedir) os.makedirs(cachedir) def teardown(): """ Test teardown. """ #return True shutil.rmtree(cachedir) ################################################################################ # Tests def smoke_test_print_time(): """ A simple smoke test for PrintTime. """ print_time = PrintTime(logfile=os.path.join(cachedir, 'test.log')) print_time('Foo') # Create a second time, to smoke test log rotation. print_time = PrintTime(logfile=os.path.join(cachedir, 'test.log')) print_time('Foo')
""" Test the logger module. """ # Author: Gael Varoquaux <gael dot varoquaux at normalesup dot org> # Copyright (c) 2009 Gael Varoquaux # License: BSD Style, 3 clauses. import shutil import os from tempfile import mkdtemp import nose from ..logger import PrintTime ################################################################################ # Test fixtures def setup(): """ Test setup. """ global cachedir cachedir = mkdtemp() #cachedir = 'foobar' if os.path.exists(cachedir): shutil.rmtree(cachedir) os.makedirs(cachedir) def teardown(): """ Test teardown. """ #return True shutil.rmtree(cachedir) ################################################################################ # Tests def smoke_test_print_time(): """ A simple smoke test for PrintTime. """ print_time = PrintTime(logfile=os.path.join(cachedir, 'test.log')) print_time('Foo')
Add test implementation for custom cookie name
import { createCookieStore } from '../../src/storage' import Cookie from 'js-cookie' describe('cookie store', () => { describe('#persist', () => { it('returns resolved promise', () => { const cookieStore = createCookieStore() expect(cookieStore.persist()).resolves }) it('saves data to cookie with default key', () => { const cookieStore = createCookieStore() const spy = jest.spyOn(Cookie, 'set') cookieStore.persist({ key: 'value' }) expect(spy).toHaveBeenCalledWith( 'redux-simple-auth-session', { key: 'value' }, { domain: null, expires: null, path: '/', secure: false } ) }) it('allows a configured cookie name', () => { const cookieStore = createCookieStore({ name: 'my-cookie-session' }) const spy = jest.spyOn(Cookie, 'set') cookieStore.persist({ key: 'value' }) expect(spy).toHaveBeenCalledWith( 'my-cookie-session', { key: 'value' }, { domain: null, expires: null, path: '/', secure: false } ) }) xit('allows a custom path') xit('allows a custom domain') xit('allows setting expiration') xit('allows setting secure cookie') }) })
import { createCookieStore } from '../../src/storage' import Cookie from 'js-cookie' describe('cookie store', () => { describe('#persist', () => { it('returns resolved promise', () => { const cookieStore = createCookieStore() expect(cookieStore.persist()).resolves }) it('saves data to cookie with default key', () => { const cookieStore = createCookieStore() const spy = jest.spyOn(Cookie, 'set') cookieStore.persist({ key: 'value' }) expect(spy).toHaveBeenCalledWith( 'redux-simple-auth-session', { key: 'value' }, { domain: null, expires: null, path: '/', secure: false } ) }) xit('allows a configured cookie name') xit('allows a custom path') xit('allows a custom domain') xit('allows setting expiration') xit('allows setting secure cookie') }) })
Convert relative apiURL paths to absolute paths
var url = require("url"); var packageJSON = require("../../../package.json"); var config = { // @@ENV gets replaced by build system environment: "@@ENV", // If the UI is served through a proxied URL, this can be set here. rootUrl: "", // Defines the Marathon API URL, // leave empty to use the same as the UI is served. apiURL: "../", // Intervall of API request in ms updateInterval: 5000, // Local http server URI while tests run localTestserverURI: { address: "localhost", port: 8181 }, version: ("@@TEAMCITY_UI_VERSION".indexOf("@@TEAMCITY") === -1) ? "@@TEAMCITY_UI_VERSION" : `${packageJSON.version}-SNAPSHOT` }; if (process.env.GULP_ENV === "development") { try { var configDev = require("./config.dev"); config = Object.assign(config, configDev); } catch (e) { console.info("You could copy config.template.js to config.dev.js " + "to enable a development configuration."); } } // Convert relative URLs to absolute URLs for node-fetch if (global.document != null) { if (config.apiURL.indexOf(":") === -1) { config.apiURL = url.resolve( document.location.origin, document.location.pathname + config.apiURL ); } } module.exports = config;
var packageJSON = require("../../../package.json"); var config = { // @@ENV gets replaced by build system environment: "@@ENV", // If the UI is served through a proxied URL, this can be set here. rootUrl: "", // Defines the Marathon API URL, // leave empty to use the same as the UI is served. apiURL: "../", // Intervall of API request in ms updateInterval: 5000, // Local http server URI while tests run localTestserverURI: { address: "localhost", port: 8181 }, version: ("@@TEAMCITY_UI_VERSION".indexOf("@@TEAMCITY") === -1) ? "@@TEAMCITY_UI_VERSION" : `${packageJSON.version}-SNAPSHOT` }; if (process.env.GULP_ENV === "development") { try { var configDev = require("./config.dev"); config = Object.assign(config, configDev); } catch (e) { console.info("You could copy config.template.js to config.dev.js " + "to enable a development configuration."); } } module.exports = config;
Fix naming issue in objectify test case
import copy import unittest import utils class ObjectifyTestCase(unittest.TestCase): def setUp(self): self.o = utils.objectify() def test_bool_empty(self): self.assertFalse(self.o) def test_bool_not_empty(self): self.o['hello'] = 'world' self.assertTrue(self.o) def test_bool_false(self): self.o['hello'] = 'world' self.o['_bool'] = False self.assertFalse(self.o) def test_bool_true(self): self.o['_bool'] = True self.assertTrue(self.o) def test_dict(self): d = {'hello': 'world', 'thanks': 'mom'} o = utils.objectify(copy.deepcopy(d)) self.assertEqual(len(o), len(d)) for key, value in d.items(): self.assertEqual(o[key], value) self.assertEqual(getattr(o, key), value) self.assertEqual(unicode(o), unicode(d)) self.assertEqual(str(o), str(d)) if __name__ == '__main__': unittest.main()
import copy import unittest import utils class ObjectifyTestCase(unittest.TestCase): def setUp(self): self.o = utils.Objectify() def test_bool_empty(self): self.assertFalse(self.o) def test_bool_not_empty(self): self.o['hello'] = 'world' self.assertTrue(self.o) def test_bool_false(self): self.o['hello'] = 'world' self.o['_bool'] = False self.assertFalse(self.o) def test_bool_true(self): self.o['_bool'] = True self.assertTrue(self.o) def test_dict(self): d = {'hello': 'world', 'thanks': 'mom'} o = utils.Objectify(copy.deepcopy(d)) self.assertEqual(len(o), len(d)) for key, value in d.items(): self.assertEqual(o[key], value) self.assertEqual(getattr(o, key), value) self.assertEqual(unicode(o), unicode(d)) self.assertEqual(str(o), str(d)) if __name__ == '__main__': unittest.main()
Fix the image masking in HaralickTexture
from . import Measurement import feature_extraction.util.cleanup as cleanup from skimage.morphology import binary_erosion, disk class HaralickTexture(Measurement): default_options = { 'clip_cell_borders': True, 'erode_cell': False, 'erode_cell_amount': False, } def __init__(self, options=None): super(HaralickTexture, self).__init__(options) def compute(self, image): # -- preprocessing if self.options.clip_cell_borders: # get the cell boundary mask mask = cleanup.cell_boundary_mask(image) # if we're told to, erode the mask with a disk by some amount if self.options.erode_cell: mask = binary_erosion(cleanup.cell_boundary_mask(), disk(self.options.erode_cell_amount)) # mask the image # TODO(liam): we can probably use scipy.MaskedArray to get a speedup here image = image.copy() image[~mask] = 0 # set everything *outside* the cell to 0 # -- haralick setup and run return []
from . import Measurement import feature_extraction.util.cleanup as cleanup from skimage.morphology import binary_erosion, disk class HaralickTexture(Measurement): default_options = { 'clip_cell_borders': True, 'erode_cell': False, 'erode_cell_amount': False, } def __init__(self, options=None): super(HaralickTexture, self).__init__(options) def compute(self, image): # -- preprocessing if self.options.clip_cell_borders: # get the cell boundary mask mask = cleanup.cell_boundary_mask(image) # if we're told to, erode the mask with a disk by some amount if self.options.erode_cell: mask = binary_erosion(cleanup.cell_boundary_mask(), disk(self.options.erode_cell_amount)) # mask the image image = image[mask] # -- haralick setup and run return []
Add missing migrations to package.
# coding: utf-8 from os.path import join, dirname from setuptools import setup with open(join(dirname(__file__), 'README.rst')) as f: long_description = f.read() setup( name='django-speedinfo', version='1.0.1', packages=['speedinfo', 'speedinfo.migrations'], include_package_data=True, install_requires=['Django>=1.10'], license='MIT', description='Live profiling tool for Django framework to measure views performance', long_description=long_description, url='https://github.com/catcombo/django-speedinfo', author='Evgeniy Krysanov', author_email='evgeniy.krysanov@gmail.com', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Environment :: Web Environment', 'Framework :: Django', 'Framework :: Django :: 1.10', 'Framework :: Django :: 1.11', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], keywords='django profiler views performance', )
# coding: utf-8 from os.path import join, dirname from setuptools import setup with open(join(dirname(__file__), 'README.rst')) as f: long_description = f.read() setup( name='django-speedinfo', version='1.0.1', packages=['speedinfo'], include_package_data=True, install_requires=['Django>=1.10'], license='MIT', description='Live profiling tool for Django framework to measure views performance', long_description=long_description, url='https://github.com/catcombo/django-speedinfo', author='Evgeniy Krysanov', author_email='evgeniy.krysanov@gmail.com', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Environment :: Web Environment', 'Framework :: Django', 'Framework :: Django :: 1.10', 'Framework :: Django :: 1.11', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], keywords='django profiler views performance', )
Use String.prototype.startsWith() instead of includes() for checking the content type
"use strict"; var Response = function(error, res) { res = res || {}; this.raw = res.body; this.headers = res.headers; this.status = res.statusCode || 500; if (error) { this._error = { error: (res.body || "Unknown error: empty response") }; } else { if (res.headers["content-type"].startsWith("application/json")) { try { this.json = res.body ? JSON.parse(res.body) : {}; } catch (ex) { this._error = { error: ex.toString() }; } } } }; Response.prototype.error = function() { if (!this._error && this.isError()) { this._error = this.json || {}; } return this._error; }; Response.prototype.isError = function() { return (this._error || this.isClientError() || this.isServerError()); }; Response.prototype.isSuccess = function() { return !this.isError(); }; Response.prototype.isClientError = function() { return this.status >= 400 && this.status < 500; }; Response.prototype.isServerError = function() { return this.status >= 500; }; module.exports = Response;
"use strict"; var Response = function(error, res) { res = res || {}; this.raw = res.body; this.headers = res.headers; this.status = res.statusCode || 500; if (error) { this._error = { error: (res.body || "Unknown error: empty response") }; } else { if (res.headers["content-type"].includes("application/json")) { try { this.json = res.body ? JSON.parse(res.body) : {}; } catch (ex) { this._error = { error: ex.toString() }; } } } }; Response.prototype.error = function() { if (!this._error && this.isError()) { this._error = this.json || {}; } return this._error; }; Response.prototype.isError = function() { return (this._error || this.isClientError() || this.isServerError()); }; Response.prototype.isSuccess = function() { return !this.isError(); }; Response.prototype.isClientError = function() { return this.status >= 400 && this.status < 500; }; Response.prototype.isServerError = function() { return this.status >= 500; }; module.exports = Response;
Return error not empty list when dnsprovider returns an error.
/* Copyright 2016 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package clouddns import ( "k8s.io/kubernetes/federation/pkg/dnsprovider" "k8s.io/kubernetes/federation/pkg/dnsprovider/providers/google/clouddns/internal/interfaces" ) type Zones struct { impl interfaces.ManagedZonesService interface_ *Interface } func (zones Zones) List() ([]dnsprovider.Zone, error) { response, err := zones.impl.List(zones.project()).Do() if err != nil { return nil, err } managedZones := response.ManagedZones() zoneList := make([]dnsprovider.Zone, len(managedZones)) for i, zone := range managedZones { zoneList[i] = &Zone{zone, &zones} } return zoneList, nil } func (zones Zones) project() string { return zones.interface_.project() }
/* Copyright 2016 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package clouddns import ( "k8s.io/kubernetes/federation/pkg/dnsprovider" "k8s.io/kubernetes/federation/pkg/dnsprovider/providers/google/clouddns/internal/interfaces" ) type Zones struct { impl interfaces.ManagedZonesService interface_ *Interface } func (zones Zones) List() ([]dnsprovider.Zone, error) { response, err := zones.impl.List(zones.project()).Do() if err != nil { return []dnsprovider.Zone{}, nil } managedZones := response.ManagedZones() zoneList := make([]dnsprovider.Zone, len(managedZones)) for i, zone := range managedZones { zoneList[i] = &Zone{zone, &zones} } return zoneList, nil } func (zones Zones) project() string { return zones.interface_.project() }
Add license header to migration
<?php // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. use Illuminate\Database\Migrations\Migration; class AddExternalContestType extends Migration { /** * Run the migrations. * * @return void */ public function up() { DB::statement("ALTER TABLE contests CHANGE type type ENUM( 'art', 'beatmap', 'music', 'external' )"); } /** * Reverse the migrations. * * @return void */ public function down() { DB::statement("ALTER TABLE contests CHANGE type type ENUM( 'art', 'beatmap', 'music' )"); } }
<?php use Illuminate\Database\Migrations\Migration; class AddExternalContestType extends Migration { /** * Run the migrations. * * @return void */ public function up() { DB::statement("ALTER TABLE contests CHANGE type type ENUM( 'art', 'beatmap', 'music', 'external' )"); } /** * Reverse the migrations. * * @return void */ public function down() { DB::statement("ALTER TABLE contests CHANGE type type ENUM( 'art', 'beatmap', 'music' )"); } }
Delete 'board_slug' in 'view_post' url
# Created by JHJ on 2016. 10. 5. from django.conf.urls import url from . import views app_name = 'board' urlpatterns = [ url(r'^$', views.board_list, name='board_list'), url(r'^(?P<board_slug>[-a-z]+)/$', views.post_list, name='post_list'), url(r'^(?P<board_slug>[-a-z]+)/new/$', views.new_post, name='new_post'), url(r'^(?P<post_id>\d+)/delete/$', views.delete_post, name='delete_post'), url(r'^(?P<post_id>\d+)/$', views.view_post, name='view_post'), url(r'^(?P<board_slug>[-a-z]+)/(?P<post_id>\d+)/comment/new/$', views.new_comment, name='new_comment'), url(r'^(?P<post_id>\d+)/comment/delete/$', views.delete_comment, name='delete_comment'), ]
# Created by JHJ on 2016. 10. 5. from django.conf.urls import url from . import views app_name = 'board' urlpatterns = [ url(r'^$', views.board_list, name='board_list'), url(r'^(?P<board_slug>[-a-z]+)/$', views.post_list, name='post_list'), url(r'^(?P<board_slug>[-a-z]+)/new/$', views.new_post, name='new_post'), url(r'^(?P<post_id>\d+)/delete/$', views.delete_post, name='delete_post'), url(r'^(?P<board_slug>[-a-z]+)/(?P<post_id>\d+)/$', views.view_post, name='view_post'), url(r'^(?P<board_slug>[-a-z]+)/(?P<post_id>\d+)/comment/new/$', views.new_comment, name='new_comment'), url(r'^(?P<post_id>\d+)/comment/delete/$', views.delete_comment, name='delete_comment'), ]
Fix sticky with find as you type It was losing its position because filtering the list of templates with find as you type was causing the height of the page to change.
(function(Modules) { "use strict"; let normalize = (string) => string.toLowerCase().replace(/ /g,''); let filter = ($searchBox, $targets) => () => { let query = normalize($searchBox.val()); $targets.each(function() { let content = $('.live-search-relevant', this).text() || $(this).text(); if ($(this).has(':checked').length) { $(this).show(); return; } if (query == '') { $(this).css('display', ''); return; } $(this).toggle( normalize(content).indexOf(normalize(query)) > -1 ); }); // make sticky JS recalculate its cache of the element's position // because live search can change the height document if ('stickAtBottomWhenScrolling' in GOVUK) { GOVUK.stickAtBottomWhenScrolling.recalculate(); } }; Modules.LiveSearch = function() { this.start = function(component) { let $component = $(component); let $searchBox = $('input', $component); let filterFunc = filter( $searchBox, $($component.data('targets')) ); $searchBox.on('keyup input', filterFunc); filterFunc(); }; }; })(window.GOVUK.Modules);
(function(Modules) { "use strict"; let normalize = (string) => string.toLowerCase().replace(/ /g,''); let filter = ($searchBox, $targets) => () => { let query = normalize($searchBox.val()); $targets.each(function() { let content = $('.live-search-relevant', this).text() || $(this).text(); if ($(this).has(':checked').length) { $(this).show(); return; } if (query == '') { $(this).css('display', ''); return; } $(this).toggle( normalize(content).indexOf(normalize(query)) > -1 ); }); }; Modules.LiveSearch = function() { this.start = function(component) { let $component = $(component); let $searchBox = $('input', $component); let filterFunc = filter( $searchBox, $($component.data('targets')) ); $searchBox.on('keyup input', filterFunc); filterFunc(); }; }; })(window.GOVUK.Modules);
[MODULES-222] Fix early initialization of log manager on JDK 9+
/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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.jboss.modules; import java.security.AccessController; /** * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a> */ final class Metrics { static final boolean ENABLED; private Metrics() { } static long getCurrentCPUTime() { return ENABLED ? System.nanoTime() : 0L; } static { ENABLED = Boolean.parseBoolean(AccessController.doPrivileged(new PropertyReadAction("jboss.modules.metrics", "false"))); } }
/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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.jboss.modules; import java.lang.management.ManagementFactory; import java.lang.management.ThreadMXBean; import java.security.AccessController; /** * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a> */ final class Metrics { static final boolean ENABLED; static final ThreadMXBean THREAD_MX_BEAN = ManagementFactory.getThreadMXBean(); private Metrics() { } static long getCurrentCPUTime() { return ENABLED ? false ? THREAD_MX_BEAN.getCurrentThreadCpuTime() : System.nanoTime() : 0L; } static { ENABLED = Boolean.parseBoolean(AccessController.doPrivileged(new PropertyReadAction("jboss.modules.metrics", "false"))); } }
Enable all taxons upon migration
<?php declare(strict_types=1); namespace Sylius\Migrations; use Doctrine\DBAL\Schema\Schema; use Doctrine\Migrations\AbstractMigration; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20200325075815 extends AbstractMigration { public function getDescription() : string { return ''; } public function up(Schema $schema) : void { // this up() migration is auto-generated, please modify it to your needs $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.'); $this->addSql('ALTER TABLE sylius_taxon ADD enabled TINYINT(1) NOT NULL'); $this->addSql('UPDATE sylius_taxon SET enabled = 1'); } public function down(Schema $schema) : void { // this down() migration is auto-generated, please modify it to your needs $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.'); $this->addSql('ALTER TABLE sylius_taxon DROP enabled'); } }
<?php declare(strict_types=1); namespace Sylius\Migrations; use Doctrine\DBAL\Schema\Schema; use Doctrine\Migrations\AbstractMigration; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20200325075815 extends AbstractMigration { public function getDescription() : string { return ''; } public function up(Schema $schema) : void { // this up() migration is auto-generated, please modify it to your needs $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.'); $this->addSql('ALTER TABLE sylius_taxon ADD enabled TINYINT(1) NOT NULL'); } public function down(Schema $schema) : void { // this down() migration is auto-generated, please modify it to your needs $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.'); $this->addSql('ALTER TABLE sylius_taxon DROP enabled'); } }
Drop the extra shuffle and stop. It now more resembles the IV key setup.
package spritz // InsecurePasswordHash calculates a CPU- and memory-hard hash of the given // password and salt. It takes a linear parameter, m, which determines both CPU // and memory cost. It also takes the length of the hash in bytes. // // N.B.: THIS IS A TOTALLY EXPERIMENTAL ALGORITHM WHICH I WROTE BEFORE I'D HAD // ANY COFFEE. DO NOT USE HACKY ALGORITHMS DESIGNED BY UNCAFFEINATED // NON-CRYPTOGRAPHERS. func InsecurePasswordHash(password, salt []byte, m, n int) []byte { // initialize to 256*m bytes var s state s.initialize(256 * m) // absorb the password s.absorb(password) if s.a > 0 { s.shuffle() } // absorb the salt s.absorbStop() s.absorb(salt) // absorb the length s.absorbStop() s.absorbByte(int(n)) // squeeze out the digest out := make([]byte, n) s.squeeze(out) return out }
package spritz // InsecurePasswordHash calculates a CPU- and memory-hard hash of the given // password and salt. It takes a linear parameter, m, which determines both CPU // and memory cost. It also takes the length of the hash in bytes. // // N.B.: THIS IS A TOTALLY EXPERIMENTAL ALGORITHM WHICH I WROTE BEFORE I'D HAD // ANY COFFEE. DO NOT USE HACKY ALGORITHMS DESIGNED BY UNCAFFEINATED // NON-CRYPTOGRAPHERS. func InsecurePasswordHash(password, salt []byte, m, n int) []byte { // initialize to 256*m bytes var s state s.initialize(256 * m) // absorb the password s.absorb(password) if s.a > 0 { s.shuffle() } s.absorbStop() // absorb the salt s.absorb(salt) if s.a > 0 { s.shuffle() } s.absorbStop() // absorb the length s.absorbByte(int(n)) s.absorbStop() // squeeze out the digest out := make([]byte, n) s.squeeze(out) return out }
fix: Use absolute path for auth0 callback
import { auth0 } from '../../config/secrets'; import { homeLocation, apiLocation } from '../../config/env'; const { clientID, clientSecret, domain } = auth0; const successRedirect = `${homeLocation}/welcome`; const failureRedirect = `${homeLocation}/signin`; export default { devlogin: { authScheme: 'mock', provider: 'dev', module: 'passport-mock-strategy' }, local: { provider: 'local', module: 'passport-local', usernameField: 'email', passwordField: 'password', authPath: '/auth/local', successRedirect: successRedirect, failureRedirect: failureRedirect, session: true, failureFlash: true }, 'auth0-login': { provider: 'auth0', module: 'passport-auth0', clientID, clientSecret, domain, cookieDomain: process.env.COOKIE_DOMAIN || 'localhost', callbackURL: `${apiLocation}/auth/auth0/callback`, authPath: '/auth/auth0', callbackPath: '/auth/auth0/callback', useCustomCallback: true, successRedirect: successRedirect, failureRedirect: failureRedirect, scope: ['openid profile email'], failureFlash: true } };
import { auth0 } from '../../config/secrets'; import { homeLocation } from '../../config/env'; const { clientID, clientSecret, domain } = auth0; const successRedirect = `${homeLocation}/welcome`; const failureRedirect = '/signin'; export default { devlogin: { authScheme: 'mock', provider: 'dev', module: 'passport-mock-strategy' }, local: { provider: 'local', module: 'passport-local', usernameField: 'email', passwordField: 'password', authPath: '/auth/local', successRedirect: successRedirect, failureRedirect: failureRedirect, session: true, failureFlash: true }, 'auth0-login': { provider: 'auth0', module: 'passport-auth0', clientID, clientSecret, domain, cookieDomain: 'freeCodeCamp.org', callbackURL: '/auth/auth0/callback', authPath: '/auth/auth0', callbackPath: '/auth/auth0/callback', useCustomCallback: true, successRedirect: successRedirect, failureRedirect: failureRedirect, scope: ['openid profile email'], failureFlash: true } };
Fix issue with GO term (unsorted).
import numpy as np import pandas as pa import unittest import pathway_extraction.uniprot_retrieval_data as uniprot_retrieval_data test_data_directory_uniprot = 'test_data/' + 'test_uniprot_retrieval/' class uniprot_retrieval_data_test(unittest.TestCase): def test_extract_information_from_uniprot(self): print("\nTesting uniprot retrieval data using blast result ") df_data = pa.read_csv(test_data_directory_uniprot + 'data.tsv', sep='\t') df_data.replace(np.nan, '', regex=True, inplace=True) df_result = uniprot_retrieval_data.extract_information_from_uniprot(df_data) df_result_truth = pa.read_csv(test_data_directory_uniprot + 'result.tsv', sep='\t') np.testing.assert_array_equal(df_result['GOs'].tolist().sort(), df_result_truth['GOs'].tolist().sort()) np.testing.assert_array_equal(df_result['InterProScan'].tolist(), df_result_truth['InterProScan'].tolist())
import numpy as np import pandas as pa import unittest import pathway_extraction.uniprot_retrieval_data as uniprot_retrieval_data test_data_directory_uniprot = 'test_data/' + 'test_uniprot_retrieval/' class uniprot_retrieval_data_test(unittest.TestCase): def test_extract_information_from_uniprot(self): print("\nTesting uniprot retrieval data using blast result ") df_data = pa.read_csv(test_data_directory_uniprot + 'data.tsv', sep='\t') df_data.replace(np.nan, '', regex=True, inplace=True) df_result = uniprot_retrieval_data.extract_information_from_uniprot(df_data) df_result_truth = pa.read_csv(test_data_directory_uniprot + 'result.tsv', sep='\t') np.testing.assert_array_equal(df_result['GOs'].tolist(), df_result_truth['GOs'].tolist()) np.testing.assert_array_equal(df_result['InterProScan'].tolist(), df_result_truth['InterProScan'].tolist())
Test should not rely on setTimeout
'use strict'; var conjoiners = require('../lib/conjoiners'); exports['simple inter-process communication'] = function(test) { test.expect(3); var value = 'test_value'; var cj1 = {}; var cj1Name = 'test'; var cj2 = { onTransenlightenment: function (event) { test.equal(event.property, 'val'); test.equal(this[event.property], value); test.equal(cj2.val, value); test.done(); } }; conjoiners.implant(cj1, 'test/conf.json', cj1Name).then(function() { return conjoiners.implant(cj2, 'test/conf.json', 'test2'); }).then(function () { cj1.val = value; }).done(); };
'use strict'; var conjoiners = require('../lib/conjoiners'); exports['simple inter-process communication'] = function(test) { test.expect(3); var value = 'test_value'; var cj1 = {}; var cj1Name = 'test'; var cj2 = { onTransenlightenment: function (event) { test.equal(event.property, 'val'); test.equal(this[event.property], value); } }; conjoiners.implant(cj1, 'test/conf.json', cj1Name).then(function() { return conjoiners.implant(cj2, 'test/conf.json', 'test2'); }).then(function () { cj1.val = value; setTimeout(function() { test.equal(cj2.val, value); test.done(); }, 1500); }).done(); };
Fix version and format and rereleas
#!/usr/bin/env python from setuptools import setup conf = dict(name='magiclog', version='1.0.1', author='Jason Dusek', author_email='jason.dusek@gmail.com', url='https://github.com/drcloud/magiclog', install_requires=[], setup_requires=['pytest-runner', 'setuptools'], tests_require=['flake8', 'pytest', 'tox'], description='Easy logger management for libraries and CLI tools.', py_modules=['magiclog'], classifiers=['Environment :: Console', 'Intended Audience :: Developers', 'Operating System :: Unix', 'Operating System :: POSIX', 'Programming Language :: Python', 'Topic :: Software Development', 'Development Status :: 4 - Beta']) if __name__ == '__main__': setup(**conf)
#!/usr/bin/env python from setuptools import setup conf = dict(name='magiclog', version='1.0.0', author = 'Jason Dusek', author_email = 'jason.dusek@gmail.com', url = 'https://github.com/drcloud/magiclog', install_requires=[], setup_requires=['pytest-runner', 'setuptools'], tests_require=['flake8', 'pytest', 'tox'], description='Easy logger management for libraries and CLI tools.', py_modules=['magiclog'], classifiers=['Environment :: Console', 'Intended Audience :: Developers', 'Operating System :: Unix', 'Operating System :: POSIX', 'Programming Language :: Python', 'Topic :: Software Development', 'Development Status :: 4 - Beta']) if __name__ == '__main__': setup(**conf)
Add support for laravel 5.3
<?php namespace Nwidart\MoneyFormatterLaravel; use Illuminate\Foundation\AliasLoader; use Illuminate\Support\ServiceProvider; use Nwidart\MoneyFormatter\MoneyFormatter; class MoneyFormatterServiceProvider extends ServiceProvider { public function register() { $this->registerConfiguration(); $this->registerAlias(); $this->app->singleton('Nwidart\MoneyFormatter\MoneyFormatter', function () { return new MoneyFormatter(config('money-formatter.locale', 'en_UK')); }); } /** * Register the configuration file so Laravel can publish them * Also merges the published config file with original */ private function registerConfiguration() { $configPath = __DIR__ . '/../config/money-formatter.php'; $this->mergeConfigFrom($configPath, 'money-formatter'); $this->publishes([$configPath => config_path('money-formatter.php')]); } /** * Register the MoneyFormatter laravel alias. */ private function registerAlias() { $aliasLoader = AliasLoader::getInstance(); $aliasLoader->alias('MoneyFormatter', 'Nwidart\MoneyFormatterLaravel\MoneyFormatter'); } }
<?php namespace Nwidart\MoneyFormatterLaravel; use Illuminate\Foundation\AliasLoader; use Illuminate\Support\ServiceProvider; use Nwidart\MoneyFormatter\MoneyFormatter; class MoneyFormatterServiceProvider extends ServiceProvider { public function register() { $this->registerConfiguration(); $this->registerAlias(); $this->app->bindShared('Nwidart\MoneyFormatter\MoneyFormatter', function () { return new MoneyFormatter(config('money-formatter.locale', 'en_UK')); }); } /** * Register the configuration file so Laravel can publish them * Also merges the published config file with original */ private function registerConfiguration() { $configPath = __DIR__ . '/../config/money-formatter.php'; $this->mergeConfigFrom($configPath, 'money-formatter'); $this->publishes([$configPath => config_path('money-formatter.php')]); } /** * Register the MoneyFormatter laravel alias. */ private function registerAlias() { $aliasLoader = AliasLoader::getInstance(); $aliasLoader->alias('MoneyFormatter', 'Nwidart\MoneyFormatterLaravel\MoneyFormatter'); } }
Check for blocks against the right interval
/* 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/. */ module.exports = function (BLOCK_INTERVAL_MS, INVALID_AGENT_INTERVAL_MS) { function IpRecord() {} IpRecord.parse = function (object) { var rec = new IpRecord() object = object || {} rec.ba = object.ba rec.bk = object.bk return rec } function isBadAgent(agent) { return false // TODO } IpRecord.prototype.isBlocked = function () { return !!(this.bk && (Date.now() - this.bk < BLOCK_INTERVAL_MS)) } IpRecord.prototype.block = function () { this.bk = Date.now() } IpRecord.prototype.retryAfter = function () { if (!this.isBlocked()) { return 0 } return Math.floor((this.bk + BLOCK_INTERVAL_MS - Date.now()) / 1000) } IpRecord.prototype.update = function (agent) { if (isBadAgent(agent)) { if (Date.now() - this.ba < INVALID_AGENT_INTERVAL_MS) { this.block() } this.ba = Date.now() } return this.retryAfter() } return IpRecord }
/* 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/. */ module.exports = function (BLOCK_INTERVAL_MS, INVALID_AGENT_INTERVAL_MS) { function IpRecord() {} IpRecord.parse = function (object) { var rec = new IpRecord() object = object || {} rec.ba = object.ba rec.bk = object.bk return rec } function isBadAgent(agent) { return false // TODO } IpRecord.prototype.isBlocked = function () { return !!(this.bk && (Date.now() - this.bk < INVALID_AGENT_INTERVAL_MS)) } IpRecord.prototype.block = function () { this.bk = Date.now() } IpRecord.prototype.retryAfter = function () { if (!this.isBlocked()) { return 0 } return Math.floor((this.bk + BLOCK_INTERVAL_MS - Date.now()) / 1000) } IpRecord.prototype.update = function (agent) { if (isBadAgent(agent)) { if (Date.now() - this.ba < INVALID_AGENT_INTERVAL_MS) { this.block() } this.ba = Date.now() } return this.retryAfter() } return IpRecord }
Return Postcode.find's callback to prevent next being called twice
"use strict"; const ScottishPostcode = require("../models/scottish_postcode"); const Postcode = require("../models/postcode"); const Pc = require("postcode"); const { InvalidPostcodeError, PostcodeNotFoundError, PostcodeNotInSpdError, } = require("../lib/errors.js"); exports.show = (request, response, next) => { const { postcode } = request.params; if (!Pc.isValid(postcode.trim())) return next(new InvalidPostcodeError()); ScottishPostcode.find(postcode, (error, result) => { if (error) return next(error); if (!result) { // The return value of Postcode.find is the return value of the callback // see postcode.js lines 186-188 return Postcode.find(postcode, (gerr, gres) => { if (gerr) return next(gerr); if (!gres) return next(new PostcodeNotFoundError()); return next(new PostcodeNotInSpdError()); }); } response.jsonApiResponse = { status: 200, result: ScottishPostcode.toJson(result), }; return next(); }); };
"use strict"; const ScottishPostcode = require("../models/scottish_postcode"); const Postcode = require("../models/postcode"); const Pc = require("postcode"); const { InvalidPostcodeError, PostcodeNotFoundError, PostcodeNotInSpdError, } = require("../lib/errors.js"); exports.show = (request, response, next) => { const { postcode } = request.params; if (!Pc.isValid(postcode.trim())) return next(new InvalidPostcodeError()); ScottishPostcode.find(postcode, (error, result) => { if (error) return next(error); if (!result) { Postcode.find(postcode, (gerr, gres) => { if (gerr) return next(gerr); if (!gres) return next(new PostcodeNotFoundError()); return next(new PostcodeNotInSpdError()); }); } response.jsonApiResponse = { status: 200, result: ScottishPostcode.toJson(result), }; return next(); }); };
Fix browserstack test failures. Old puppeteer is not supported anymore.
import Client from '../../client.js'; import { enterJob } from '../../../utils/buildmessage.js'; import { ensureDependencies } from '../../../cli/dev-bundle-helpers.js'; const NPM_DEPENDENCIES = { puppeteer: '8.0.0' }; export default class PuppeteerClient extends Client { constructor(options) { super(options); enterJob( { title: 'Installing Puppeteer in Meteor tool' }, () => { ensureDependencies(NPM_DEPENDENCIES); } ); this.npmPackageExports = require('puppeteer'); this.name = 'Puppeteer'; } async connect() { // Note for Travis and CircleCI to run sandbox must be turned off. // From a security perspective this is not ideal, in the future would be worthwhile // to configure to include only for CI based setups this.browser = await this.npmPackageExports.launch({ args: ['--no-sandbox', '--disable-setuid-sandbox'] }); this.page = await this.browser.newPage(); this.page.goto(`http://${this.host}:${this.port}`); } async stop() { this.page && await this.page.close(); this.page = null; this.browser && await this.browser.close(); this.browser = null; } static pushClients(clients, appConfig) { clients.push(new PuppeteerClient(appConfig)); } }
import Client from '../../client.js'; import { enterJob } from '../../../utils/buildmessage.js'; import { ensureDependencies } from '../../../cli/dev-bundle-helpers.js'; const NPM_DEPENDENCIES = { puppeteer: '1.3.0' }; export default class PuppeteerClient extends Client { constructor(options) { super(options); enterJob( { title: 'Installing Puppeteer in Meteor tool' }, () => { ensureDependencies(NPM_DEPENDENCIES); } ); this.npmPackageExports = require('puppeteer'); this.name = 'Puppeteer'; } async connect() { // Note for Travis and CircleCI to run sandbox must be turned off. // From a security perspective this is not ideal, in the future would be worthwhile // to configure to include only for CI based setups this.browser = await this.npmPackageExports.launch({ args: ['--no-sandbox', '--disable-setuid-sandbox'] }); this.page = await this.browser.newPage(); this.page.goto(`http://${this.host}:${this.port}`); } async stop() { this.page && await this.page.close(); this.page = null; this.browser && await this.browser.close(); this.browser = null; } static pushClients(clients, appConfig) { clients.push(new PuppeteerClient(appConfig)); } }
Use the browser to send the request
<?php /** * This file is part of ReactGuzzleRing. * ** (c) 2014 Cees-Jan Kiewiet * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace WyriHaximus\React\Guzzle\HttpClient; use Clue\React\Buzz\Browser; use Clue\React\Buzz\Io\Sender; use Psr\Http\Message\RequestInterface; use React\EventLoop\LoopInterface; use React\HttpClient\Client as HttpClient; /** * Class RequestFactory * * @package WyriHaximus\React\Guzzle\HttpClient */ class RequestFactory { /** * * @param RequestInterface $request * @param array $options * @param HttpClient $httpClient * @param LoopInterface $loop * @return \React\Promise\Promise */ public function create(RequestInterface $request, array $options, HttpClient $httpClient, LoopInterface $loop) { return (new Browser($loop, new Sender($httpClient)))->send($request); } }
<?php /** * This file is part of ReactGuzzleRing. * ** (c) 2014 Cees-Jan Kiewiet * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace WyriHaximus\React\Guzzle\HttpClient; use Psr\Http\Message\RequestInterface; use React\EventLoop\LoopInterface; use React\HttpClient\Client as HttpClient; /** * Class RequestFactory * * @package WyriHaximus\React\Guzzle\HttpClient */ class RequestFactory { /** * * @param RequestInterface $request * @param array $options * @param HttpClient $httpClient * @param LoopInterface $loop * @return \React\Promise\Promise */ public function create(RequestInterface $request, array $options, HttpClient $httpClient, LoopInterface $loop) { return Request::send($request, $options, $httpClient, $loop); } }
Fix typo. contact should be context
""" Output the collected values to . Zer0MQ pub/sub channel """ from Handler import Handler import zmq class zmqHandler ( Handler ): """ Implements the abstract Handler class, sending data to a Zer0MQ pub channel """ def __init__( self, config=None ): """ Create a new instance of zmqHandler class """ # Initialize Handler Handler.__init__(self,config) # Initialize Data self.context = None self.socket = None # Initialize Options self.port = int( self.config['port'] ) # Create ZMQ pub socket and bind self._bind() def _bind(self): """ Create PUB socket and bind """ self.context = zmq.Context() self.socket = self.context.socket(zmq.PUB) self.socket.bind("tcp://*:%i" % self.port ) def __del__(self): """ Destroy instance of the zmqHandler class """ pass def process(self,metric): """ Process a metric and send it to zmq pub socket """ # Acquire a lock self.lock.acquire() # Send the data as ...... self.socket.send("%s" % str(metric) ) # Release lock self.lock.release()
""" Output the collected values to . Zer0MQ pub/sub channel """ from Handler import Handler import zmq class zmqHandler ( Handler ): """ Implements the abstract Handler class, sending data to a Zer0MQ pub channel """ def __init__( self, config=None ): """ Create a new instance of zmqHandler class """ # Initialize Handler Handler.__init__(self,config) # Initialize Data self.context = None self.socket = None # Initialize Options self.port = int( self.config['port'] ) # Create ZMQ pub socket and bind self._bind() def _bind(self): """ Create PUB socket and bind """ self.context = zmq.Context() self.socket = self.contact.socket(zmq.PUB) self.socket.bind("tcp://*:%i" % self.port ) def __del__(self): """ Destroy instance of the zmqHandler class """ pass def process(self,metric): """ Process a metric and send it to zmq pub socket """ # Acquire a lock self.lock.acquire() # Send the data as ...... self.socket.send("%s" % str(metric) ) # Release lock self.lock.release()
Fix a bug with Expires header
<?php /** * Created by IntelliJ IDEA. * User: Kevin * Date: 16.06.2015 * Time: 19:10 */ namespace Kevinrob\GuzzleCache; use Psr\Http\Message\ResponseInterface; abstract class AbstractPrivateCache implements CacheStorageInterface { /** * @param ResponseInterface $response * @return CacheEntry|null entry to save, null if can't cache it */ protected function getCacheObject(ResponseInterface $response) { if ($response->hasHeader("Cache-Control")) { $cacheControlDirectives = $response->getHeader("Cache-Control"); if (in_array("no-store", $cacheControlDirectives)) { // No store allowed (maybe some sensitives data...) return null; } // TODO return info for caching (stale, revalidate, ...) } if ($response->hasHeader("Expires")) { $expireAt = \DateTime::createFromFormat('D, d M Y H:i:s T', $response->getHeaderLine("Expires")); if ($expireAt !== FALSE) { return new CacheEntry($response, $expireAt); } } return null; } }
<?php /** * Created by IntelliJ IDEA. * User: Kevin * Date: 16.06.2015 * Time: 19:10 */ namespace Kevinrob\GuzzleCache; use Psr\Http\Message\ResponseInterface; abstract class AbstractPrivateCache implements CacheStorageInterface { /** * @param ResponseInterface $response * @return CacheEntry|null entry to save, null if can't cache it */ protected function getCacheObject(ResponseInterface $response) { if ($response->hasHeader("Cache-Control")) { $cacheControlDirectives = $response->getHeader("Cache-Control"); if (in_array("no-store", $cacheControlDirectives)) { // No store allowed (maybe some sensitives data...) return null; } // TODO return info for caching (stale, revalidate, ...) } if ($response->hasHeader("Expires")) { $expireAt = \DateTime::createFromFormat('D, d M Y H:i:s T', $response->getHeader("Expires")); if ($expireAt !== FALSE) { return new CacheEntry($response, $expireAt); } } return null; } }
Implement check for empty file selections while using the CLI Fixes #3
#!/usr/bin/env node var path = require('path'); var nconf = require('nconf'); var yamlLint = require('./yaml-lint'); var leprechaun = require('leprechaun'); var merge = require('lodash.merge'); var snakeCase = require('lodash.snakecase'); var glob = require('glob'); var Promise = require('bluebird'); var options = {}; nconf.argv().env({ match: /^yamllint/i }).file({ file: path.resolve(process.cwd(), '.yaml-lint.json') }); [ 'schema' ].forEach(function (key) { var env = snakeCase(key); options[key] = nconf.get(key) || nconf.get('yamllint_' + env.toLowerCase()) || nconf.get('YAMLLINT' + env.toUpperCase()); }); var config = nconf.get(); var files = []; (config._ || []).forEach(function (file) { files = files.concat(glob.sync(file)); }); if (files.length === 0) { leprechaun.error('YAML Lint failed.'); console.error('No YAML files were found matching your selection.'); process.exit(1); } else { Promise.map(files, function (file) { return yamlLint.lintFile(file, options); }).then(function () { leprechaun.success('YAML Lint successful.'); }).catch(function (error) { leprechaun.error('YAML Lint failed.'); console.error(error.message); process.exit(1); }); }
#!/usr/bin/env node var path = require('path'); var nconf = require('nconf'); var yamlLint = require('./yaml-lint'); var leprechaun = require('leprechaun'); var merge = require('lodash.merge'); var snakeCase = require('lodash.snakecase'); var glob = require('glob'); var Promise = require('bluebird'); var options = {}; nconf.argv().env({ match: /^yamllint/i }).file({ file: path.resolve(process.cwd(), '.yaml-lint.json') }); [ 'schema' ].forEach(function (key) { var env = snakeCase(key); options[key] = nconf.get(key) || nconf.get('yamllint_' + env.toLowerCase()) || nconf.get('YAMLLINT' + env.toUpperCase()); }); var config = nconf.get(); var files = []; (config._ || []).forEach(function (file) { files = files.concat(glob.sync(file)); }); Promise.map(files, function (file) { return yamlLint.lintFile(file, options); }).then(function () { leprechaun.success('YAML Lint successful.'); }).catch(function (error) { leprechaun.error('YAML Lint failed.'); console.error(error.message); process.exit(1); });
Fix types for Symfony 5.4
<?php namespace Enqueue\Symfony\Client; use Enqueue\Client\SpoolProducer; use Symfony\Component\Console\ConsoleEvents; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpKernel\KernelEvents; class FlushSpoolProducerListener implements EventSubscriberInterface { /** * @var SpoolProducer */ private $producer; /** * @param SpoolProducer $producer */ public function __construct(SpoolProducer $producer) { $this->producer = $producer; } public function flushMessages() { $this->producer->flush(); } /** * {@inheritdoc} */ public static function getSubscribedEvents(): array { $events = []; if (class_exists(KernelEvents::class)) { $events[KernelEvents::TERMINATE] = 'flushMessages'; } if (class_exists(ConsoleEvents::class)) { $events[ConsoleEvents::TERMINATE] = 'flushMessages'; } return $events; } }
<?php namespace Enqueue\Symfony\Client; use Enqueue\Client\SpoolProducer; use Symfony\Component\Console\ConsoleEvents; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpKernel\KernelEvents; class FlushSpoolProducerListener implements EventSubscriberInterface { /** * @var SpoolProducer */ private $producer; /** * @param SpoolProducer $producer */ public function __construct(SpoolProducer $producer) { $this->producer = $producer; } public function flushMessages() { $this->producer->flush(); } /** * {@inheritdoc} */ public static function getSubscribedEvents() { $events = []; if (class_exists(KernelEvents::class)) { $events[KernelEvents::TERMINATE] = 'flushMessages'; } if (class_exists(ConsoleEvents::class)) { $events[ConsoleEvents::TERMINATE] = 'flushMessages'; } return $events; } }
Move attribute comparator with others
/*global TodoMVC */ 'use strict'; TodoMVC.module('Todos', function (Todos, App, Backbone) { // Todo Model // ---------- Todos.Todo = Backbone.Model.extend({ defaults: { title: '', completed: false, created: 0 }, initialize: function () { if (this.isNew()) { this.set('created', Date.now()); } }, toggle: function () { return this.set('completed', !this.isCompleted()); }, isCompleted: function () { return this.get('completed'); }, matchesFilter: function (filter) { if (filter == 'all') { return true; } if (filter == 'active') { return !this.isCompleted(); } return this.isCompleted(); } }); // Todo Collection // --------------- Todos.TodoList = Backbone.Collection.extend({ model: Todos.Todo, localStorage: new Backbone.LocalStorage('todos-backbone-marionette'), comparator: 'created', getCompleted: function () { return this.filter(this._isCompleted); }, getActive: function () { return this.reject(this._isCompleted); }, _isCompleted: function (todo) { return todo.isCompleted(); } }); });
/*global TodoMVC */ 'use strict'; TodoMVC.module('Todos', function (Todos, App, Backbone) { // Todo Model // ---------- Todos.Todo = Backbone.Model.extend({ defaults: { title: '', completed: false, created: 0 }, initialize: function () { if (this.isNew()) { this.set('created', Date.now()); } }, toggle: function () { return this.set('completed', !this.isCompleted()); }, isCompleted: function () { return this.get('completed'); }, matchesFilter: function (filter) { if (filter == 'all') { return true; } if (filter == 'active') { return !this.isCompleted(); } return this.isCompleted(); } }); // Todo Collection // --------------- Todos.TodoList = Backbone.Collection.extend({ model: Todos.Todo, localStorage: new Backbone.LocalStorage('todos-backbone-marionette'), getCompleted: function () { return this.filter(this._isCompleted); }, getActive: function () { return this.reject(this._isCompleted); }, comparator: 'created', _isCompleted: function (todo) { return todo.isCompleted(); } }); });
Rename env.data -> env.current_user; Set locale.
"use strict"; /*global nodeca, _*/ var me_in_fields = [ '_uname', 'locale' ]; // fetch current user info // fired before each controllers nodeca.filters.before('', { weight: -70 }, function load_current_user(params, next) { var env = this; // // fill in default (guest) values // env.current_user = null; env.runtime.user_name = ''; env.runtime.is_member = false; env.runtime.is_guest = true; // // if there's no session or session has no user_id, user is guest - skip // if (!env.session || !env.session.user_id) { next(); return; } nodeca.models.users.User .findOne({ '_id': env.session.user_id }) .select(me_in_fields.join(' ')) .setOptions({ lean: true }) .exec(function(err, user){ if (err) { next(err); return; } // user in session, but db does not know this user if (!user) { next(); return; } env.current_user = user; env.runtime.user_name = user._uname; env.runtime.is_guest = false; env.runtime.is_member = true; // set user's locale env.session.locale = user.locale || env.session.locale; next(); }); });
"use strict"; /*global nodeca, _*/ var me_in_fields = [ '_uname', 'locale' ]; // fetch current user info // fired before each controllers nodeca.filters.before('', { weight: -70 }, function load_current_user(params, next) { var env = this; // // fill in default (guest) values // env.user = null; env.runtime.user_name = ''; env.runtime.is_member = false; env.runtime.is_guest = true; // // if there's no session or session has no user_id, user is guest - skip // if (!env.session || !env.session.user_id) { next(); return; } nodeca.models.users.User .findOne({ '_id': env.session.user_id }) .select(me_in_fields.join(' ')) .setOptions({ lean: true }) .exec(function(err, user){ if (err) { next(err); return; } // user in session, but db does not know this user if (!user) { next(); return; } env.user = user; env.runtime.user_name = user._uname; env.runtime.is_guest = false; env.runtime.is_member = true; next(); }); });
Increment version in preparation for release
import subprocess import sys from setuptools import Command, setup class RunTests(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): errno = subprocess.call([sys.executable, '-m', 'unittest', 'parserutils.tests.tests']) raise SystemExit(errno) setup( name='parserutils', description='A collection of performant parsing utilities', keywords='parser,parsing,utils,utilities,collections,dates,elements,numbers,strings,url,xml', version='0.3.0', packages=[ 'parserutils', 'parserutils.tests' ], install_requires=[ 'defusedxml', 'python-dateutil', 'six' ], url='https://github.com/consbio/parserutils', license='BSD', cmdclass={'test': RunTests} )
import subprocess import sys from setuptools import Command, setup class RunTests(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): errno = subprocess.call([sys.executable, '-m', 'unittest', 'parserutils.tests.tests']) raise SystemExit(errno) setup( name='parserutils', description='A collection of performant parsing utilities', keywords='parser,parsing,utils,utilities,collections,dates,elements,numbers,strings,url,xml', version='0.2.4', packages=[ 'parserutils', 'parserutils.tests' ], install_requires=[ 'defusedxml', 'python-dateutil', 'six' ], url='https://github.com/consbio/parserutils', license='BSD', cmdclass={'test': RunTests} )
Update docker images to version 46
/* * 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 io.trino.tests.product.launcher.env; public final class EnvironmentDefaults { public static final String DOCKER_IMAGES_VERSION = "46"; public static final String HADOOP_BASE_IMAGE = "ghcr.io/trinodb/testing/hdp2.6-hive"; public static final String HADOOP_IMAGES_VERSION = DOCKER_IMAGES_VERSION; public static final String TEMPTO_ENVIRONMENT_CONFIG = "/dev/null"; private EnvironmentDefaults() {} }
/* * 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 io.trino.tests.product.launcher.env; public final class EnvironmentDefaults { public static final String DOCKER_IMAGES_VERSION = "45"; public static final String HADOOP_BASE_IMAGE = "ghcr.io/trinodb/testing/hdp2.6-hive"; public static final String HADOOP_IMAGES_VERSION = DOCKER_IMAGES_VERSION; public static final String TEMPTO_ENVIRONMENT_CONFIG = "/dev/null"; private EnvironmentDefaults() {} }
Add back the ಠ_ಠ face I like to judge people who don't use evergreen browsers and I'd hope the code checking for support does as well.
var detection = 'class ಠ_ಠ extends Array{constructor(j=`a`,...c){const q=(({u: e})=>{return {[`${c}`]:Symbol(j)};})({});super(j,q,...c)}}new Promise(f=>{const a=function*(){return "\u{20BB7}".match(/./u)[0].length===2||!0};for (let z of a()){const [x,y,w,k]=[new Set(),new WeakSet(),new Map(), new WeakMap()];break}f(new Proxy({},{get:(h,i) =>i in h ?h[i]:"j".repeat(0o2)}))}).then(t => new ಠ_ಠ(t.d))' var result module.exports = function () { if (result === void 0) { try { eval(detection) result = true } catch (e) { result = false } } return result }
var detection = 'class ಠ extends Array{constructor(j=`a`,...c){const q=(({u: e})=>{return {[`${c}`]:Symbol(j)};})({});super(j,q,...c)}}new Promise(f=>{const a=function*(){return "\u{20BB7}".match(/./u)[0].length===2||!0};for (let z of a()){const [x,y,w,k]=[new Set(),new WeakSet(),new Map(), new WeakMap()];break}f(new Proxy({},{get:(h,i) =>i in h ?h[i]:"j".repeat(0o2)}))}).then(t => new ಠ(t.d))' var result module.exports = function () { if (result === void 0) { try { eval(detection) result = true } catch (e) { result = false } } return result }
Use the extracted json for getting data from OSEObject to not extract it every time
class OSEObject(object): """Superclass to all OSE objects that hold data about remote API.""" def __init__(self, ose): self.ose = ose self.refresh() def refresh(self): """Reloads all info about this object. Uses _request_fresh() method defined by subclasses to obtain fresh response. """ self._response = self._request_fresh() self._json = self._response.json() def _request_fresh(self): raise NotImplementedError('Class {cls} doesn\'t implement _request_fresh method.'.\ format(cls=type(self))) def __getattr__(self, attr): return self._json['data'][attr]
class OSEObject(object): """Superclass to all OSE objects that hold data about remote API.""" def __init__(self, ose): self.ose = ose self.refresh() def refresh(self): """Reloads all info about this object. Uses _request_fresh() method defined by subclasses to obtain fresh response. """ self._response = self._request_fresh() self._json = self._response.json() def _request_fresh(self): raise NotImplementedError('Class {cls} doesn\'t implement _request_fresh method.'.\ format(cls=type(self))) def __getattr__(self, attr): return self._response.json()['data'][attr]
Update email to temporarily available one
<?php // Check for empty fields if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['phone']) || empty($_POST['message']) || !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)) { echo "No arguments Provided!"; return false; } $name = $_POST['name']; $email_address = $_POST['email']; $phone = $_POST['phone']; $message = $_POST['message']; // Create the email and send the message $to = 'contact@zuhaibahmad.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to. $email_subject = "Quote Request: $name"; $email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message"; $headers = "From: info@extravaganzainnovations.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com. $headers .= "Reply-To: $email_address"; mail($to,$email_subject,$email_body,$headers); return true; ?>
<?php // Check for empty fields if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['phone']) || empty($_POST['message']) || !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)) { echo "No arguments Provided!"; return false; } $name = $_POST['name']; $email_address = $_POST['email']; $phone = $_POST['phone']; $message = $_POST['message']; // Create the email and send the message $to = 'mail@extravaganzainnovations.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to. $email_subject = "Quote Request: $name"; $email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message"; $headers = "From: info@extravaganzainnovations.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com. $headers .= "Reply-To: $email_address"; mail($to,$email_subject,$email_body,$headers); return true; ?>
Add a call to ssh.InsecureIgnoreHostKey() for recent Go versions
package main import ( "fmt" "log" "os" "golang.org/x/crypto/ssh" ) func main() { if len(os.Args) != 4 { log.Fatalf("Usage: %s <user> <host:port> <command>", os.Args[0]) } client, session, err := connectToHost(os.Args[1], os.Args[2]) if err != nil { panic(err) } out, err := session.CombinedOutput(os.Args[3]) if err != nil { panic(err) } fmt.Println(string(out)) client.Close() } func connectToHost(user, host string) (*ssh.Client, *ssh.Session, error) { var pass string fmt.Print("Password: ") fmt.Scanf("%s\n", &pass) sshConfig := &ssh.ClientConfig{ User: user, Auth: []ssh.AuthMethod{ssh.Password(pass)}, } sshConfig.HostKeyCallback = ssh.InsecureIgnoreHostKey() client, err := ssh.Dial("tcp", host, sshConfig) if err != nil { return nil, nil, err } session, err := client.NewSession() if err != nil { client.Close() return nil, nil, err } return client, session, nil }
package main import ( "fmt" "log" "os" "golang.org/x/crypto/ssh" ) func main() { if len(os.Args) != 4 { log.Fatalf("Usage: %s <user> <host:port> <command>", os.Args[0]) } client, session, err := connectToHost(os.Args[1], os.Args[2]) if err != nil { panic(err) } out, err := session.CombinedOutput(os.Args[3]) if err != nil { panic(err) } fmt.Println(string(out)) client.Close() } func connectToHost(user, host string) (*ssh.Client, *ssh.Session, error) { var pass string fmt.Print("Password: ") fmt.Scanf("%s\n", &pass) sshConfig := &ssh.ClientConfig{ User: user, Auth: []ssh.AuthMethod{ssh.Password(pass)}, } client, err := ssh.Dial("tcp", host, sshConfig) if err != nil { return nil, nil, err } session, err := client.NewSession() if err != nil { client.Close() return nil, nil, err } return client, session, nil }
Add buckets for collecting pingdom data
# Copy this file to development_environment.py # and replace OAuth credentials your dev credentials TOKENS = { '_foo_bucket': '_foo_bucket-bearer-token', 'bucket': 'bucket-bearer-token', 'foo': 'foo-bearer-token', 'foo_bucket': 'foo_bucket-bearer-token', 'licensing': 'licensing-bearer-token', 'licensing_journey': 'licensing_journey-bearer-token', 'licensing_live_data': 'licensing_live_data_bearer_token', 'licence_finder_live_data': 'licence_finder_live_data_bearer_token' } PERMISSIONS = {} OAUTH_CLIENT_ID = \ "1759c91cdc926eebe5d5c9fce53a58170ad17ba30a22b4b451c377a339a98844" OAUTH_CLIENT_SECRET = \ "8f205218c0a378e33dccae5a557b4cac766f343a7dbfcb50de2286f03db4273a" OAUTH_BASE_URL = "http://signon.dev.gov.uk"
# Copy this file to development_environment.py # and replace OAuth credentials your dev credentials TOKENS = { '_foo_bucket': '_foo_bucket-bearer-token', 'bucket': 'bucket-bearer-token', 'foo': 'foo-bearer-token', 'foo_bucket': 'foo_bucket-bearer-token', 'licensing': 'licensing-bearer-token', 'licensing_journey': 'licensing_journey-bearer-token' } PERMISSIONS = {} OAUTH_CLIENT_ID = \ "1759c91cdc926eebe5d5c9fce53a58170ad17ba30a22b4b451c377a339a98844" OAUTH_CLIENT_SECRET = \ "8f205218c0a378e33dccae5a557b4cac766f343a7dbfcb50de2286f03db4273a" OAUTH_BASE_URL = "http://signon.dev.gov.uk"
Apply box props to the Box wrapper
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import Box, { pickBoxProps } from '../box'; import theme from './theme.css'; import Island from './Island'; import { elementIsDark } from '../utils/utils'; class IslandGroup extends PureComponent { render() { const { children, className, color, dark, size, ...otherProps } = this.props; const boxProps = pickBoxProps(otherProps); const isDark = elementIsDark(color, dark); const classNames = cx(theme['segmented'], theme['island'], theme[color], { [theme['dark']]: isDark }, className); return ( <Box {...boxProps} className={classNames} padding={0}> {React.Children.map(children, child => { return ( <Island {...child.props} color={color} dark={isDark} size={size}> {child.props.children} </Island> ); })} </Box> ); } } IslandGroup.propTypes = { children: PropTypes.any, className: PropTypes.string, color: PropTypes.oneOf(['neutral', 'mint', 'violet', 'ruby', 'gold', 'aqua', 'white']), dark: PropTypes.bool, size: PropTypes.oneOf(['small', 'medium', 'large']), }; IslandGroup.defaultProps = { color: 'white', }; export default IslandGroup;
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import Box from '../box'; import theme from './theme.css'; import Island from './Island'; import { elementIsDark } from '../utils/utils'; class IslandGroup extends PureComponent { render() { const { children, className, color, dark, size } = this.props; const isDark = elementIsDark(color, dark); const classNames = cx(theme['segmented'], theme['island'], theme[color], { [theme['dark']]: isDark }, className); return ( <Box className={classNames} padding={0}> {React.Children.map(children, child => { return ( <Island {...child.props} color={color} dark={isDark} size={size}> {child.props.children} </Island> ); })} </Box> ); } } IslandGroup.propTypes = { children: PropTypes.any, className: PropTypes.string, color: PropTypes.oneOf(['neutral', 'mint', 'violet', 'ruby', 'gold', 'aqua', 'white']), dark: PropTypes.bool, size: PropTypes.oneOf(['small', 'medium', 'large']), }; IslandGroup.defaultProps = { color: 'white', }; export default IslandGroup;
Fix bug with header categories
<?php namespace ATPCms\Model; require_once("Page.php"); require_once("StaticBlock.php"); class Category extends \ATP\ActiveRecord { public function displayName() { return $this->name; } public static function headerCategories() { $cat = new self(); return $cat->loadMultiple(array( 'where' => "show_in_header=1" )); } public function mostRecent($count) { $page = new Page(); return $page->loadMultiple(array( 'where' => "category_id = ? AND is_active=1", 'data' => array($this->id), 'orderBy' => "post_date DESC", 'limit' => $count )); } } Category::init();
<?php namespace ATPCms\Model; require_once("Page.php"); require_once("StaticBlock.php"); class Category extends \ATP\ActiveRecord { public function displayName() { return $this->name; } public static function headerCategories() { $where = "show_in_header=1"; $cat = new self(); return $cat->loadMultiple($where); } public function mostRecent($count) { $page = new Page(); return $page->loadMultiple(array( 'where' => "category_id = ? AND is_active=1", 'data' => array($this->id), 'orderBy' => "post_date DESC", 'limit' => $count )); } } Category::init();
Fix a SQL error in email validation
<?php use FelixOnline\Exceptions; class ValidationController extends BaseController { function GET($matches) { try { $code = \FelixOnline\Core\BaseManager::build('FelixOnline\Core\EmailValidation', 'email_validation') ->filter('code = "%s"', array($matches['code'])) ->one(); } catch (Exceptions\InternalException $e) { throw new NotFoundException( $e->getMessage(), $matches, 'ValidationController', FrontendException::EXCEPTION_NOTFOUND, $e ); } $code->setConfirmed(1)->save(); try { $comments = \FelixOnline\Core\BaseManager::build('FelixOnline\Core\Comment', 'comment') ->filter('email = "%s"', array($code->getEmail())) ->filter('active = 1') ->filter('spam = 0') ->values(); foreach($comments as $comment) { if ($comment->getReply()) { // if comment is replying to an internal comment $comment->emailReply(); } // email authors of article $comment->emailAuthors(); } } catch (\Exception $e) { } $this->theme->appendData(array( 'email' => $code->getEmail() )); $this->theme->render('validation'); } }
<?php use FelixOnline\Exceptions; class ValidationController extends BaseController { function GET($matches) { try { $code = \FelixOnline\Core\BaseManager::build('FelixOnline\Core\EmailValidation', 'email_validation') ->filter('code = "%s"', array($matches['code'])) ->one(); } catch (Exceptions\InternalException $e) { throw new NotFoundException( $e->getMessage(), $matches, 'ValidationController', FrontendException::EXCEPTION_NOTFOUND, $e ); } $code->setConfirmed(1)->save(); try { $comments = \FelixOnline\Core\BaseManager::build('FelixOnline\Core\Comment', 'comment') ->filter('email = "%s"', array($code->getEmail())) ->filter('rejected = 0') ->filter('spam = 0') ->values(); foreach($comments as $comment) { if ($comment->getReply()) { // if comment is replying to an internal comment $comment->emailReply(); } // email authors of article $comment->emailAuthors(); } } catch (\Exception $e) { } $this->theme->appendData(array( 'email' => $code->getEmail() )); $this->theme->render('validation'); } }
Add appearance count to the API.
# -*- coding: utf-8 -*- from rest_framework import serializers from apps.broadcasts.models import Broadcast, Host, Raid, Series from apps.games.models import Game, Platform from apps.subscribers.models import Ticket class HostSerializer(serializers.ModelSerializer): class Meta: fields = ('id', 'timestamp', 'username', 'broadcast') model = Host class RaidSerializer(serializers.ModelSerializer): class Meta: fields = ('id', 'timestamp', 'username', 'broadcast', 'game') model = Raid class SeriesSerializer(serializers.ModelSerializer): class Meta: model = Series class GameSerializer(serializers.ModelSerializer): appearances = serializers.IntegerField(source='appears_on.count', read_only=True) class Meta: model = Game class PlatformSerializer(serializers.ModelSerializer): class Meta: model = Platform class TicketSerializer(serializers.ModelSerializer): class Meta: model = Ticket class BroadcastSerializer(serializers.ModelSerializer): hosts = serializers.PrimaryKeyRelatedField(many=True, read_only=True) raids = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Broadcast
# -*- coding: utf-8 -*- from rest_framework import serializers from apps.broadcasts.models import Broadcast, Host, Raid, Series from apps.games.models import Game, Platform from apps.subscribers.models import Ticket class HostSerializer(serializers.ModelSerializer): class Meta: fields = ('id', 'timestamp', 'username', 'broadcast') model = Host class RaidSerializer(serializers.ModelSerializer): class Meta: fields = ('id', 'timestamp', 'username', 'broadcast', 'game') model = Raid class SeriesSerializer(serializers.ModelSerializer): class Meta: model = Series class GameSerializer(serializers.ModelSerializer): class Meta: model = Game class PlatformSerializer(serializers.ModelSerializer): class Meta: model = Platform class TicketSerializer(serializers.ModelSerializer): class Meta: model = Ticket class BroadcastSerializer(serializers.ModelSerializer): hosts = serializers.PrimaryKeyRelatedField(many=True, read_only=True) raids = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Broadcast
Set full versions on all dependencies and updated most to latest version
from setuptools import setup, find_packages package_data = ['static/css/*', 'static/img/*', 'static/js/*', 'static/js/templates/*', 'templates/djukebox/*'] dependencies = ['Pillow==2.1.0', 'django-celery==3.0.21', 'mutagen==1.21', 'simplejson==3.3.0', 'django-bootstrap-form', 'django-tastypie==0.9.15'] setup(name = "djukebox", version = "0.2.0", description = "A django HTML 5 audio player", author = "Justin Michalicek", author_email = "jmichalicek@gmail.com", url = "https://github.com/jmichalicek/djukebox/", license = "www.opensource.org/licenses/bsd-license.php", packages = find_packages(), #'package' package must contain files (see list above) package_data = {'djukebox' : package_data }, install_requires = dependencies, long_description = """A HTML 5 audio player using Django""" #This next part it for the Cheese Shop, look a little down the page. #classifiers = [] )
from setuptools import setup, find_packages package_data = ['static/css/*', 'static/img/*', 'static/js/*', 'static/js/templates/*', 'templates/djukebox/*'] dependencies = ['pillow', 'django-celery==2.5.5', 'mutagen', 'simplejson', 'django-bootstrap-form', 'django-tastypie==0.9.15'] setup(name = "djukebox", version = "0.2.0", description = "A django HTML 5 audio player", author = "Justin Michalicek", author_email = "jmichalicek@gmail.com", url = "https://github.com/jmichalicek/djukebox/", license = "www.opensource.org/licenses/bsd-license.php", packages = find_packages(), #'package' package must contain files (see list above) package_data = {'djukebox' : package_data }, install_requires = dependencies, long_description = """A HTML 5 audio player using Django""" #This next part it for the Cheese Shop, look a little down the page. #classifiers = [] )
Add key for JSON string
package data; import util.UserAuthUtil; /** Class to build Login/Logout response objects in JSON format */ public class ResponseBuilder { /** * @param isLoggedIn user login status * @param redirectURL URL to redirect after login/logout * @return JSON string with login/logout URL * e.g., logged in: { "isLoggedIn":{"loginURL" : "/_ah/logout?continue=%2FLogin"}, "isLoggedOut":{""}} * logged out: { "isLoggedIn":{""}, "isLoggedOut":{"logoutURL" : "/_ah/login?continue=%2FLogin"}} */ public static String toJson(boolean isLoggedIn, String redirectURL) { return "{ \"isLoggedIn\":{\"" + buildLogout(isLoggedIn, redirectURL) + "\"}, " + "\"isLoggedOut\":{\"" + buildLogin(isLoggedIn, redirectURL) + "\"}}"; } private static String buildLogin(boolean isLoggedIn, String redirectURL) { return isLoggedIn ? "" : "\"loginURL\" :" + UserAuthUtil.getLoginURL(redirectURL); } private static String buildLogout(boolean isLoggedIn, String redirectURL) { return isLoggedIn ? "\"logoutURL\" :" + UserAuthUtil.getLogoutURL(redirectURL) : ""; } }
package data; import util.UserAuthUtil; /** Class to build Login/Logout response objects in JSON format */ public class ResponseBuilder { /** * @param isLoggedIn user login status * @param redirectURL URL to redirect after login/logout * @return JSON string with login/logout URL * e.g., logged in: { "isLoggedIn":{"/_ah/logout?continue=%2FLogin"}, "isLoggedOut":{""}} * logged out: { "isLoggedIn":{""}, "isLoggedOut":{"/_ah/login?continue=%2FLogin"}} */ public static String toJson(boolean isLoggedIn, String redirectURL) { return "{ \"isLoggedIn\":{\"" + buildLogout(isLoggedIn, redirectURL) + "\"}, " + "\"isLoggedOut\":{\"" + buildLogin(isLoggedIn, redirectURL) + "\"}}"; } private static String buildLogin(boolean isLoggedIn, String redirectURL) { return isLoggedIn ? "" : UserAuthUtil.getLoginURL(redirectURL); } private static String buildLogout(boolean isLoggedIn, String redirectURL) { return isLoggedIn ? UserAuthUtil.getLogoutURL(redirectURL) : ""; } }
Return after flushing the database
var messenger = require('../lib/messenger'); var session = require('../lib/session'); module.exports = function (server) { server.post('/messages', function (req, res, next) { var phoneNumber = req.params.From; var message = req.params.Body.toLowerCase(); if (message === 'flush') { session.flushall(function () { messenger.send(phoneNumber, 'The database has been flushed.'); }); res.send(200); return; } session.get(phoneNumber, function(err, user) { if (err) { messenger.fail(phoneNumber); res.send(500); } if (user) { messenger.send(phoneNumber, 'Hello, old friend. (' + user + ')' ); } else { session.set(phoneNumber, 'initial', function () { messenger.send(phoneNumber, 'Nice to meet you.'); }); } }); res.send(200, {status: 'ok'}); }); }
var messenger = require('../lib/messenger'); var session = require('../lib/session'); module.exports = function (server) { server.post('/messages', function (req, res, next) { var phoneNumber = req.params.From; var message = req.params.Body.toLowerCase(); if (message === 'flush') { session.flushall(function () { messenger.send(phoneNumber, 'The database has been flushed.'); }); } session.get(phoneNumber, function(err, user) { if (err) { messenger.fail(phoneNumber); res.send(500); } if (user) { messenger.send(phoneNumber, 'Hello, old friend. (' + user + ')' ); } else { session.set(phoneNumber, 'initial', function () { messenger.send(phoneNumber, 'Nice to meet you.'); }); } }); res.send(200, {status: 'ok'}); }); }