text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Make cards hoverable for dat ux
@extends('layouts.default') @section('content') <main class="container events"> <hr /> <h1>{{$day}}</h1> <hr /> <div class="row"> @foreach($events as $event) <div class="col s12 m6 l4"> <div class="card hoverable"> @if( $event->image ) <div class="card-image"> <a href="https://www.facebook.com/events/{{$event->facebook_id}}"> <img src="{{$event->image}}"> </a> </div> @endif <div class="card-content"> <h4>{{$event->title}}</h5> <h5>{{$event->society()->first()->name}} Society</h5> <p>{{date('H:i, l j F', strtotime($event->time))}}@if($event->location), <strong>{{$event->location}}</strong>@endif</p> @if($event->description) <p>{{$event->description}}</p> @endif </div> <div class="card-action"> <a href="https://www.facebook.com/events/{{$event->facebook_id}}"> Facebook Event </a> <a href="{{URL::to('/event/' . $event->id . '/calendar')}}" class="calendar-button"> Add To Calendar </a> </div> </div> </div> @endforeach </div> </main> @endsection
@extends('layouts.default') @section('content') <main class="container events"> <hr /> <h1>{{$day}}</h1> <hr /> <div class="row"> @foreach($events as $event) <div class="col s12 m6 l4"> <div class="card"> @if( $event->image ) <div class="card-image"> <a href="https://www.facebook.com/events/{{$event->facebook_id}}"> <img src="{{$event->image}}"> </a> </div> @endif <div class="card-content"> <h4>{{$event->title}}</h5> <h5>{{$event->society()->first()->name}} Society</h5> <p>{{date('H:i, l j F', strtotime($event->time))}}@if($event->location), <strong>{{$event->location}}</strong>@endif</p> @if($event->description) <p>{{$event->description}}</p> @endif </div> <div class="card-action"> <a href="https://www.facebook.com/events/{{$event->facebook_id}}"> Facebook Event </a> <a href="{{URL::to('/event/' . $event->id . '/calendar')}}" class="calendar-button"> Add To Calendar </a> </div> </div> </div> @endforeach </div> </main> @endsection
Add user factory to auth handler
<?php namespace Colorium\Stateful; abstract class Auth { /** @var provider */ protected static $provider; /** @var \Closure */ protected static $factory; /** @var object */ protected static $user; /** @var string */ protected static $root = '__AUTH__'; /** * Load session provider * * @param provider $provider * @return provider */ public static function provider(provider $provider = null) { if($provider) { static::$provider = $provider; } elseif(!static::$provider) { static::$provider = new provider\Native(static::$root); } return static::$provider; } /** * Set user factory * * @param \Closure $factory */ public static function factory(\Closure $factory) { static::$factory = $factory; } /** * Get user rank * * @return int */ public static function rank() { return static::provider()->get('rank', 0); } /** * Get user ref * * @return string */ public static function ref() { return static::provider()->get('ref'); } /** * Get user object * * @return object */ public static function user() { if(!static::$user and static::$factory) { static::$user = call_user_func(static::$factory, static::ref()); } return static::$user; } /** * Log user in session * * @param int $rank * @param string $ref */ public static function login($rank = 1, $ref = null) { static::provider()->set('rank', $rank); static::provider()->set('ref', $ref); } /** * Log user out of session */ public static function logout() { static::provider()->drop('rank'); static::provider()->drop('ref'); } }
<?php namespace Colorium\Stateful; abstract class Auth { /** @var Provider */ protected static $provider; /** @var string */ protected static $root = '__AUTH__'; /** * Load session provider * * @param Provider $provider * @return Provider */ public static function provider(Provider $provider = null) { if($provider) { static::$provider = $provider; } elseif(!static::$provider) { static::$provider = new Provider\Native(static::$root); } return static::$provider; } /** * Get user rank * * @return int */ public static function rank() { return static::provider()->get('rank', 0); } /** * Get user object * * @return object */ public static function user() { return static::provider()->get('user'); } /** * Log user in session * * @param int $rank * @param object $user */ public static function login($rank = 1, $user = null) { static::provider()->set('rank', $rank); static::provider()->set('user', $user); } /** * Log user out of session */ public static function logout() { static::provider()->drop('rank'); static::provider()->drop('user'); } }
Create destination directory if not exists
<?php namespace phtamas\yii2\imagecontroller; use yii\base\Action as BaseAction; use yii\web\NotFoundHttpException; class Action extends BaseAction { /** * @var \phtamas\yii2\imageprocessor\Component */ public $imageProcessor; /** * @var string */ public $sourceDir; /** * @var bool */ public $save = false; /** * @var null|string */ public $destinationDir; public function run($filename) { $filename = basename($filename); $sourceDir = \Yii::getAlias($this->sourceDir); $destinationDir = \Yii::getAlias($this->destinationDir); $sourcePath = $sourceDir . '/' . $filename; if (!is_file($sourcePath)) { throw new NotFoundHttpException(); } if ($this->save) { if (!is_dir($destinationDir)) { mkdir($destinationDir); } $this->imageProcessor->saveAndSend( $sourcePath, $destinationDir . '/' . $filename, pathinfo($filename, PATHINFO_EXTENSION), $this->id ); } else { $this->imageProcessor->send( $sourcePath, pathinfo($filename, PATHINFO_EXTENSION), $this->id ); } } }
<?php namespace phtamas\yii2\imagecontroller; use yii\base\Action as BaseAction; use yii\web\NotFoundHttpException; class Action extends BaseAction { /** * @var \phtamas\yii2\imageprocessor\Component */ public $imageProcessor; /** * @var string */ public $sourceDir; /** * @var bool */ public $save = false; /** * @var null|string */ public $destinationDir; public function run($filename) { $filename = basename($filename); $sourcePath = \Yii::getAlias($this->sourceDir) . '/' . $filename; if (!is_file($sourcePath)) { throw new NotFoundHttpException(); } if ($this->save) { $this->imageProcessor->saveAndSend( \Yii::getAlias($this->sourceDir) . '/' . $filename, \Yii::getAlias($this->destinationDir) . '/' . $filename, pathinfo($filename, PATHINFO_EXTENSION), $this->id ); } else { $this->imageProcessor->send( \Yii::getAlias($this->sourceDir) . '/' . $filename, pathinfo($filename, PATHINFO_EXTENSION), $this->id ); } } }
Fix a lint indent issue
from ..auth_provider import KnowledgeAuthProvider from ..models import User from flask import ( redirect, render_template, request, url_for, ) from ldap3 import Connection, Server, ALL from knowledge_repo.constants import AUTH_LOGIN_FORM, LDAP, USERNAME class LdapAuthProvider(KnowledgeAuthProvider): _registry_keys = [LDAP] def init(self): if not self.app.config.get('LDAP_SERVER'): raise RuntimeError( 'Use of LDAP authentication requires specification ' 'of the LDAP_SERVER configuration variable.') self.server = Server(self.app.config['LDAP_SERVER'], get_info=ALL) def prompt(self): return render_template(AUTH_LOGIN_FORM, skip_password=False) def authorize(self): user = self.get_user() if user is None: raise RuntimeError('No such user or invalid credentials') if self.validate(user) is False: return render_template( AUTH_LOGIN_FORM, error_message='Uh-oh, it looks like something in ' 'your credentials was wrong...') self._perform_login(user) return redirect(url_for('index.render_feed')) def validate(self, user): userdn = self.app.config['LDAP_USERDN_SCHEMA'].format(user_id=user.identifier) password = request.form['password'] conn = Connection(self.server, user=userdn, password=password) return conn.bind() def get_user(self): return User(identifier=request.form[USERNAME])
from ..auth_provider import KnowledgeAuthProvider from ..models import User from flask import ( redirect, render_template, request, url_for, ) from ldap3 import Server, Connection, ALL from knowledge_repo.constants import AUTH_LOGIN_FORM, LDAP, USERNAME class LdapAuthProvider(KnowledgeAuthProvider): _registry_keys = [LDAP] def init(self): if not self.app.config.get('LDAP_SERVER'): raise RuntimeError( 'Use of LDAP authentication requires specification ' 'of the LDAP_SERVER configuration variable.') self.server = Server(self.app.config['LDAP_SERVER'], get_info=ALL) def prompt(self): return render_template(AUTH_LOGIN_FORM, skip_password=False) def authorize(self): user = self.get_user() if user is None: raise RuntimeError('No such user or invalid credentials') if self.validate(user) is False: return render_template(AUTH_LOGIN_FORM, error_message='Uh-oh, it looks like something in ' 'your credentials was wrong...') self._perform_login(user) return redirect(url_for('index.render_feed')) def validate(self, user): userdn = self.app.config['LDAP_USERDN_SCHEMA'].format(user_id=user.identifier) password = request.form['password'] conn = Connection(self.server, user=userdn, password=password) return conn.bind() def get_user(self): return User(identifier=request.form[USERNAME])
Fix login controller to go to correct route.
Application.Controllers.controller('login', ["$scope", "$state", "User", "alertService", "mcapi", "Nav", "pubsub", "model.projects", "projectFiles", function ($scope, $state, User, alertService, mcapi, Nav, pubsub, projects, projectFiles) { $scope.login = function () { mcapi('/user/%/apikey', $scope.email, $scope.password) .success(function (u) { User.setAuthenticated(true, u); pubsub.send("tags.change"); Nav.setActiveNav('home'); projects.clear(); projectFiles.clear(); projects.getList().then(function(projects) { $state.go('projects.project.home', {id: projects[0].id}); }); }) .error(function (data) { alertService.sendMessage(data.error); }).put({password: $scope.password}); }; $scope.cancel = function () { $state.transitionTo('home'); }; }]);
Application.Controllers.controller('login', ["$scope", "$state", "User", "alertService", "mcapi", "Nav", "pubsub", "model.projects", "projectFiles", function ($scope, $state, User, alertService, mcapi, Nav, pubsub, projects, projectFiles) { $scope.login = function () { mcapi('/user/%/apikey', $scope.email, $scope.password) .success(function (u) { User.setAuthenticated(true, u); pubsub.send("tags.change"); Nav.setActiveNav('home'); projects.clear(); projectFiles.clear(); projects.getList().then(function(projects) { $state.go('projects.project.overview', {id: projects[0].id}); }); }) .error(function (data) { alertService.sendMessage(data.error); }).put({password: $scope.password}); }; $scope.cancel = function () { $state.transitionTo('home'); }; }]);
Add check for holding any of the Appointments Collection
<?php namespace App; use Illuminate\Support\Collection; use Illuminate\Database\Eloquent\Model; use Carbon\Carbon; class Vacancy extends Model { protected $fillable = ['business_id', 'service_id', 'date', 'start_at', 'finish_at', 'capacity']; protected $guarded = ['id']; protected $dates = ['start_at', 'finish_at']; public function business() { return $this->belongsTo('App\Business'); } public function service() { return $this->belongsTo('App\Service'); } public function scopeForDate($query, Carbon $date) { return $query->where('date', '=', $date->toDateString()); } public function scopeForService($query, Service $service) { return $query->where('service_id', '=', $service->id); } public function isFull(Collection $appointments) { $slots = $this->capacity; foreach ($appointments as $appointment) { if ($this->holdsAppointment($appointment)) { $slots--; } } return $slots < 1; } public function holdsAppointment(Appointment $appointment) { return (($this->date == $appointment->date) && ($this->service_id == $appointment->service_id) && ($this->business_id == $appointment->business_id)); } public function holdsAnyAppointment(Collection $appointments) { foreach ($appointments as $appointment) { if ($this->holdsAppointment($appointment)) return true; } return false; } }
<?php namespace App; use Illuminate\Support\Collection; use Illuminate\Database\Eloquent\Model; use Carbon\Carbon; class Vacancy extends Model { protected $fillable = ['business_id', 'service_id', 'date', 'start_at', 'finish_at', 'capacity']; protected $guarded = ['id']; protected $dates = ['start_at', 'finish_at']; public function business() { return $this->belongsTo('App\Business'); } public function service() { return $this->belongsTo('App\Service'); } public function scopeForDate($query, Carbon $date) { return $query->where('date', '=', $date->toDateString()); } public function scopeForService($query, Service $service) { return $query->where('service_id', '=', $service->id); } public function isFull(Collection $appointments) { $slots = $this->capacity; foreach ($appointments as $appointment) { if ($this->holdsAppointment($appointment)) { $slots--; } } return $slots < 1; } public function holdsAppointment(Appointment $appointment) { return (($this->date == $appointment->date) && ($this->service_id == $appointment->service_id) && ($this->business_id == $appointment->business_id)); } }
Fix for queued job support
<?php /** * If the queued jobs module is installed, this will be used instead of * updating vfi's in onBeforeWrite. * * @author Mark Guinn <[email protected]> * @date 07.02.2015 * @package shop_search * @subpackage helpers */ if (!interface_exists('QueuedJob')) { return; } class VirtualFieldIndexQueuedJob extends AbstractQueuedJob implements QueuedJob { /** * The QueuedJob queue to use when processing updates * @config * @var int */ private static $reindex_queue = 2; // QueuedJob::QUEUED; /** * @param DataObject $object * @param array $fields */ public function __construct($object = null, $fields = array()) { if ($object) { $this->setObject($object); } $this->rebuildFields = $fields; } /** * Helper method */ public function triggerProcessing() { singleton('QueuedJobService')->queueJob($this); } /** * @return string */ public function getTitle() { $obj = $this->getObject(); return "Update Virtual Field Indexes: " . ($obj ? $obj->getTitle() : '???'); } /** * Reprocess any needed fields */ public function process() { Versioned::reading_stage('Stage'); /** @var DataObject|VirtualFieldIndex $obj */ $obj = $this->getObject(); if ($obj) { $obj->rebuildVFI(); } $this->isComplete = true; } }
<?php /** * If the queued jobs module is installed, this will be used instead of * updating vfi's in onBeforeWrite. * * @author Mark Guinn <[email protected]> * @date 07.02.2015 * @package shop_search * @subpackage helpers */ if (!interface_exists('QueuedJob')) { return; } class VirtualFieldIndexQueuedJob extends AbstractQueuedJob implements QueuedJob { /** * The QueuedJob queue to use when processing updates * @config * @var int */ private static $reindex_queue = 2; // QueuedJob::QUEUED; /** * @param DataObject $object * @param array $fields */ public function __construct($object, array $fields) { $this->setObject($object); $this->rebuildFields = $fields; } /** * Helper method */ public function triggerProcessing() { singleton('QueuedJobService')->queueJob($this); } /** * @return string */ public function getTitle() { $obj = $this->getObject(); return "Update Virtual Field Indexes: " . ($obj ? $obj->getTitle() : '???'); } /** * Reprocess any needed fields */ public function process() { Versioned::reading_stage('Stage'); $obj = $this->getObject(); if ($obj) { $obj->rebuildVFI(); } $this->isComplete = true; } }
Allow for generators in ipc handlers
const { ipcMain } = require('electron'); function isPromise(object) { return object.then && typeof(object.then) === 'function'; } function isGenerator(object) { return object.next && typeof(object.next) === 'function'; } class IPCHandler { handle(event, funct, binding = this) { const localFunc = funct.bind(binding); ipcMain.on(event, (ev, ...args) => { const localFuncResult = localFunc(...args); if(isPromise(localFuncResult)) { localFuncResult.then((...result) => { ev.sender.send(event, ...result); }); } else if(isGenerator(localFuncResult)) { for(let result of localFuncResult) { ev.sender.send(event, result); } } else { ev.sender.send(event, localFuncResult); } }); } handleSync(event, funct, binding = this) { const localFunc = funct.bind(binding); ipcMain.on(event, (ev, ...args) => { const localFuncResult = localFunc(...args); if(isPromise(localFuncResult)) { localFuncResult.then((result) => { ev.returnValue = result; }); } else { ev.returnValue = localFuncResult; } }); } provide(event, func) { const localFunc = func.bind(this); ipcMain.on(event, localFunc); } } module.exports = IPCHandler;
const { ipcMain } = require('electron'); class IPCHandler { handle(event, funct, binding = this) { const localFunc = funct.bind(binding); ipcMain.on(event, (ev, ...args) => { const localFuncResult = localFunc(...args); if(localFuncResult.then) { localFuncResult.then((...result) => { ev.sender.send(event, ...result); }); } else { ev.sender.send(event, localFuncResult); } }); } handleSync(event, funct, binding = this) { const localFunc = funct.bind(binding); ipcMain.on(event, (ev, ...args) => { const localFuncResult = localFunc(...args); if(localFuncResult.then) { localFuncResult.then((result) => { ev.returnValue = result; }); } else { ev.returnValue = localFuncResult; } }); } provide(event, func) { const localFunc = func.bind(this); ipcMain.on(event, localFunc); } } module.exports = IPCHandler;
Allow for multiple mappings by dbxref
<?php namespace AppBundle\API\Mapping; use AppBundle\API\Webservice; use AppBundle\User\FennecUser; use Symfony\Component\HttpFoundation\ParameterBag; class ByDbxrefId extends Webservice { private $db; /** * @inheritdoc */ public function execute(ParameterBag $query, FennecUser $user = null) { $this->db = $this->getManagerFromQuery($query)->getConnection(); if(!$query->has('ids') || !is_array($query->get('ids')) || count($query->get('ids')) === 0 || !$query->has('db')){ return array(); } $ids = $query->get('ids'); $result = array_fill_keys($ids, null); $placeholders = implode(',', array_fill(0, count($ids), '?')); $query_get_mapping = <<<EOF SELECT fennec_id, identifier FROM fennec_dbxref WHERE db_id=(SELECT db_id FROM db WHERE name=?) AND identifier IN ({$placeholders}) EOF; $stm_get_mapping = $this->db->prepare($query_get_mapping); $stm_get_mapping->execute(array_merge([$query->get('db')], $ids)); while($row = $stm_get_mapping->fetch(\PDO::FETCH_ASSOC)){ $id = $row['identifier']; if($result[$id] === null){ $result[$id] = $row['fennec_id']; } else { if(! is_array($result[$id]) ){ $result[$id] = [$result[$id]]; } $result[$id][] = $row['fennec_id']; } } return $result; } }
<?php namespace AppBundle\API\Mapping; use AppBundle\API\Webservice; use AppBundle\User\FennecUser; use Symfony\Component\HttpFoundation\ParameterBag; class ByDbxrefId extends Webservice { private $db; /** * @inheritdoc */ public function execute(ParameterBag $query, FennecUser $user = null) { $this->db = $this->getManagerFromQuery($query)->getConnection(); if(!$query->has('ids') || !is_array($query->get('ids')) || count($query->get('ids')) === 0 || !$query->has('db')){ return array(); } $ids = $query->get('ids'); $result = array_fill_keys($ids, null); $placeholders = implode(',', array_fill(0, count($ids), '?')); $query_get_mapping = <<<EOF SELECT fennec_id, identifier AS ncbi_taxid FROM fennec_dbxref WHERE db_id=(SELECT db_id FROM db WHERE name=?) AND identifier IN ({$placeholders}) EOF; $stm_get_mapping = $this->db->prepare($query_get_mapping); $stm_get_mapping->execute(array_merge([$query->get('db')], $ids)); while($row = $stm_get_mapping->fetch(\PDO::FETCH_ASSOC)){ $result[$row['ncbi_taxid']] = $row['fennec_id']; } return $result; } }
Rename var name as same asa parameter
<?php declare(strict_types=1); namespace Ray\Di\MultiBinding; use Koriym\ParamReader\ParamReaderInterface; use Ray\Di\Di\Set; use Ray\Di\Exception\SetNotFound; use Ray\Di\InjectionPointInterface; use Ray\Di\InjectorInterface; use Ray\Di\ProviderInterface; final class MapProvider implements ProviderInterface { /** @var MultiBindings */ private $multiBindings; /** @var InjectionPointInterface */ private $ip; /** @var InjectorInterface */ private $injector; /** @var ParamReaderInterface */ private $reader; public function __construct( InjectionPointInterface $ip, MultiBindings $multiBindings, InjectorInterface $injector, ParamReaderInterface $reader ) { $this->multiBindings = $multiBindings; $this->ip = $ip; $this->injector = $injector; $this->reader = $reader; } public function get(): Map { /** @var ?Set $set */ $set = $this->reader->getParametrAnnotation($this->ip->getParameter(), Set::class); if ($set === null) { throw new SetNotFound((string) $this->ip->getParameter()); } /** @var array<string, LazyTo<object>> $lazies */ $lazies = $this->multiBindings[$set->interface]; return new Map($lazies, $this->injector); } }
<?php declare(strict_types=1); namespace Ray\Di\MultiBinding; use Koriym\ParamReader\ParamReaderInterface; use Ray\Di\Di\Set; use Ray\Di\Exception\SetNotFound; use Ray\Di\InjectionPointInterface; use Ray\Di\InjectorInterface; use Ray\Di\ProviderInterface; final class MapProvider implements ProviderInterface { /** @var MultiBindings */ private $multiBindings; /** @var InjectionPointInterface */ private $ip; /** @var InjectorInterface */ private $injector; /** @var ParamReaderInterface */ private $reader; public function __construct( InjectionPointInterface $ip, MultiBindings $multiBindings, InjectorInterface $injector, ParamReaderInterface $reader ) { $this->multiBindings = $multiBindings; $this->ip = $ip; $this->injector = $injector; $this->reader = $reader; } public function get(): Map { /** @var ?Set $set */ $set = $this->reader->getParametrAnnotation($this->ip->getParameter(), Set::class); if ($set === null) { throw new SetNotFound((string) $this->ip->getParameter()); } /** @var array<string, LazyTo<object>> $keyBasedLazy */ $keyBasedLazy = $this->multiBindings[$set->interface]; return new Map($keyBasedLazy, $this->injector); } }
:art: Refactor rule to work with gonzales 3.2.1
'use strict'; var helpers = require('../helpers'); module.exports = { 'name': 'space-after-comma', 'defaults': { 'include': true }, 'detect': function (ast, parser) { var result = []; ast.traverseByTypes(['operator', 'delimiter'], function (operator, i, parent) { var next, doubleNext; if (operator.content === ',') { next = parent.content[i + 1] || false; doubleNext = parent.content[i + 2] || false; if (next) { if (operator.is('delimiter')) { if (next.is('selector')) { next = next.content[0]; } } if ((next.is('space') && !helpers.hasEOL(next.content)) && !parser.options.include) { if (doubleNext && doubleNext.is('singlelineComment')) { return false; } result = helpers.addUnique(result, { 'ruleId': parser.rule.name, 'line': next.start.line, 'column': next.start.column, 'message': 'Commas should not be followed by a space', 'severity': parser.severity }); } if (!next.is('space') && parser.options.include) { result = helpers.addUnique(result, { 'ruleId': parser.rule.name, 'line': operator.start.line, 'column': operator.start.column, 'message': 'Commas should be followed by a space', 'severity': parser.severity }); } } } }); return result; } };
'use strict'; var helpers = require('../helpers'); module.exports = { 'name': 'space-after-comma', 'defaults': { 'include': true }, 'detect': function (ast, parser) { var result = []; ast.traverseByTypes(['operator', 'delimiter'], function (operator, i, parent) { var next; if (operator.content === ',') { next = parent.content[i + 1]; if (next) { if (operator.is('delimiter')) { if (next.is('simpleSelector')) { next = next.content[0]; } } if ((next.is('space') && !helpers.hasEOL(next.content)) && !parser.options.include) { result = helpers.addUnique(result, { 'ruleId': parser.rule.name, 'line': next.start.line, 'column': next.start.column, 'message': 'Commas should not be followed by a space', 'severity': parser.severity }); } if (!next.is('space') && parser.options.include) { result = helpers.addUnique(result, { 'ruleId': parser.rule.name, 'line': operator.start.line, 'column': operator.start.column, 'message': 'Commas should be followed by a space', 'severity': parser.severity }); } } } }); return result; } };
Implement Gref.tips() to fetch it's tips.
import os class Gref(object): def __init__(self, store, channel, identifier): self.store = store self.channel = channel.replace("/", "_") self.identifier = identifier self._node_path = os.path.join(self.store.gref_path(), self.channel, self.identifier) def __str__(self): return "%s/%s" % (self.channel, self.identifier) def exists(self): return os.path.exists(self._node_path) def tips(self): return os.listdir(self._node_path) def node_path(self): if not self.exists(): os.makedirs(self._node_path) return self._node_path def write_tip(self, tip, signature): tip_path = self.tip_path(tip) open(tip_path, 'a').close() fh = open(tip_path, 'r+') fh.seek(0) fh.write(signature) fh.truncate() fh.close() def tip_path(self, tip): return os.path.join(self.node_path(), tip) def __iter__(self): return os.listdir(self.node_path()).__iter__() def remove_tip(self, tip): try: os.unlink(os.path.join(self.tip_path(tip))) except: raise def as_dict(self): return { "channel": self.channel, "identifier": self.identifier, "node_path": self._node_path }
import os class Gref(object): def __init__(self, store, channel, identifier): self.store = store self.channel = channel.replace("/", "_") self.identifier = identifier self._node_path = os.path.join(self.store.gref_path(), self.channel, self.identifier) def __str__(self): return "%s/%s" % (self.channel, self.identifier) def exists(self): return os.path.exists(self._node_path) def node_path(self): if not self.exists(): os.makedirs(self._node_path) return self._node_path def write_tip(self, tip, signature): tip_path = self.tip_path(tip) open(tip_path, 'a').close() fh = open(tip_path, 'r+') fh.seek(0) fh.write(signature) fh.truncate() fh.close() def tip_path(self, tip): return os.path.join(self.node_path(), tip) def __iter__(self): return os.listdir(self.node_path()).__iter__() def remove_tip(self, tip): try: os.unlink(os.path.join(self.tip_path(tip))) except: raise def as_dict(self): return { "channel": self.channel, "identifier": self.identifier, "node_path": self._node_path }
Remove text to make tweet unique for testing
# Listener Class Override import time import json from tweepy.streaming import StreamListener import sys class Listener(StreamListener): def __init__(self, twitter_api, start_time=time.time()): self.time = start_time self.api = twitter_api def on_data(self, data): # uids we are currently trackin user_ids = [ 842062946, 896881849, 786673790, 1003145436, 1702767096, 2767456571, 2844888263, 19991403, 2516461339 ] try: uid = json.loads(data)["user"]["id"] print "UID:" + str(uid) if (uid in user_ids): tweet = json.loads(data)["text"] print "tweeting " + tweet + "..." self.api.update_status(status = tweet) print "Done." else: print "Do nothing. UID:" + str(uid) + " not tracked." time.sleep(5) saveFile = open("raw_tweets.json", "a") saveFile.write(data) saveFile.write("\n") saveFile.close() return True except BaseException, e: print "failed in ondata,", str(e) time.sleep(5) pass def on_error(self, status): print status
# Listener Class Override import time import json from tweepy.streaming import StreamListener import sys class Listener(StreamListener): def __init__(self, twitter_api, start_time=time.time()): self.time = start_time self.api = twitter_api def on_data(self, data): # uids we are currently trackin user_ids = [ 842062946, 896881849, 786673790, 1003145436, 1702767096, 2767456571, 2844888263, 19991403, 2516461339 ] try: uid = json.loads(data)["user"]["id"] print "UID:" + str(uid) if (uid in user_ids): tweet = json.loads(data)["text"] + "something" print "tweeting " + tweet + "..." self.api.update_status(status = tweet) print "Done." else: print "Do nothing. UID:" + str(uid) + " not tracked." time.sleep(5) saveFile = open("raw_tweets.json", "a") saveFile.write(data) saveFile.write("\n") saveFile.close() return True except BaseException, e: print "failed in ondata,", str(e) time.sleep(5) pass def on_error(self, status): print status
FIX "message: Class \SecucardConnect\Product\Payment\Model\Merchant does not exist" for some php versions
<?php namespace SecucardConnect\Product\Payment\Model; use SecucardConnect\Product\Common\Model\BaseModel; /** * Class Transactions * @package SecucardConnect\Product\Payment\Model */ class Transactions extends BaseModel { /** * @var \SecucardConnect\Product\General\Model\Merchant */ public $merchant; /** * @var int */ public $trans_id; /** * @var int */ public $product_id; /** * @var string */ public $product; /** * @var string */ public $product_raw; /** * @var int */ public $zahlungsmittel_id; /** * @var int */ public $contract_id; /** * @var int */ public $amount; /** * @var string */ public $currency; /** * @var string */ public $created; /** * @var string */ public $updated; /** * @var string */ public $description; /** * @var string */ public $description_raw; /** * @var int */ public $status; /** * @var string */ public $status_text; /** * @var array */ public $details; /** * @var \SecucardConnect\Product\Common\Model\Contact */ public $customer; /** * @var string */ public $incoming_payment_date; /** * @var string */ public $payout_date; }
<?php namespace SecucardConnect\Product\Payment\Model; use SecucardConnect\Product\Common\Model\BaseModel; use SecucardConnect\Product\Common\Model\Contact; use SecucardConnect\Product\General\Model\Merchant; /** * Class Transactions * @package SecucardConnect\Product\Payment\Model */ class Transactions extends BaseModel { /** * @var Merchant */ public $merchant; /** * @var int */ public $trans_id; /** * @var int */ public $product_id; /** * @var string */ public $product; /** * @var string */ public $product_raw; /** * @var int */ public $zahlungsmittel_id; /** * @var int */ public $contract_id; /** * @var int */ public $amount; /** * @var string */ public $currency; /** * @var string */ public $created; /** * @var string */ public $updated; /** * @var string */ public $description; /** * @var string */ public $description_raw; /** * @var int */ public $status; /** * @var string */ public $status_text; /** * @var array */ public $details; /** * @var Contact */ public $customer; /** * @var string */ public $incoming_payment_date; /** * @var string */ public $payout_date; }
Fix Product Picker to lookup SKU. Before: Ransack was not finding sku on product, thereby it was not including it in the search. After: Sku is correctly looked up on the product master.
$.fn.productAutocomplete = function (options) { 'use strict'; // Default options options = options || {}; var multiple = typeof(options.multiple) !== 'undefined' ? options.multiple : true; this.select2({ minimumInputLength: 3, multiple: multiple, initSelection: function (element, callback) { $.get(Spree.routes.product_search, { ids: element.val().split(','), token: Spree.api_key }, function (data) { callback(multiple ? data.products : data.products[0]); }); }, ajax: { url: Spree.routes.product_search, datatype: 'json', data: function (term, page) { return { q: { name_or_master_sku_cont: term, }, m: 'OR', token: Spree.api_key }; }, results: function (data, page) { var products = data.products ? data.products : []; return { results: products }; } }, formatResult: function (product) { return product.name; }, formatSelection: function (product) { return product.name; } }); }; $(document).ready(function () { $('.product_picker').productAutocomplete(); });
$.fn.productAutocomplete = function (options) { 'use strict'; // Default options options = options || {}; var multiple = typeof(options.multiple) !== 'undefined' ? options.multiple : true; this.select2({ minimumInputLength: 3, multiple: multiple, initSelection: function (element, callback) { $.get(Spree.routes.product_search, { ids: element.val().split(','), token: Spree.api_key }, function (data) { callback(multiple ? data.products : data.products[0]); }); }, ajax: { url: Spree.routes.product_search, datatype: 'json', data: function (term, page) { return { q: { name_cont: term, sku_cont: term }, m: 'OR', token: Spree.api_key }; }, results: function (data, page) { var products = data.products ? data.products : []; return { results: products }; } }, formatResult: function (product) { return product.name; }, formatSelection: function (product) { return product.name; } }); }; $(document).ready(function () { $('.product_picker').productAutocomplete(); });
Use Window instead of JFrame to find top-level parent.
/* * Copyright (c) 2009 Kathryn Huxtable and Kenneth Orr. * * This file is part of the SeaGlass Pluggable Look and Feel. * * 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. * * $Id$ */ package com.seaglass.state; import java.awt.Component; import java.awt.Window; import javax.swing.JComponent; import javax.swing.JInternalFrame; /** */ public class ToolBarWindowIsActiveState extends State { public ToolBarWindowIsActiveState() { super("WindowIsActive"); } protected boolean isInState(JComponent c) { Component parent = c; while (parent.getParent() != null) { if (parent instanceof JInternalFrame || parent instanceof Window) { break; } parent = parent.getParent(); } if (parent instanceof JInternalFrame) { return ((JInternalFrame) parent).isSelected(); } else if (parent instanceof Window) { return ((Window) parent).isFocused(); } // Default to true. return true; } }
/* * Copyright (c) 2009 Kathryn Huxtable and Kenneth Orr. * * This file is part of the SeaGlass Pluggable Look and Feel. * * 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. * * $Id$ */ package com.seaglass.state; import java.awt.Component; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JInternalFrame; /** */ public class ToolBarWindowIsActiveState extends State { public ToolBarWindowIsActiveState() { super("WindowIsActive"); } protected boolean isInState(JComponent c) { Component parent = c; while (parent.getParent() != null) { if (parent instanceof JInternalFrame || parent instanceof JFrame) { break; } parent = parent.getParent(); } if (parent instanceof JInternalFrame) { return ((JInternalFrame) parent).isSelected(); } else if (parent instanceof JFrame) { return ((JFrame) parent).isActive(); } // Default to true. return true; } }
Fix unicode declaration on test
from __future__ import unicode_literals import random from ..pipeline import TextCategorizer from ..lang.en import English from ..vocab import Vocab from ..tokens import Doc from ..gold import GoldParse def test_textcat_learns_multilabel(): docs = [] nlp = English() vocab = nlp.vocab letters = ['a', 'b', 'c'] for w1 in letters: for w2 in letters: cats = {letter: float(w2==letter) for letter in letters} docs.append((Doc(vocab, words=['d']*3 + [w1, w2] + ['d']*3), cats)) random.shuffle(docs) model = TextCategorizer(vocab, width=8) for letter in letters: model.add_label(letter) optimizer = model.begin_training() for i in range(20): losses = {} Ys = [GoldParse(doc, cats=cats) for doc, cats in docs] Xs = [doc for doc, cats in docs] model.update(Xs, Ys, sgd=optimizer, losses=losses) random.shuffle(docs) for w1 in letters: for w2 in letters: doc = Doc(vocab, words=['d']*3 + [w1, w2] + ['d']*3) truth = {letter: w2==letter for letter in letters} model(doc) for cat, score in doc.cats.items(): if not truth[cat]: assert score < 0.5 else: assert score > 0.5
import random from ..pipeline import TextCategorizer from ..lang.en import English from ..vocab import Vocab from ..tokens import Doc from ..gold import GoldParse def test_textcat_learns_multilabel(): docs = [] nlp = English() vocab = nlp.vocab letters = ['a', 'b', 'c'] for w1 in letters: for w2 in letters: cats = {letter: float(w2==letter) for letter in letters} docs.append((Doc(vocab, words=['d']*3 + [w1, w2] + ['d']*3), cats)) random.shuffle(docs) model = TextCategorizer(vocab, width=8) for letter in letters: model.add_label(letter) optimizer = model.begin_training() for i in range(20): losses = {} Ys = [GoldParse(doc, cats=cats) for doc, cats in docs] Xs = [doc for doc, cats in docs] model.update(Xs, Ys, sgd=optimizer, losses=losses) random.shuffle(docs) for w1 in letters: for w2 in letters: doc = Doc(vocab, words=['d']*3 + [w1, w2] + ['d']*3) truth = {letter: w2==letter for letter in letters} model(doc) for cat, score in doc.cats.items(): print(doc, cat, score) if not truth[cat]: assert score < 0.5 else: assert score > 0.5
Fix error where DateTime is sometimes null
<?php namespace Concrete\Core\Summary\Data\Field; use Symfony\Component\Serializer\Normalizer\DenormalizerInterface; use DateTime; use DateTimeZone; class DatetimeDataFieldData implements DataFieldDataInterface { /** * @var DateTime | null */ protected $dateTime; public function __construct(DateTime $dateTime = null) { if ($dateTime) { $this->dateTime = $dateTime; } } public function __toString() { return ($this->dateTime !== null) ? (string) $this->dateTime->getTimestamp() : ''; } /** * @return DateTime|null */ public function getDateTime() { return $this->dateTime; } #[\ReturnTypeWillChange] public function jsonSerialize() { if ($this->dateTime !== null) { return [ 'class' => self::class, 'timestamp' => (string) $this->dateTime->getTimestamp(), 'timezone' => (string) $this->dateTime->getTimezone()->getName() ]; } return [ 'class' => self::class, 'timestamp' => '', 'timezone' => '' ]; } public function denormalize(DenormalizerInterface $denormalizer, $data, $format = null, array $context = []) { if (isset($data['timestamp'])) { $dateTime = new DateTime(); $dateTime->setTimestamp($data['timestamp']); $dateTime->setTimezone(new DateTimeZone($data['timezone'])); $this->dateTime = $dateTime; } } public function __call($name, $arguments) { return $this->dateTime->$name(...$arguments); } }
<?php namespace Concrete\Core\Summary\Data\Field; use Symfony\Component\Serializer\Normalizer\DenormalizerInterface; use DateTime; use DateTimeZone; class DatetimeDataFieldData implements DataFieldDataInterface { /** * @var DateTime */ protected $dateTime; public function __construct(DateTime $dateTime = null) { if ($dateTime) { $this->dateTime = $dateTime; } } public function __toString() { return (string) $this->dateTime->getTimestamp(); } /** * @return DateTime */ public function getDateTime() { return $this->dateTime; } #[\ReturnTypeWillChange] public function jsonSerialize() { return [ 'class' => self::class, 'timestamp' => (string) $this->dateTime->getTimestamp(), 'timezone' => (string) $this->dateTime->getTimezone()->getName() ]; } public function denormalize(DenormalizerInterface $denormalizer, $data, $format = null, array $context = []) { if (isset($data['timestamp'])) { $dateTime = new DateTime(); $dateTime->setTimestamp($data['timestamp']); $dateTime->setTimezone(new DateTimeZone($data['timezone'])); $this->dateTime = $dateTime; } } public function __call($name, $arguments) { return $this->dateTime->$name(...$arguments); } }
Move override logic into update rather than touch
from framework.auth.core import _get_current_user from website.files.models.base import File, Folder, FileNode, FileVersion __all__ = ('DataverseFile', 'DataverseFolder', 'DataverseFileNode') class DataverseFileNode(FileNode): provider = 'dataverse' class DataverseFolder(DataverseFileNode, Folder): pass class DataverseFile(DataverseFileNode, File): version_identifier = 'version' def update(self, revision, data): """Note: Dataverse only has psuedo versions, don't save them""" self.name = data['name'] self.materialized_path = data['materialized'] version = FileVersion(identifier=revision) version.update_metadata(data, save=False) user = _get_current_user() if not user or not self.node.can_edit(user=user): try: # Users without edit permission can only see published files if not data['extra']['hasPublishedVersion']: # Blank out name and path for the render # Dont save because there's no reason to persist the change self.name = '' self.materialized_path = '' return (version, '<div class="alert alert-info" role="alert">This file does not exist.</div>') except (KeyError, IndexError): pass return version
import requests from framework.auth.core import _get_current_user from website.files.models.base import File, Folder, FileNode, FileVersion __all__ = ('DataverseFile', 'DataverseFolder', 'DataverseFileNode') class DataverseFileNode(FileNode): provider = 'dataverse' class DataverseFolder(DataverseFileNode, Folder): pass class DataverseFile(DataverseFileNode, File): def touch(self, version=None, revision=None, **kwargs): """Note: Dataverse only has psuedo versions, don't save them""" version = revision or version # Use revision or version resp = requests.get(self.generate_waterbutler_url(meta=True, version=version, **kwargs)) if resp.status_code != 200: return None data = resp.json() self.name = data['data']['name'] self.materialized_path = data['data']['materialized'] version = FileVersion(identifier=version) version.update_metadata(data['data'], save=False) user = _get_current_user() if not user or not self.node.can_edit(user=user): try: # Users without edit permission can only see published files if not data['data']['extra']['hasPublishedVersion']: # Blank out name and path for the render # Dont save because there's no reason to persist the change self.name = '' self.materialized_path = '' return (version, '<div class="alert alert-info" role="alert">This file does not exist.</div>') except (KeyError, IndexError): pass
Solve navigation problem when you are in list view and pres the button to come back to view (before it was to home)
/** * @author Jose A. Dianes <[email protected]> * * The prc-cluster-list-filters directive allows us to reuse a spectra visualisations using SpeckTackle. * */ var clusterListFiltersDirective = angular.module('prideClusterApp.clusterListFiltersDirective', []) clusterListFiltersDirective.directive('prcClusterListFilters', function() { return { restrict: 'E', scope: { }, controller: "ClusterListFiltersCtrl", templateUrl: 'components/directives/clusterListFilters-directive/clusterListFilters-directive.html' }; }); clusterListFiltersDirective.controller('ClusterListFiltersCtrl', ['$scope', '$routeParams', '$location', function($scope, $routeParams, $location) { function updateState(view) { // Set location (URL) $location.path(view); $location.search({ q:$routeParams.q, page:$routeParams.page, size:$routeParams.size }); } // attach filter-submit function $scope.listSubmit = function() { updateState("list"); } $scope.chartSubmit = function() { updateState("chart"); } } ]);
/** * @author Jose A. Dianes <[email protected]> * * The prc-cluster-list-filters directive allows us to reuse a spectra visualisations using SpeckTackle. * */ var clusterListFiltersDirective = angular.module('prideClusterApp.clusterListFiltersDirective', []) clusterListFiltersDirective.directive('prcClusterListFilters', function() { return { restrict: 'E', scope: { }, controller: "ClusterListFiltersCtrl", templateUrl: 'components/directives/clusterListFilters-directive/clusterListFilters-directive.html' }; }); clusterListFiltersDirective.controller('ClusterListFiltersCtrl', ['$scope', '$routeParams', '$location', function($scope, $routeParams, $location) { function updateState(view) { // Set location (URL) $location.path(view); $location.search({ q:$routeParams.q, page:$routeParams.page, size:$routeParams.size }); } // attach filter-submit function $scope.listSubmit = function() { updateState("/list"); } $scope.chartSubmit = function() { updateState("/chart"); } } ]);
Set entity loader to autoload Http namespace
<?php namespace Luminary\Services\ApiLoader\Loaders; use Luminary\Services\ApiLoader\Registry\Registrar; class EntityLoader extends AbstractApiLoader { /** * Return the relative path to the directory * for auto loading * * @return string */ public static function path() :string { return 'Entities'; } /** * Initialize a service path by name * to include * * @param \Luminary\Services\ApiLoader\Registry\Registrar $registrar */ protected function register(Registrar $registrar) { $registrar->registerModelFactories('Database/Factories'); $registrar->registerMigrations('Database/Migrations'); $registrar->registerMiddleware('Middleware'); $registrar->registerPolicies('Policies/PolicyRegistrar.php'); $registrar->registerSeeders('Database/Seeds'); $registrar->registerEvents('Events/EventRegistrar.php'); $registrar->registerMorphMap('Models'); // Http $registrar->registerRoutes('Http/routes.php'); $registrar->registerCustomRoutes('Http/custom-routes.php'); $registrar->registerRouteMiddleware('Http/Middleware/registry.php'); $registrar->registerAuthorizer('Http/Requests/Auth.php'); $registrar->registerSanitizer('Http/Requests/Sanitizer.php'); $registrar->registerValidators('Http/Requests/Validators'); } }
<?php namespace Luminary\Services\ApiLoader\Loaders; use Luminary\Services\ApiLoader\Registry\Registrar; class EntityLoader extends AbstractApiLoader { /** * Return the relative path to the directory * for auto loading * * @return string */ public static function path() :string { return 'Entities'; } /** * Initialize a service path by name * to include * * @param \Luminary\Services\ApiLoader\Registry\Registrar $registrar */ protected function register(Registrar $registrar) { $registrar->registerModelFactories('Database/Factories'); $registrar->registerMigrations('Database/Migrations'); $registrar->registerMiddleware('Middleware'); $registrar->registerPolicies('Policies/PolicyRegistrar.php'); $registrar->registerSeeders('Database/Seeds'); $registrar->registerEvents('Events/EventRegistrar.php'); $registrar->registerMorphMap('Models'); // Http if(config('luminary.dynamic_routing') !== false) { $registrar->registerRoutes('Http/routes.php'); $registrar->registerCustomRoutes('Http/custom-routes.php'); $registrar->registerRouteMiddleware('Http/Middleware/registry.php'); $registrar->registerAuthorizer('Http/Requests/Auth.php'); $registrar->registerSanitizer('Http/Requests/Sanitizer.php'); $registrar->registerValidators('Http/Requests/Validators'); } } }
Fix exception handling in HTTPNotifier
import logging import requests from .base import Notifier log = logging.getLogger(__name__) class HTTPNotifier(Notifier): ''' A Notifier that sends http post request to a given url ''' def __init__(self, auth=None, json=True, **kwargs): ''' Create a new HTTPNotifier :param auth: If given, auth is handed over to request.post :param recipients: The urls to post to. :param json: If True, send message as json payload, else use an url query string :type json: bool :type recipients: Iterable of recipients or dict mapping categories to recipients :param categories: The message categories this Notifier should relay :type categories: Iterable :param level: The minimum level for messages to be relayed :type level: int ''' self.auth = auth self.json = json super().__init__(**kwargs) def notify(self, recipient, msg): try: params = msg.to_dict() params.pop('image', None) if self.json is True: params['timestamp'] = str(params['timestamp']) params['uuid'] = str(params['uuid']) ret = requests.post(recipient, json=params, auth=self.auth) else: ret = requests.post(recipient, params=params, auth=self.auth) ret.raise_for_status() except ConnectionError: # traceback of requests connection errors are really long for # such a simple thing log.error('No connection to {}'.format(recipient)) except: log.exception('Could not post message')
import logging import requests from .base import Notifier log = logging.getLogger(__name__) class HTTPNotifier(Notifier): ''' A Notifier that sends http post request to a given url ''' def __init__(self, auth=None, json=True, **kwargs): ''' Create a new HTTPNotifier :param auth: If given, auth is handed over to request.post :param recipients: The urls to post to. :param json: If True, send message as json payload, else use an url query string :type json: bool :type recipients: Iterable of recipients or dict mapping categories to recipients :param categories: The message categories this Notifier should relay :type categories: Iterable :param level: The minimum level for messages to be relayed :type level: int ''' self.auth = auth self.json = json super().__init__(**kwargs) def notify(self, recipient, msg): try: params = msg.to_dict() params.pop('image', None) if self.json is True: params['timestamp'] = str(params['timestamp']) params['uuid'] = str(params['uuid']) ret = requests.post(recipient, json=params, auth=self.auth) else: ret = requests.post(recipient, params=params, auth=self.auth) ret.raise_for_status() except ConnectionError: except: log.exception('Could not post message')
Add API key to context
from __future__ import absolute_import from django.contrib.auth.models import AnonymousUser from django.utils.crypto import constant_time_compare from rest_framework.authentication import BasicAuthentication from rest_framework.exceptions import AuthenticationFailed from sentry.app import raven from sentry.models import ApiKey, ProjectKey class QuietBasicAuthentication(BasicAuthentication): def authenticate_header(self, request): return 'xBasic realm="%s"' % self.www_authenticate_realm class ApiKeyAuthentication(QuietBasicAuthentication): def authenticate_credentials(self, userid, password): if password: return try: key = ApiKey.objects.get_from_cache(key=userid) except ApiKey.DoesNotExist: return None if not key.is_active: raise AuthenticationFailed('Key is disabled') raven.tags_context({ 'api_key': userid, }) return (AnonymousUser(), key) class ProjectKeyAuthentication(QuietBasicAuthentication): def authenticate_credentials(self, userid, password): try: pk = ProjectKey.objects.get_from_cache(public_key=userid) except ProjectKey.DoesNotExist: return None if not constant_time_compare(pk.secret_key, password): return None if not pk.is_active: raise AuthenticationFailed('Key is disabled') if not pk.roles.api: raise AuthenticationFailed('Key does not allow API access') return (AnonymousUser(), pk)
from __future__ import absolute_import from django.contrib.auth.models import AnonymousUser from django.utils.crypto import constant_time_compare from rest_framework.authentication import BasicAuthentication from rest_framework.exceptions import AuthenticationFailed from sentry.models import ApiKey, ProjectKey class QuietBasicAuthentication(BasicAuthentication): def authenticate_header(self, request): return 'xBasic realm="%s"' % self.www_authenticate_realm class ApiKeyAuthentication(QuietBasicAuthentication): def authenticate_credentials(self, userid, password): if password: return try: key = ApiKey.objects.get_from_cache(key=userid) except ApiKey.DoesNotExist: return None if not key.is_active: raise AuthenticationFailed('Key is disabled') return (AnonymousUser(), key) class ProjectKeyAuthentication(QuietBasicAuthentication): def authenticate_credentials(self, userid, password): try: pk = ProjectKey.objects.get_from_cache(public_key=userid) except ProjectKey.DoesNotExist: return None if not constant_time_compare(pk.secret_key, password): return None if not pk.is_active: raise AuthenticationFailed('Key is disabled') if not pk.roles.api: raise AuthenticationFailed('Key does not allow API access') return (AnonymousUser(), pk)
Change injection method to append
(function() { const IS_LOCAL = !!(localStorage["ultratypedev"]), URL_REMOTE = "https://rawgit.com/ultratype/UltraTypeBot/master/OUT/OUT.js", URL_OUT = IS_LOCAL ? chrome.extension.getURL('OUT/OUT.js') : URL_REMOTE, injectFull = () => { window.stop(); let x = new XMLHttpRequest(); x.open('GET', window.location.href, true); x.onload = function() { const doc = `<script src="${URL_OUT}"></script>\n${this.responseText}`; document.open(); document.write(doc); document.close(); } x.send(null); }, injectAppend = () => { let scr = document.createElement('script'); scr.src = URL_OUT; if (document.head) { document.head.appendChild(scr); } else { // Retry after about 100 ms setTimeout(injectAppend, 100); } }; /* if (window.location.href.includes('nitrotype.com/race')) { // Use full injection method on the main page injectFull(); return; } else { // Slower append injection method is used injectAppend(); } */ injectAppend(); })();
(function() { const IS_LOCAL = !!(localStorage["ultratypedev"]), URL_REMOTE = "https://rawgit.com/ultratype/UltraTypeBot/master/OUT/OUT.js", URL_OUT = IS_LOCAL ? chrome.extension.getURL('OUT/OUT.js') : URL_REMOTE, injectFull = () => { window.stop(); let x = new XMLHttpRequest(); x.open('GET', window.location.href, true); x.onload = function() { const doc = `<script src="${URL_OUT}"></script>\n${this.responseText}`; document.open(); document.write(doc); document.close(); } x.send(null); }, injectAppend = () => { let scr = document.createElement('script'); scr.src = URL_OUT; if (document.head) { document.head.appendChild(scr); } else { // Retry after about 100 ms setTimeout(injectAppend, 100); } }; if (window.location.href.includes('nitrotype.com/race')) { // Use full injection method on the main page injectFull(); return; } else { // Slower append injection method is used injectAppend(); } })();
Remove devtool in production build - Reduces bundle size by 90%
const path = require('path'); const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer'); const config = { entry: path.resolve(__dirname, './src/index.js'), output: { path: path.resolve(__dirname, './dist'), filename: 'app.bundle.js', }, module: { rules: [ { test: /\.jsx?$/, exclude: [/node_modules/], use: ['babel-loader', 'eslint-loader'], }, { test: /\.less$/, use: [ 'style-loader', 'css-loader', 'postcss-loader', 'less-loader', ], }, { test: /\.svg$/, loader: 'raw-loader', }, ], }, watchOptions: { ignored: /node_modules/, }, plugins: [], }; const PROD_ENV = process.argv.includes('-p'); if (!PROD_ENV) { config.plugins.push(new BundleAnalyzerPlugin()); config.devtool = 'cheap-eval-source-map'; } module.exports = config;
const path = require('path'); const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer'); const CompressionPlugin = require('compression-webpack-plugin'); const config = { entry: path.resolve(__dirname, './src/index.js'), output: { path: path.resolve(__dirname, './dist'), filename: 'app.bundle.js', }, module: { rules: [ { test: /\.jsx?$/, exclude: [/node_modules/], use: ['babel-loader', 'eslint-loader'], }, { test: /\.less$/, use: [ 'style-loader', 'css-loader', 'postcss-loader', 'less-loader', ], }, { test: /\.svg$/, loader: 'raw-loader', }, ], }, devtool: 'cheap-eval-source-map', watchOptions: { ignored: /node_modules/, }, plugins: [], }; const PROD_ENV = process.argv.includes('-p'); if (PROD_ENV) { config.plugins.push(new CompressionPlugin({ asset: '[path].gz[query]', algorithm: 'gzip', test: /\.(js|html)$/, threshold: 10240, minRatio: 0.8 })); } else { config.plugins.push(new BundleAnalyzerPlugin()); } module.exports = config;
BAP-16838: Fix form types issues for commerce application - revert autocomplete_aliases changes
<?php namespace Oro\Bundle\LocaleBundle\Form\Type; use Oro\Bundle\FormBundle\Form\Type\OroEntitySelectOrCreateInlineType; use Symfony\Component\Form\AbstractType; use Symfony\Component\OptionsResolver\OptionsResolver; class LocalizationSelectType extends AbstractType { const NAME = 'oro_locale_localization_select'; /** * {@inheritdoc} */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults( [ 'autocomplete_alias' => 'oro_localization', 'create_form_route' => 'oro_locale_localization_create', 'configs' => [ 'placeholder' => 'oro.locale.localization.form.placeholder.choose', ] ] ); } /** * {@inheritdoc} */ public function getName() { return $this->getBlockPrefix(); } /** * {@inheritdoc} */ public function getBlockPrefix() { return self::NAME; } /** * {@inheritdoc} */ public function getParent() { return OroEntitySelectOrCreateInlineType::class; } }
<?php namespace Oro\Bundle\LocaleBundle\Form\Type; use Oro\Bundle\FormBundle\Form\Type\OroEntitySelectOrCreateInlineType; use Symfony\Component\Form\AbstractType; use Symfony\Component\OptionsResolver\OptionsResolver; class LocalizationSelectType extends AbstractType { const NAME = 'oro_locale_localization_select'; /** * {@inheritdoc} */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults( [ 'autocomplete_alias' => LocalizationType::class, 'create_form_route' => 'oro_locale_localization_create', 'configs' => [ 'placeholder' => 'oro.locale.localization.form.placeholder.choose', ] ] ); } /** * {@inheritdoc} */ public function getName() { return $this->getBlockPrefix(); } /** * {@inheritdoc} */ public function getBlockPrefix() { return self::NAME; } /** * {@inheritdoc} */ public function getParent() { return OroEntitySelectOrCreateInlineType::class; } }
Rename variable for better clarity
'use strict'; angular .module('lmServices') .service('Window', function($window) { this.on = function(opts) { // Cache the available width and height to avoiding an issue in Chrome (and maybe other // browsers) where the window resize event is fired twice every time. var obj = { width: opts.width(), height: opts.height(), off: function() { angular.element($window).off('resize', onWindowResize); } }; function onWindowResize() { var nw = opts.width(); var nh = opts.height(); if (nw === obj.width && nh === obj.height) { return; } obj.width = nw; obj.height = nh; if (opts.resize) { opts.resize(); } } angular.element($window).on('resize', onWindowResize); return obj; }; });
'use strict'; angular .module('lmServices') .service('Window', function($window) { this.on = function(opts) { // Cache the available width and height to avoiding an issue in Chrome (and maybe other // browsers) where the window resize event is fired twice every time. var x = { width: opts.width(), height: opts.height(), off: function() { angular.element($window).off('resize', onWindowResize); } }; function onWindowResize() { var nw = opts.width(); var nh = opts.height(); if (nw === x.width && nh === x.height) { return; } x.width = nw; x.height = nh; if (opts.resize) { opts.resize(); } } angular.element($window).on('resize', onWindowResize); return x; }; });
Remove disconnect binding from client I'm not even sure this would do anything
var socket = io('/push-it'); var fingerprint2str; var vid = document.getElementById('bigvid'); var bg = document.getElementsByClassName('push-it')[0]; var clients = []; fingerprint2str = localStorage.getItem('fingerprint2'); var uri = document.createElement('a'); uri.href = document.URL; if (bg !== null) { bg.addEventListener('click', function () { resetVid(); }, false); } function resetVid() { vid.pause(); vid.currentTime = 0; vid.muted = false; vid.style.visibility = "inherit"; } socket.on('connect', function () { console.log('Firing. Room: %s', uri.pathname); if (!localStorage.getItem('fingerprint2')) { console.log('No Fingerprint found. Setting...'); new Fingerprint2().get(function (result) { fingerprint2str = result; localStorage.setItem('fingerprint2', result); socket.emit('client connected', { 'fp2str': fingerprint2str, 'room': uri.pathname }); }); } else { socket.emit('client connected', { 'fp2str': fingerprint2str, 'room': uri.pathname }); } }); socket.on('push it', function (data) { console.log('Pushed.'); resetVid(); vid.play(); }); socket.on('clients update', function (data) { console.log('Clients:'); console.log(data); });
var socket = io('/push-it'); var fingerprint2str; var vid = document.getElementById('bigvid'); var bg = document.getElementsByClassName('push-it')[0]; var clients = []; fingerprint2str = localStorage.getItem('fingerprint2'); var uri = document.createElement('a'); uri.href = document.URL; if (bg !== null) { bg.addEventListener('click', function () { resetVid(); }, false); } function resetVid() { vid.pause(); vid.currentTime = 0; vid.muted = false; vid.style.visibility = "inherit"; } socket.on('connect', function () { console.log('Firing. Room: %s', uri.pathname); if (!localStorage.getItem('fingerprint2')) { console.log('No Fingerprint found. Setting...'); new Fingerprint2().get(function (result) { fingerprint2str = result; localStorage.setItem('fingerprint2', result); socket.emit('client connected', { 'fp2str': fingerprint2str, 'room': uri.pathname }); }); } else { socket.emit('client connected', { 'fp2str': fingerprint2str, 'room': uri.pathname }); } }); socket.on('disconnect', function () { }); socket.on('push it', function (data) { console.log('Pushed.'); resetVid(); vid.play(); }); socket.on('clients update', function (data) { console.log('Clients:'); console.log(data); });
Update BrowserifyCompiler for n Pipeline settings.
import re from django.conf import settings from django.utils.encoding import smart_bytes from pipeline.compilers import CompilerBase from pipeline.exceptions import CompilerError class BrowserifyCompiler(CompilerBase): output_extension = 'browserified.js' def match_file(self, path): # Allow for cache busting hashes between ".browserify" and ".js" return re.search(r'\.browserify(\.[a-fA-F0-9]+)?\.js$', path) is not None def compile_file(self, infile, outfile, outdated=False, force=False): pipeline_settings = getattr(settings, 'PIPELINE', {}) command = "%s %s %s > %s" % ( pipeline_settings.get('BROWSERIFY_BINARY', '/usr/bin/env browserify'), pipeline_settings.get('BROWSERIFY_ARGUMENTS', ''), infile, outfile ) return self.execute_command(command) def execute_command(self, command, content=None, cwd=None): """This is like the one in SubProcessCompiler, except it checks the exit code.""" import subprocess pipe = subprocess.Popen(command, shell=True, cwd=cwd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) if content: content = smart_bytes(content) stdout, stderr = pipe.communicate(content) if self.verbose: print(stderr) if pipe.returncode != 0: raise CompilerError(stderr) return stdout
import re from django.conf import settings from django.utils.encoding import smart_bytes from pipeline.compilers import CompilerBase from pipeline.exceptions import CompilerError class BrowserifyCompiler(CompilerBase): output_extension = 'browserified.js' def match_file(self, path): # Allow for cache busting hashes between ".browserify" and ".js" return re.search(r'\.browserify(\.[a-fA-F0-9]+)?\.js$', path) is not None def compile_file(self, infile, outfile, outdated=False, force=False): command = "%s %s %s > %s" % ( getattr(settings, 'PIPELINE_BROWSERIFY_BINARY', '/usr/bin/env browserify'), getattr(settings, 'PIPELINE_BROWSERIFY_ARGUMENTS', ''), infile, outfile ) return self.execute_command(command) def execute_command(self, command, content=None, cwd=None): """This is like the one in SubProcessCompiler, except it checks the exit code.""" import subprocess pipe = subprocess.Popen(command, shell=True, cwd=cwd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) if content: content = smart_bytes(content) stdout, stderr = pipe.communicate(content) if self.verbose: print(stderr) if pipe.returncode != 0: raise CompilerError(stderr) return stdout
Add search by request_id field.
from django.db.models import Q from ..models import LogRecord def _filter_records(request): getvars = request.GET logrecord_qs = LogRecord.objects.all().select_related('app') # Filtering by get params. if getvars.get('q'): q = getvars.get('q') logrecord_qs = logrecord_qs.filter( Q(app__name__icontains=q) | Q(message__icontains=q) | Q(fileName__icontains=q) | Q(loggerName__icontains=q) | Q(exception_message__icontains=q) | Q(request_id__icontains=q) | Q(_extra__icontains=q) ) if getvars.get('app'): logrecord_qs = logrecord_qs.filter(app_id=getvars.get('app')) if getvars.get('logger'): logrecord_qs = logrecord_qs.filter(loggerName=getvars.get('logger')) if getvars.getlist('level'): logrecord_qs = logrecord_qs.filter(level__in=getvars.getlist('level')) if getvars.get('from'): logrecord_qs = logrecord_qs.filter(timestamp__gte=getvars.get('from')) if getvars.get('to'): logrecord_qs = logrecord_qs.filter(timestamp__lte=getvars.get('to')) return logrecord_qs
from django.db.models import Q from ..models import LogRecord def _filter_records(request): getvars = request.GET logrecord_qs = LogRecord.objects.all().select_related('app') # Filtering by get params. if getvars.get('q'): q = getvars.get('q') logrecord_qs = logrecord_qs.filter( Q(app__name__icontains=q) | Q(message__icontains=q) | Q(fileName__icontains=q) | Q(loggerName__icontains=q) | Q(exception_message__icontains=q) | Q(_extra__icontains=q) ) if getvars.get('app'): logrecord_qs = logrecord_qs.filter(app_id=getvars.get('app')) if getvars.get('logger'): logrecord_qs = logrecord_qs.filter(loggerName=getvars.get('logger')) if getvars.getlist('level'): logrecord_qs = logrecord_qs.filter(level__in=getvars.getlist('level')) if getvars.get('from'): logrecord_qs = logrecord_qs.filter(timestamp__gte=getvars.get('from')) if getvars.get('to'): logrecord_qs = logrecord_qs.filter(timestamp__lte=getvars.get('to')) return logrecord_qs
Add readline support for the REPL
from . import * import readline ps1 = '\n% ' ps2 = '| ' try: from blessings import Terminal term = Terminal() ps1 = term.bold_blue(ps1) ps2 = term.bold_blue(ps2) def fancy_movement(): print(term.move_up() + term.clear_eol() + term.move_up()) except ImportError: def fancy_movement(): pass def getfilefunc(mod, droplast=True): return Func(fixtags(flattenbody(mod, droplast=droplast))) def runfile(fname): invoke(getfilefunc(parseFile(fname)), stdlib()) def readProgram(): try: yield input(ps1) while True: line = input(ps2) if not line: fancy_movement() return yield line except EOFError: print() raise SystemExit def interactive(): env = stdlib() while True: try: retval, = invoke(getfilefunc(parseString('\n'.join(readProgram())), droplast=False), env) if retval is not None: print(arepr(retval)) except KeyboardInterrupt: print() except Exception as e: print(e) import sys if len(sys.argv) > 1: runfile(sys.argv[1]) else: interactive()
from . import * ps1 = '\n% ' ps2 = '| ' try: from blessings import Terminal term = Terminal() ps1 = term.bold_blue(ps1) ps2 = term.bold_blue(ps2) def fancy_movement(): print(term.move_up() + term.clear_eol() + term.move_up()) except ImportError: def fancy_movement(): pass def getfilefunc(mod, droplast=True): return Func(fixtags(flattenbody(mod, droplast=droplast))) def runfile(fname): invoke(getfilefunc(parseFile(fname)), stdlib()) def readProgram(): try: yield input(ps1) while True: line = input(ps2) if not line: fancy_movement() return yield line except EOFError: print() raise SystemExit def interactive(): env = stdlib() while True: try: retval, = invoke(getfilefunc(parseString('\n'.join(readProgram())), droplast=False), env) if retval is not None: print(arepr(retval)) except KeyboardInterrupt: print() except Exception as e: print(e) import sys if len(sys.argv) > 1: runfile(sys.argv[1]) else: interactive()
Remove interactivity from cc histogram
export default class ChannelHistogramController { constructor() { 'ngInject'; } $onInit() { this.histOptions = { chart: { type: 'lineChart', showLegend: false, showXAxis: false, showYAxis: false, interactive: false, margin: { top: 0, right: 0, bottom: 0, left: 0 }, xAxis: { showLabel: false }, yAxis: { showLabel: false } } }; if (this.data) { this.histData = Array.from(this.data); } } $onChanges(changesObj) { if ('data' in changesObj && changesObj.data.currentValue) { this.histData = Array.from(changesObj.data.currentValue); } } }
export default class ChannelHistogramController { constructor() { 'ngInject'; } $onInit() { this.histOptions = { chart: { type: 'lineChart', showLegend: false, showXAxis: false, showYAxis: false, margin: { top: 0, right: 0, bottom: 0, left: 0 }, xAxis: { showLabel: false }, yAxis: { showLabel: false } } }; if (this.data) { this.histData = Array.from(this.data); } } $onChanges(changesObj) { if ('data' in changesObj && changesObj.data.currentValue) { this.histData = Array.from(changesObj.data.currentValue); } } }
Tag eve version more precisly
#!/usr/bin/env python try: from setuptools import setup except ImportError: from distutils.core import setup with open('README.rst', 'r') as f: readme = f.read() setup( name='eve-auth-jwt', version='1.0.1', description='Eve JWT authentication', long_description=readme, author='Olivier Poitrey', author_email='[email protected]', url='https://github.com/rs/eve-auth-jwt', keywords=["eve", "api", "rest", "oauth", "auth", "jwt"], packages=['eve_auth_jwt'], package_dir={'eve_auth_jwt': 'eve_auth_jwt'}, install_requires=["Eve => 0.5.0", "PyJWT == 1.0.1"], test_suite='test', tests_require=['flake8', 'nose'], license="MIT", classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Environment :: No Input/Output (Daemon)', 'Intended Audience :: Developers', 'Intended Audience :: Telecommunications Industry', 'License :: OSI Approved :: MIT License', 'Operating System :: Unix', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: HTTP Servers', 'Topic :: Security', ] )
#!/usr/bin/env python try: from setuptools import setup except ImportError: from distutils.core import setup with open('README.rst', 'r') as f: readme = f.read() setup( name='eve-auth-jwt', version='1.0.1', description='Eve JWT authentication', long_description=readme, author='Olivier Poitrey', author_email='[email protected]', url='https://github.com/rs/eve-auth-jwt', keywords=["eve", "api", "rest", "oauth", "auth", "jwt"], packages=['eve_auth_jwt'], package_dir={'eve_auth_jwt': 'eve_auth_jwt'}, install_requires=["Eve", "PyJWT == 1.0.1"], test_suite='test', tests_require=['flake8', 'nose'], license="MIT", classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Environment :: No Input/Output (Daemon)', 'Intended Audience :: Developers', 'Intended Audience :: Telecommunications Industry', 'License :: OSI Approved :: MIT License', 'Operating System :: Unix', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: HTTP Servers', 'Topic :: Security', ] )
Change all composers to use an array on views
<?php namespace REBELinBLUE\Deployer\Providers; use Illuminate\Contracts\View\Factory; use Illuminate\Support\ServiceProvider; use REBELinBLUE\Deployer\Composers\ActiveUserComposer; use REBELinBLUE\Deployer\Composers\HeaderComposer; use REBELinBLUE\Deployer\Composers\NavigationComposer; use REBELinBLUE\Deployer\Composers\ThemeComposer; use REBELinBLUE\Deployer\Composers\VersionComposer; /** * The view service provider. */ class ViewServiceProvider extends ServiceProvider { public $composers = [ ActiveUserComposer::class => ['_partials.nav', 'dialogs.command', 'user.profile'], HeaderComposer::class => ['_partials.nav'], NavigationComposer::class => ['_partials.sidebar'], ThemeComposer::class => ['layout', 'user.profile'], VersionComposer::class => ['_partials.update'], ]; /** * Bootstrap the application services. * * @param \Illuminate\Contracts\View\Factory $factory * @return void */ public function boot(Factory $factory) { foreach ($this->composers as $composer => $views) { $factory->composer($views, $composer); } } /** * Register the application services. * * @return void */ public function register() { // } }
<?php namespace REBELinBLUE\Deployer\Providers; use Illuminate\Contracts\View\Factory; use Illuminate\Support\ServiceProvider; use REBELinBLUE\Deployer\Composers\ActiveUserComposer; use REBELinBLUE\Deployer\Composers\HeaderComposer; use REBELinBLUE\Deployer\Composers\NavigationComposer; use REBELinBLUE\Deployer\Composers\ThemeComposer; use REBELinBLUE\Deployer\Composers\VersionComposer; /** * The view service provider. */ class ViewServiceProvider extends ServiceProvider { public $composers = [ ActiveUserComposer::class => ['_partials.nav', 'dialogs.command', 'user.profile'], HeaderComposer::class => '_partials.nav', NavigationComposer::class => '_partials.sidebar', ThemeComposer::class => ['layout', 'user.profile'], VersionComposer::class => '_partials.update', ]; /** * Bootstrap the application services. * * @param \Illuminate\Contracts\View\Factory $factory * @return void */ public function boot(Factory $factory) { foreach ($this->composers as $composer => $views) { $factory->composer($views, $composer); } } /** * Register the application services. * * @return void */ public function register() { // } }
Test something besides the || operator in JS.
var assert = require('assert'); require('./support/start')(function(command) { exports['test abilities endpoint'] = function() { assert.response(command.servers['Core'], { url: '/assets/tilemill/js/abilities.js' }, { status: 200 }, function(res) { var body = res.body.replace(/^\s*var\s+abilities\s*=\s*(.+?);?$/, '$1'); var abilities = JSON.parse(body); assert.ok(abilities.fonts.indexOf('Arial Regular') >= 0 || abilities.fonts.indexOf('DejaVu Sans Book') >= 0); assert.deepEqual([0,206,209], abilities.carto.colors.darkturquoise); assert.deepEqual([ "background-color", "background-image", "srs", "buffer-size", "base", "paths-from-xml", "minimum-version", "font-directory" ], Object.keys(abilities.carto.symbolizers.map)); assert.deepEqual({ mbtiles: true, png: true, pdf: true, svg: true }, abilities.exports); } ); }; });
var assert = require('assert'); require('./support/start')(function(command) { exports['test abilities endpoint'] = function() { assert.response(command.servers['Core'], { url: '/assets/tilemill/js/abilities.js' }, { status: 200 }, function(res) { var body = res.body.replace(/^\s*var\s+abilities\s*=\s*(.+?);?$/, '$1'); var abilities = JSON.parse(body); assert.ok(abilities.fonts.indexOf('Arial Regular') >= 0 || abilities.fonts.indexOf('Arial Regular') >= 0); assert.deepEqual([0,206,209], abilities.carto.colors.darkturquoise); assert.deepEqual([ "background-color", "background-image", "srs", "buffer-size", "base", "paths-from-xml", "minimum-version", "font-directory" ], Object.keys(abilities.carto.symbolizers.map)); assert.deepEqual({ mbtiles: true, png: true, pdf: true, svg: true }, abilities.exports); } ); }; });
Revert "Attempt to fix fading of splash image" This reverts commit c7bf9d431e13746db551cd983420258f92d554a0.
$(document).ready(function() { $("#splash").hide(); $("footer").hide(); if ($("#splash").length > 0) { $("#splash").bind("load", function () { $("#splash").fadeIn(3000); $("footer").delay(1500).fadeIn(3000); }); } else { $("footer").delay(1500).fadeIn(3000); } $("a[class='tooltip-hover']").tooltip(); $("a[class='tooltip-click']").tooltip({ trigger: "click" }); $("a[class^='tooltip-']").attr("href", "javascript:void(0)"); $("a[href$='.jpg'],a[href$='.png']").fancybox({ padding: 10, margin: 50, loop: false, helpers : { title : { type: "over" }, overlay : { showEarly: false, css : { "background" : "rgba(25, 25, 25, 0.80)" } } } }); $(".fancybox-media").fancybox({ padding: 10, margin: 50, loop: false, helpers : { media : {}, title : { type: "float" }, overlay : { showEarly: false, css : { "background" : "rgba(25, 25, 25, 0.80)" } } } }); });
$(document).ready(function() { $("#splash").hide(); $("footer").hide(); if ($("#splash").length > 0) { $("#splash").bind("load", function () { $("#splash").fadeIn(3000); $("footer").delay(1500).fadeIn(3000); }); $("#splash").fadeIn(3000); $("footer").delay(1500).fadeIn(3000); } else { $("footer").delay(1500).fadeIn(3000); } $("a[class='tooltip-hover']").tooltip(); $("a[class='tooltip-click']").tooltip({ trigger: "click" }); $("a[class^='tooltip-']").attr("href", "javascript:void(0)"); $("a[href$='.jpg'],a[href$='.png']").fancybox({ padding: 10, margin: 50, loop: false, helpers : { title : { type: "over" }, overlay : { showEarly: false, css : { "background" : "rgba(25, 25, 25, 0.80)" } } } }); $(".fancybox-media").fancybox({ padding: 10, margin: 50, loop: false, helpers : { media : {}, title : { type: "float" }, overlay : { showEarly: false, css : { "background" : "rgba(25, 25, 25, 0.80)" } } } }); });
Add possibility to perform a full content swap when installing packages through CIF file (useful for starting point packages)
<?php namespace Concrete\Core\Backup\ContentImporter\Importer\Routine; use Concrete\Core\Attribute\Type; use Concrete\Core\Block\BlockType\BlockType; use Concrete\Core\Package\Package; use Concrete\Core\Permission\Category; use Concrete\Core\Support\Facade\Facade; use Concrete\Core\Validation\BannedWord\BannedWord; use Concrete\Core\Package\PackageService; class ImportPackagesRoutine extends AbstractRoutine { public function getHandle() { return 'packages'; } public function import(\SimpleXMLElement $sx) { if (isset($sx->packages)) { foreach ($sx->packages->package as $p) { $pkg = Package::getByHandle((string) $p['handle']); if (!$pkg) { $pkgClass = Package::getClass((string) $p['handle']); if ($pkgClass) { $app = Facade::getFacadeApplication(); $service = $app->make(PackageService::class); $data = []; if (isset($p['full-content-swap'])) { $data["pkgDoFullContentSwap"] = true; } if (isset($p['content-swap-file'])) { $data["contentSwapFile"] = (string)$p['content-swap-file']; } $service->install($pkgClass, $data); } } } } } }
<?php namespace Concrete\Core\Backup\ContentImporter\Importer\Routine; use Concrete\Core\Attribute\Type; use Concrete\Core\Block\BlockType\BlockType; use Concrete\Core\Package\Package; use Concrete\Core\Permission\Category; use Concrete\Core\Support\Facade\Facade; use Concrete\Core\Validation\BannedWord\BannedWord; use Concrete\Core\Package\PackageService; class ImportPackagesRoutine extends AbstractRoutine { public function getHandle() { return 'packages'; } public function import(\SimpleXMLElement $sx) { if (isset($sx->packages)) { foreach ($sx->packages->package as $p) { $pkg = Package::getByHandle((string) $p['handle']); if (!$pkg) { $pkgClass = Package::getClass((string) $p['handle']); if ($pkgClass) { $app = Facade::getFacadeApplication(); $service = $app->make(PackageService::class); $service->install($pkgClass, []); } } } } } }
Return null for last modified if no fixtures are available
<?php namespace Driebit\Prepper\Fixture; class FixtureSet implements \IteratorAggregate { private $fixtures = array(); private $classes = array(); private $lastModified; public function __construct($fixtures) { $this->fixtures = $fixtures; foreach ($fixtures as $fixture) { $this->classes[] = new $fixture; } } public function getHash() { $fixtures = $this->fixtures; // Sort so we same fixtures in different order get the same hash sort($fixtures); // json_encode is faster than serialize: http://stackoverflow.com/a/7723730 return md5(json_encode($fixtures)); } public function getLastModified() { if (null === $this->lastModified && count($this->classes) > 0) { $mtimes = array(); foreach ($this->classes as $class) { if ($class instanceof DatedFixtureInterface) { // @todo } else { // Determine last modified on file mtime $reflClass = new \ReflectionClass($class); $mtimes[] = filemtime($reflClass->getFileName()); } } // Look at the fixture that was modified last sort($mtimes); $this->lastModified = new \DateTime('@' . $mtimes[0]); } return $this->lastModified; } public function getIterator() { return new \ArrayIterator($this->classes); } }
<?php namespace Driebit\Prepper\Fixture; class FixtureSet implements \IteratorAggregate { private $fixtures = array(); private $classes = array(); private $lastModified; public function __construct($fixtures) { $this->fixtures = $fixtures; foreach ($fixtures as $fixture) { $this->classes[] = new $fixture; } } public function getHash() { $fixtures = $this->fixtures; // Sort so we same fixtures in different order get the same hash sort($fixtures); // json_encode is faster than serialize: http://stackoverflow.com/a/7723730 return md5(json_encode($fixtures)); } public function getLastModified() { if (null === $this->lastModified) { $mtimes = array(); foreach ($this->classes as $class) { if ($class instanceof DatedFixtureInterface) { // @todo } else { // Determine last modified on file mtime $reflClass = new \ReflectionClass($class); $mtimes[] = filemtime($reflClass->getFileName()); } } // Look at the fixture that was modified last sort($mtimes); $this->lastModified = new \DateTime('@' . $mtimes[0]); } return $this->lastModified; } public function getIterator() { return new \ArrayIterator($this->classes); } }
Fix : Range of len(1) have to be a tuple of tuples
import msgpack import logging from .constants import FAILURE_STATUS class MessageFormatError(Exception): pass class Request(object): """Handler objects for frontend->backend objects messages""" def __new__(cls, *args, **kwargs): content = { 'DB_UID': kwargs.pop('db_uid'), 'COMMAND': kwargs.pop('command'), 'ARGS': kwargs.pop('args'), } return msgpack.packb(content) class Response(object): def __init__(self, raw_message): self.error = None errors_logger = logging.getLogger("errors_logger") message = msgpack.unpackb(raw_message) try: self.status = message.pop('STATUS') self._datas = message.pop('DATAS') except KeyError: errors_logger.exception("Invalid response message : %s" % message) raise MessageFormatError("Invalid response message") self._handle_failures() @property def datas(self): if hasattr(self, '_datas') and self._datas is not None: if (len(self._datas) == 1) and not isinstance(self._datas[0], (tuple, list)): return self._datas[0] return self._datas def _handle_failures(self): if self.status == FAILURE_STATUS: self.error = { 'code': int(self.datas[0]), 'msg': self.datas[1], }
import msgpack import logging from .constants import FAILURE_STATUS class MessageFormatError(Exception): pass class Request(object): """Handler objects for frontend->backend objects messages""" def __new__(cls, *args, **kwargs): content = { 'DB_UID': kwargs.pop('db_uid'), 'COMMAND': kwargs.pop('command'), 'ARGS': kwargs.pop('args'), } return msgpack.packb(content) class Response(object): def __init__(self, raw_message): self.error = None errors_logger = logging.getLogger("errors_logger") message = msgpack.unpackb(raw_message) try: self.status = message.pop('STATUS') self._datas = message.pop('DATAS') except KeyError: errors_logger.exception("Invalid response message : %s" % message) raise MessageFormatError("Invalid response message") self._handle_failures() @property def datas(self): if hasattr(self, '_datas') and self._datas is not None: if (len(self._datas) == 1): return self._datas[0] return self._datas def _handle_failures(self): if self.status == FAILURE_STATUS: self.error = { 'code': int(self.datas[0]), 'msg': self.datas[1], }
Remove "htmlunit" from browser options
""" This class containts some frequently-used constants """ class Environment: QA = "qa" STAGING = "staging" PRODUCTION = "production" MASTER = "master" LOCAL = "local" TEST = "test" class Files: DOWNLOADS_FOLDER = "downloaded_files" ARCHIVED_DOWNLOADS_FOLDER = "archived_files" class ValidBrowsers: valid_browsers = ["firefox", "ie", "edge", "safari", "chrome", "phantomjs"] class Browser: FIREFOX = "firefox" INTERNET_EXPLORER = "ie" EDGE = "edge" SAFARI = "safari" GOOGLE_CHROME = "chrome" PHANTOM_JS = "phantomjs" VERSION = { "firefox": None, "ie": None, "edge": None, "safari": None, "chrome": None, "phantomjs": None } LATEST = { "firefox": None, "ie": None, "edge": None, "safari": None, "chrome": None, "phantomjs": None } class State: NOTRUN = "NotRun" ERROR = "Error" FAILURE = "Fail" PASS = "Pass" SKIP = "Skip" BLOCKED = "Blocked" DEPRECATED = "Deprecated"
""" This class containts some frequently-used constants """ class Environment: QA = "qa" STAGING = "staging" PRODUCTION = "production" MASTER = "master" LOCAL = "local" TEST = "test" class Files: DOWNLOADS_FOLDER = "downloaded_files" ARCHIVED_DOWNLOADS_FOLDER = "archived_files" class ValidBrowsers: valid_browsers = ["firefox", "ie", "edge", "safari", "chrome", "phantomjs"] class Browser: FIREFOX = "firefox" INTERNET_EXPLORER = "ie" EDGE = "edge" SAFARI = "safari" GOOGLE_CHROME = "chrome" PHANTOM_JS = "phantomjs" HTML_UNIT = "htmlunit" VERSION = { "firefox": None, "ie": None, "edge": None, "safari": None, "chrome": None, "phantomjs": None, "htmlunit": None } LATEST = { "firefox": None, "ie": None, "edge": None, "safari": None, "chrome": None, "phantomjs": None, "htmlunit": None } class State: NOTRUN = "NotRun" ERROR = "Error" FAILURE = "Fail" PASS = "Pass" SKIP = "Skip" BLOCKED = "Blocked" DEPRECATED = "Deprecated"
Handle App::abort() no longer exist. Signed-off-by: crynobone <[email protected]>
<?php namespace Orchestra\Support\Traits; use Illuminate\Support\Facades\App; use Orchestra\Support\Facades\Messages; use Illuminate\Support\Facades\Redirect; use Symfony\Component\HttpKernel\Exception\HttpException use Symfony\Component\HttpKernel\Exception\NotFoundHttpException trait ControllerResponseTrait { /** * Queue notification and redirect. * * @param string $to * @param string $message * @param string $type * @return mixed */ public function redirectWithMessage($to, $message = null, $type = 'success') { ! is_null($message) && Messages::add($type, $message); return $this->redirect($to); } /** * Queue notification and redirect. * * @param string $to * @param mixed $errors * @return mixed */ public function redirectWithErrors($to, $errors) { return $this->redirect($to)->withInput()->withErrors($errors); } /** * Redirect. * * @param string $to * @return mixed */ public function redirect($to) { return Redirect::to($to); } /** * Halt current request using App::abort(). * * @param int $code * @return void * @throws \Symfony\Component\HttpKernel\Exception\HttpException * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException */ public function suspend($code) { if ($status == 404) { throw new NotFoundHttpException(''); } throw new HttpException($code, '', null, []); } }
<?php namespace Orchestra\Support\Traits; use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Redirect; use Orchestra\Support\Facades\Messages; trait ControllerResponseTrait { /** * Queue notification and redirect. * * @param string $to * @param string $message * @param string $type * @return Response */ public function redirectWithMessage($to, $message = null, $type = 'success') { ! is_null($message) && Messages::add($type, $message); return $this->redirect($to); } /** * Queue notification and redirect. * * @param string $to * @param mixed $errors * @return Response */ public function redirectWithErrors($to, $errors) { return $this->redirect($to)->withInput()->withErrors($errors); } /** * Redirect. * * @param string $to * @param string $message * @param string $type * @return Response */ public function redirect($to) { return Redirect::to($to); } /** * Halt current request using App::abort(). * * @param integer $status * @return Response */ public function suspend($status) { return App::abort($status); } }
Make the hide_input extension work with jupyter - Add the needed load_ipython_extension property - Use the require mechanism
// Adds a button to hide the input part of the currently selected cells // Prevent this script from cluttering the IPython namespace define([], function () { "use strict"; var hide_input = function () { // Find the selected cell var cell = IPython.notebook.get_selected_cell(); // Toggle visibility of the input div cell.element.find("div.input").toggle('slow') if ( cell.metadata.input_collapsed ) { cell.metadata.input_collapsed = false; } else { cell.metadata.input_collapsed = true; } }; var init_hide_input = function(){ // Add a button to the toolbar IPython.toolbar.add_buttons_group([{ label:'hide input', icon:'fa-chevron-up', callback:hide_input, }]); // Collapse all cells that are marked as hidden var cells = IPython.notebook.get_cells(); cells.forEach( function(cell){ if( cell.metadata.input_collapsed ){ cell.element.find("div.input").toggle(0); } } ); // Write a message to the console to confirm the extension loaded console.log("hide_input cell extension loaded correctly"); return true; }; var load_ipython_extension = function () { init_hide_input(); }; // Initialize the extension return { load_ipython_extension : load_ipython_extension } });
// Adds a button to hide the input part of the currently selected cells // Prevent this script from cluttering the IPython namespace (function (IPython) { "use strict"; var hide_input = function () { // Find the selected cell var cell = IPython.notebook.get_selected_cell(); // Toggle visibility of the input div cell.element.find("div.input").toggle('slow') if ( cell.metadata.input_collapsed ) { cell.metadata.input_collapsed = false; } else { cell.metadata.input_collapsed = true; } }; var init_hide_input = function(){ // Add a button to the toolbar IPython.toolbar.add_buttons_group([{ label:'hide input', icon:'fa-chevron-up', callback:hide_input, }]); // Collapse all cells that are marked as hidden var cells = IPython.notebook.get_cells(); cells.forEach( function(cell){ if( cell.metadata.input_collapsed ){ cell.element.find("div.input").toggle(0); } } ); // Write a message to the console to confirm the extension loaded console.log("hide_input cell extension loaded correctly"); return true; }; // Initialize the extension init_hide_input(); }(IPython));
Add support for Python 2.6 and 2.7 Remove the following error when using Python 2.6 and 2.7. TypeError: 'encoding' is an invalid keyword argument for this function Python 3 operation is unchanged
from __future__ import print_function import argparse import sys import io from opencc import OpenCC def main(): parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-i', '--input', metavar='<file>', help='Read original text from <file>.') parser.add_argument('-o', '--output', metavar='<file>', help='Write converted text to <file>.') parser.add_argument('-c', '--config', metavar='<conversion>', help='Conversion') parser.add_argument('--in-enc', metavar='<encoding>', default='UTF-8', help='Encoding for input') parser.add_argument('--out-enc', metavar='<encoding>', default='UTF-8', help='Encoding for output') args = parser.parse_args() if args.config is None: print("Please specify a conversion.", file=sys.stderr) return 1 cc = OpenCC(args.config) with io.open(args.input if args.input else 0, encoding=args.in_enc) as f: input_str = f.read() output_str = cc.convert(input_str) with io.open(args.output if args.output else 1, 'w', encoding=args.out_enc) as f: f.write(output_str) return 0 if __name__ == '__main__': sys.exit(main())
from __future__ import print_function import argparse import sys from opencc import OpenCC def main(): parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-i', '--input', metavar='<file>', help='Read original text from <file>.') parser.add_argument('-o', '--output', metavar='<file>', help='Write converted text to <file>.') parser.add_argument('-c', '--config', metavar='<file>', help='Configuration file') parser.add_argument('--in-enc', metavar='<encoding>', default='UTF-8', help='Encoding for input') parser.add_argument('--out-enc', metavar='<encoding>', default='UTF-8', help='Encoding for output') args = parser.parse_args() if args.config is None: print("Please specify a configuration file.", file=sys.stderr) return 1 cc = OpenCC(args.config) with open(args.input if args.input else 0, encoding=args.in_enc) as f: input_str = f.read() output_str = cc.convert(input_str) with open(args.output if args.output else 1, 'w', encoding=args.out_enc) as f: f.write(output_str) return 0 if __name__ == '__main__': sys.exit(main())
Print help when invoked with no arguments This is more useful.
import sys import pathlib import argparse import pkg_resources from jacquard.config import load_config def argument_parser(): parser = argparse.ArgumentParser(description="Split testing server") parser.add_argument( '-v', '--verbose', help="enable verbose output", action='store_true', ) parser.add_argument( '-c', '--config', help="config file", type=pathlib.Path, default=pathlib.Path('config.cfg'), ) parser.set_defaults(func=None) subparsers = parser.add_subparsers(metavar='subcommand') for entry_point in pkg_resources.iter_entry_points('jacquard.commands'): command = entry_point.load()() command_help = getattr(command, 'help', entry_point.name) subparser = subparsers.add_parser( entry_point.name, help=command_help, description=command_help, ) subparser.set_defaults(func=command.handle) command.add_arguments(subparser) return parser def main(args=sys.argv[1:]): parser = argument_parser() options = parser.parse_args(args) if options.func is None: parser.print_help() return # Parse options config = load_config(options.config) # Run subcommand options.func(config, options) if '__name__' == '__main__': main()
import sys import pathlib import argparse import pkg_resources from jacquard.config import load_config def argument_parser(): parser = argparse.ArgumentParser(description="Split testing server") parser.add_argument( '-v', '--verbose', help="enable verbose output", action='store_true', ) parser.add_argument( '-c', '--config', help="config file", type=pathlib.Path, default=pathlib.Path('config.cfg'), ) parser.set_defaults(func=None) subparsers = parser.add_subparsers(metavar='subcommand') for entry_point in pkg_resources.iter_entry_points('jacquard.commands'): command = entry_point.load()() command_help = getattr(command, 'help', entry_point.name) subparser = subparsers.add_parser( entry_point.name, help=command_help, description=command_help, ) subparser.set_defaults(func=command.handle) command.add_arguments(subparser) return parser def main(args=sys.argv[1:]): parser = argument_parser() options = parser.parse_args(args) if options.func is None: parser.print_usage() return # Parse options config = load_config(options.config) # Run subcommand options.func(config, options) if '__name__' == '__main__': main()
Remove unused code and get rid of flake8 errors
import json import os import time from google.appengine.api import urlfetch def getUserId(user, id_type="email"): if id_type == "email": return user.email() if id_type == "oauth": """A workaround implementation for getting userid.""" auth = os.getenv('HTTP_AUTHORIZATION') bearer, token = auth.split() token_type = 'id_token' if 'OAUTH_USER_ID' in os.environ: token_type = 'access_token' url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?%s=%s' % (token_type, token)) user = {} wait = 1 for i in range(3): resp = urlfetch.fetch(url) if resp.status_code == 200: user = json.loads(resp.content) break elif resp.status_code == 400 and 'invalid_token' in resp.content: url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?%s=%s' % ('access_token', token)) else: time.sleep(wait) wait = wait + i return user.get('user_id', '')
import json import os import time import uuid from google.appengine.api import urlfetch from models import Profile def getUserId(user, id_type="email"): if id_type == "email": return user.email() if id_type == "oauth": """A workaround implementation for getting userid.""" auth = os.getenv('HTTP_AUTHORIZATION') bearer, token = auth.split() token_type = 'id_token' if 'OAUTH_USER_ID' in os.environ: token_type = 'access_token' url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?%s=%s' % (token_type, token)) user = {} wait = 1 for i in range(3): resp = urlfetch.fetch(url) if resp.status_code == 200: user = json.loads(resp.content) break elif resp.status_code == 400 and 'invalid_token' in resp.content: url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?%s=%s' % ('access_token', token)) else: time.sleep(wait) wait = wait + i return user.get('user_id', '') if id_type == "custom": # implement your own user_id creation and getting algorythm # this is just a sample that queries datastore for an existing profile # and generates an id if profile does not exist for an email profile = Conference.query(Conference.mainEmail == user.email()) if profile: return profile.id() else: return str(uuid.uuid1().get_hex())
Hide webpack build information when running karma
// Reference: http://karma-runner.github.io/0.12/config/configuration-file.html module.exports = function karmaConfig (config) { config.set({ frameworks: [ // Reference: https://github.com/karma-runner/karma-mocha // Set framework to mocha 'mocha' ], reporters: [ // Reference: https://github.com/mlex/karma-spec-reporter // Set reporter to print detailed results to console 'spec', // Reference: https://github.com/karma-runner/karma-coverage // Output code coverage files 'coverage' ], files: [ // Reference: https://www.npmjs.com/package/phantomjs-polyfill // Needed because React.js requires bind and phantomjs does not support it 'node_modules/phantomjs-polyfill/bind-polyfill.js', // Grab all files in the app folder that contain .test. 'app/**/*.test.*' ], preprocessors: { // Reference: http://webpack.github.io/docs/testing.html // Reference: https://github.com/webpack/karma-webpack // Convert files with webpack and load sourcemaps 'app/**/*.test.*': ['webpack', 'sourcemap'] }, browsers: [ // Run tests using PhantomJS 'PhantomJS' ], singleRun: true, // Configure code coverage reporter coverageReporter: { dir: 'build/coverage/', type: 'html' }, // Test webpack config webpack: require('./webpack.test'), // Hide webpack build information from output webpackMiddleware: { noInfo: true } }) }
// Reference: http://karma-runner.github.io/0.12/config/configuration-file.html module.exports = function karmaConfig (config) { config.set({ frameworks: [ // Reference: https://github.com/karma-runner/karma-mocha // Set framework to mocha 'mocha' ], reporters: [ // Reference: https://github.com/mlex/karma-spec-reporter // Set reporter to print detailed results to console 'spec', // Reference: https://github.com/karma-runner/karma-coverage // Output code coverage files 'coverage' ], files: [ // Reference: https://www.npmjs.com/package/phantomjs-polyfill // Needed because React.js requires bind and phantomjs does not support it 'node_modules/phantomjs-polyfill/bind-polyfill.js', // Grab all files in the app folder that contain .test. 'app/**/*.test.*' ], preprocessors: { // Reference: http://webpack.github.io/docs/testing.html // Reference: https://github.com/webpack/karma-webpack // Convert files with webpack and load sourcemaps 'app/**/*.test.*': ['webpack', 'sourcemap'] }, browsers: [ // Run tests using PhantomJS 'PhantomJS' ], singleRun: true, // Configure code coverage reporter coverageReporter: { dir: 'build/coverage/', type: 'html' }, // Test webpack config webpack: require('./webpack.test') }) }
Update comments. Remove redundant comment
<?php /** * @author Pierre-Henry Soria <[email protected]> * @copyright (c) 2018, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / App / System / Module /PWA / Controller */ namespace PH7; use PH7\Framework\Http\Http; class MainController extends Controller { const CONTENT_TYPE = 'application/json'; const JSON_TPL_EXT = '.json.tpl'; public function manifest() { $this->setContentType(); $this->view->bg_color = $this->config->values['module.setting']['background_color']; $this->jsonOutput(); } /** * @return void * * @throws Framework\Http\Exception * @throws Framework\Layout\Tpl\Engine\PH7Tpl\Exception */ private function jsonOutput() { /* Compression damages JSON syntax, so disable them */ $this->view->setHtmlCompress(false); $this->view->setPhpCompress(false); $this->setContentType(); // Header, output format $this->view->display($this->httpRequest->currentController() . PH7_DS . $this->registry->action . self::JSON_TPL_EXT); } /** * @return void * * @throws Framework\Http\Exception */ private function setContentType() { Http::setContentType(self::CONTENT_TYPE); } }
<?php /** * @author Pierre-Henry Soria <[email protected]> * @copyright (c) 2018, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / App / System / Module /PWA / Controller */ namespace PH7; use PH7\Framework\Http\Http; class MainController extends Controller { const CONTENT_TYPE = 'application/json'; const JSON_TPL_EXT = '.json.tpl'; public function manifest() { $this->setContentType(); $this->view->bg_color = $this->config->values['module.setting']['background_color']; $this->jsonOutput(); } /** * @return void * * @throws Framework\Http\Exception * @throws Framework\Layout\Tpl\Engine\PH7Tpl\Exception */ private function jsonOutput() { /* Compression damages JSON syntax, so disable them */ $this->view->setHtmlCompress(false); $this->view->setPhpCompress(false); // Display $this->setContentType(); // Header $this->view->display($this->httpRequest->currentController() . PH7_DS . $this->registry->action . self::JSON_TPL_EXT); } /** * @return void * * @throws Framework\Http\Exception */ private function setContentType() { Http::setContentType(self::CONTENT_TYPE); //Output format } }
Print audiolang in json output
import json # save info from common.print_info() last_info = None def output(video_extractor, pretty_print=True): ve = video_extractor out = {} out['url'] = ve.url out['title'] = ve.title out['site'] = ve.name out['streams'] = ve.streams try: if ve.audiolang: out['audiolang'] = ve.audiolang except NameError: pass if pretty_print: print(json.dumps(out, indent=4, sort_keys=True, ensure_ascii=False)) else: print(json.dumps(out)) # a fake VideoExtractor object to save info class VideoExtractor(object): pass def print_info(site_info=None, title=None, type=None, size=None): global last_info # create a VideoExtractor and save info for download_urls() ve = VideoExtractor() last_info = ve ve.name = site_info ve.title = title ve.url = None def download_urls(urls=None, title=None, ext=None, total_size=None, refer=None): ve = last_info if not ve: ve = VideoExtractor() ve.name = '' ve.url = urls ve.title=title # save download info in streams stream = {} stream['container'] = ext stream['size'] = total_size stream['src'] = urls if refer: stream['refer'] = refer stream['video_profile'] = '__default__' ve.streams = {} ve.streams['__default__'] = stream output(ve)
import json # save info from common.print_info() last_info = None def output(video_extractor, pretty_print=True): ve = video_extractor out = {} out['url'] = ve.url out['title'] = ve.title out['site'] = ve.name out['streams'] = ve.streams if pretty_print: print(json.dumps(out, indent=4, sort_keys=True, ensure_ascii=False)) else: print(json.dumps(out)) # a fake VideoExtractor object to save info class VideoExtractor(object): pass def print_info(site_info=None, title=None, type=None, size=None): global last_info # create a VideoExtractor and save info for download_urls() ve = VideoExtractor() last_info = ve ve.name = site_info ve.title = title ve.url = None def download_urls(urls=None, title=None, ext=None, total_size=None, refer=None): ve = last_info if not ve: ve = VideoExtractor() ve.name = '' ve.url = urls ve.title=title # save download info in streams stream = {} stream['container'] = ext stream['size'] = total_size stream['src'] = urls if refer: stream['refer'] = refer stream['video_profile'] = '__default__' ve.streams = {} ve.streams['__default__'] = stream output(ve)
Include ids for scheduled events to make schedule data unique
import gevent import msgpack import redis import time from lymph.core.interfaces import Interface from lymph.core.decorators import rpc from lymph.utils import make_id class Scheduler(Interface): service_type = 'scheduler' schedule_key = 'schedule' def __init__(self, *args, **kwargs): super(Scheduler, self).__init__(*args, **kwargs) self.redis = redis.StrictRedis() def on_start(self): self.container.spawn(self.loop) @rpc() def schedule(self, channel, eta, event_type, payload): self.redis.zadd(self.schedule_key, eta, msgpack.dumps({ 'id': make_id(), 'event_type': event_type, 'payload': payload, })) channel.ack() def loop(self): while True: pipe = self.redis.pipeline() now = int(time.time()) pipe.zrangebyscore(self.schedule_key, 0, now) pipe.zremrangebyscore(self.schedule_key, 0, now) events, n = pipe.execute() for event in events: event = msgpack.loads(event, encoding='utf-8') self.emit(event['event_type'], event['payload']) gevent.sleep(1)
import gevent import msgpack import redis import time from lymph.core.interfaces import Interface from lymph.core.decorators import rpc class Scheduler(Interface): service_type = 'scheduler' schedule_key = 'schedule' def __init__(self, *args, **kwargs): super(Scheduler, self).__init__(*args, **kwargs) self.redis = redis.StrictRedis() def on_start(self): self.container.spawn(self.loop) @rpc() def schedule(self, channel, eta, event_type, payload): self.redis.zadd(self.schedule_key, eta, msgpack.dumps({ 'event_type': event_type, 'payload': payload, })) channel.ack() def loop(self): while True: pipe = self.redis.pipeline() now = int(time.time()) # FIXME: handle timezones pipe.zrangebyscore(self.schedule_key, 0, now) pipe.zremrangebyscore(self.schedule_key, 0, now) events, n = pipe.execute() for event in events: event = msgpack.loads(event, encoding='utf-8') self.emit(event['event_type'], event['payload']) gevent.sleep(1)
Add empty line at EOF
<?php namespace Modules\Blog\Repositories\Cache; use Modules\Blog\Repositories\TagRepository; use Modules\Core\Repositories\Cache\BaseCacheDecorator; class CacheTagDecorator extends BaseCacheDecorator implements TagRepository { /** * @var TagRepository */ protected $repository; public function __construct(TagRepository $tag) { parent::__construct(); $this->entityName = 'tags'; $this->repository = $tag; } /** * @param $name * @return mixed */ public function findByName($name) { return $this->cache ->tags($this->entityName, 'global') ->remember("{$this->locale}.{$this->entityName}.findByName.{$name}", $this->cacheTime, function () use ($name) { return $this->repository->findByName($name); } ); } /** * Create the tag for the specified language * * @param string $lang * @param array $name * @return mixed */ public function createForLanguage($lang, $name) { $this->cache->tags($this->entityName)->flush(); return $this->repository->createForLanguage($lang, $name); } }
<?php namespace Modules\Blog\Repositories\Cache; use Modules\Blog\Repositories\TagRepository; use Modules\Core\Repositories\Cache\BaseCacheDecorator; class CacheTagDecorator extends BaseCacheDecorator implements TagRepository { /** * @var TagRepository */ protected $repository; public function __construct(TagRepository $tag) { parent::__construct(); $this->entityName = 'tags'; $this->repository = $tag; } /** * @param $name * @return mixed */ public function findByName($name) { return $this->cache ->tags($this->entityName, 'global') ->remember("{$this->locale}.{$this->entityName}.findByName.{$name}", $this->cacheTime, function () use ($name) { return $this->repository->findByName($name); } ); } /** * Create the tag for the specified language * * @param string $lang * @param array $name * @return mixed */ public function createForLanguage($lang, $name) { $this->cache->tags($this->entityName)->flush(); return $this->repository->createForLanguage($lang, $name); } }
Set the radio to the previous status if there is a fail
FrontendCore.define('on-off-table', ['devicePackage' ], function () { return { onStart: function () { FrontendCore.requireAndStart('notification'); $('.switch input').each( function(){ var oTarget = this; $(oTarget).change( function() { var oInput = this, sValue = oInput.checked, sUrl = this.checked === true ? document.getElementById('enable-' + this.id).value : document.getElementById('disable-' + this.id).value; $.ajax({ url: sUrl, type: 'post' }).fail( function( response ) { if ( sValue === true ) { oInput.checked = false; } else { oInput.checked = true; } var sMessage = response.responseJSON.message !== undefined ? response.responseJSON.message : 'Sorry, something was wrong.'; FrontendMediator.publish( 'notification', { type : 'ko', message: sMessage } ); }); }); }); } }; });
FrontendCore.define('on-off-table', ['devicePackage' ], function () { return { onStart: function () { FrontendCore.requireAndStart('notification'); $('.switch input').each( function(){ var oTarget = this; $(oTarget).change( function() { var sUrl = this.checked === true ? document.getElementById('enable-' + this.id).value : document.getElementById('disable-' + this.id).value ; $.ajax({ url: sUrl, type: 'post' }).fail( function( response ) { var sMessage = response.responseJSON.message !== undefined ? response.responseJSON.message : 'Sorry, something was wrong.'; FrontendMediator.publish( 'notification', { type : 'ko', message: sMessage } ); $(oTarget).click(); }); }); }); } }; });
Add GA events for Explore detail footer links
import React from 'react'; import PropTypes from 'prop-types'; // Utils import { logEvent } from 'utils/analytics'; // Styles import './styles.scss'; function ExploreDetailFooterComponent(props) { const { setSidebarAnchor } = props; return ( <div className="c-explore-detail-footer"> <a onClick={() => { setSidebarAnchor('overview'); logEvent('Explore (Detail)', 'Clicks to Scroll', 'Overview'); }} onKeyPress={() => { setSidebarAnchor('overview'); logEvent('Explore (Detail)', 'Clicks to Scroll', 'Overview'); }} role="button" tabIndex={0} > OVERVIEW </a> <a onClick={() => { setSidebarAnchor('layers'); logEvent('Explore (Detail)', 'Clicks to Scroll', 'Layers'); }} onKeyPress={() => { setSidebarAnchor('layers'); logEvent('Explore (Detail)', 'Clicks to Scroll', 'Layers'); }} role="button" tabIndex={0} > LAYERS </a> <a onClick={() => { setSidebarAnchor('visualization'); logEvent('Explore (Detail)', 'Clicks to Scroll', 'Visualization'); }} onKeyPress={() => { setSidebarAnchor('visualization'); logEvent('Explore (Detail)', 'Clicks to Scroll', 'Visualization'); }} role="button" tabIndex={0} > VISUALIZATION </a> <a onClick={() => { setSidebarAnchor('further_information'); logEvent('Explore (Detail)', 'Clicks to Scroll', 'Further information'); }} onKeyPress={() => { setSidebarAnchor('further_information'); logEvent('Explore (Detail)', 'Clicks to Scroll', 'Further information'); }} role="button" tabIndex={0} > FURTHER INFORMATION </a> </div> ); } ExploreDetailFooterComponent.propTypes = { setSidebarAnchor: PropTypes.func.isRequired }; export default ExploreDetailFooterComponent;
import React from 'react'; import PropTypes from 'prop-types'; // Styles import './styles.scss'; function ExploreDetailFooterComponent(props) { const { setSidebarAnchor } = props; return ( <div className="c-explore-detail-footer"> <a onClick={() => setSidebarAnchor('overview')} onKeyPress={() => setSidebarAnchor('overview')} role="button" tabIndex={0} > OVERVIEW </a> <a onClick={() => setSidebarAnchor('layers')} onKeyPress={() => setSidebarAnchor('layers')} role="button" tabIndex={0} > LAYERS </a> <a onClick={() => setSidebarAnchor('visualization')} onKeyPress={() => setSidebarAnchor('visualization')} role="button" tabIndex={0} > VISUALIZATION </a> <a onClick={() => setSidebarAnchor('further_information')} onKeyPress={() => setSidebarAnchor('further_information')} role="button" tabIndex={0} > FURTHER INFORMATION </a> </div> ); } ExploreDetailFooterComponent.propTypes = { setSidebarAnchor: PropTypes.func.isRequired }; export default ExploreDetailFooterComponent;
Use cheerio for line number instead of jQuery Option available in MJML 3.2
'use babel'; import { documentParser, MJMLValidator } from 'mjml' import container from './container' export default { activate() { window.mjml_disable_jquery = true require('atom-package-deps').install(); }, deactivate() { window.mjml_disable_jquery = false }, provideLinter() { return { name: 'MJML', scope: 'file', grammarScopes: ['text.mjml.basic'], lintsOnChange: false, lint: (TextEditor) => { return new Promise(resolve => { const filePath = TextEditor.getPath(); const fileText = TextEditor.getText() const MJMLDocument = documentParser(fileText, { container: container(), defaultAttributes: {}, cssClasses: {}, css: [], fonts: [] }) const report = MJMLValidator(MJMLDocument) const formattedError = report.map(e => { const line = e.line - 1 const currentLine = TextEditor.getBuffer().lineForRow(e.line - 1) return { filePath, range: [[line, currentLine.indexOf('<')], [line, TextEditor.getBuffer().lineLengthForRow(line)]], type: 'Error', text: e.message } }) resolve(formattedError) }) } } } }
'use babel'; import { documentParser, MJMLValidator } from 'mjml' import container from './container' export default { activate() { require('atom-package-deps').install(); }, deactivate() { }, provideLinter() { return { name: 'MJML', scope: 'file', grammarScopes: ['text.mjml.basic'], lintsOnChange: false, lint: (TextEditor) => { return new Promise(resolve => { const filePath = TextEditor.getPath(); const fileText = TextEditor.getText() const MJMLDocument = documentParser(fileText, { container: container(), defaultAttributes: {}, cssClasses: {}, css: [], fonts: [] }) const report = MJMLValidator(MJMLDocument) const formattedError = report.map(e => { const line = e.line - 1 const currentLine = TextEditor.getBuffer().lineForRow(e.line - 1) return { filePath, range: [[line, currentLine.indexOf('<')], [line, TextEditor.getBuffer().lineLengthForRow(line)]], type: 'Error', text: e.message } }) resolve(formattedError) }) } } } }
Fix up route to logs tab
import React from 'react'; import TaskDetail from './TaskDetail'; import MesosStateStore from '../../../../../../src/js/stores/MesosStateStore'; import ServiceBreadcrumbs from '../../components/ServiceBreadcrumbs'; import Page from '../../../../../../src/js/components/Page'; class ServiceTaskDetailPage extends React.Component { render() { const {params, routes} = this.props; const {id, taskID} = params; let routePrefix = `/services/overview/${encodeURIComponent(id)}/tasks/${encodeURIComponent(taskID)}`; const tabs = [ {label: 'Details', routePath: routePrefix + '/details'}, {label: 'Files', routePath: routePrefix + '/files'}, {label: 'Logs', routePath: routePrefix + '/view'} ]; let task = MesosStateStore.getTaskFromTaskID(taskID); if (task == null) { return this.getNotFound('task', taskID); } const breadcrumbs = ( <ServiceBreadcrumbs serviceID={id} taskID={task.getId()} taskName={task.getName()} /> ); return ( <Page> <Page.Header breadcrumbs={breadcrumbs} tabs={tabs} iconID="services" /> <TaskDetail params={params} routes={routes}> {this.props.children} </TaskDetail> </Page> ); } } TaskDetail.propTypes = { params: React.PropTypes.object, routes: React.PropTypes.array }; module.exports = ServiceTaskDetailPage;
import React from 'react'; import TaskDetail from './TaskDetail'; import MesosStateStore from '../../../../../../src/js/stores/MesosStateStore'; import ServiceBreadcrumbs from '../../components/ServiceBreadcrumbs'; import Page from '../../../../../../src/js/components/Page'; class ServiceTaskDetailPage extends React.Component { render() { const {params, routes} = this.props; const {id, taskID} = params; let routePrefix = `/services/overview/${encodeURIComponent(id)}/tasks/${encodeURIComponent(taskID)}`; const tabs = [ {label: 'Details', routePath: routePrefix + '/details'}, {label: 'Files', routePath: routePrefix + '/files'}, {label: 'Logs', routePath: routePrefix + '/logs'} ]; let task = MesosStateStore.getTaskFromTaskID(taskID); if (task == null) { return this.getNotFound('task', taskID); } const breadcrumbs = ( <ServiceBreadcrumbs serviceID={id} taskID={task.getId()} taskName={task.getName()} /> ); return ( <Page> <Page.Header breadcrumbs={breadcrumbs} tabs={tabs} iconID="services" /> <TaskDetail params={params} routes={routes}> {this.props.children} </TaskDetail> </Page> ); } } TaskDetail.propTypes = { params: React.PropTypes.object, routes: React.PropTypes.array }; module.exports = ServiceTaskDetailPage;
Revert "Bumping the version reflecting the bugfix" This reverts commit 7f3daf4755aff19d04acf865df39f7d188655b15.
#!/usr/bin/env python from __future__ import unicode_literals from setuptools import setup, find_packages install_requires = [ "Jinja2", "boto>=2.36.0", "flask", "httpretty==0.8.10", "requests", "xmltodict", "six", "werkzeug", "sure", "freezegun" ] extras_require = { # No builtin OrderedDict before 2.7 ':python_version=="2.6"': ['ordereddict'], } setup( name='moto', version='0.4.27', description='A library that allows your python tests to easily' ' mock out the boto library', author='Steve Pulec', author_email='[email protected]', url='https://github.com/spulec/moto', entry_points={ 'console_scripts': [ 'moto_server = moto.server:main', ], }, packages=find_packages(exclude=("tests", "tests.*")), install_requires=install_requires, extras_require=extras_require, license="Apache", test_suite="tests", classifiers=[ "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "License :: OSI Approved :: Apache Software License", "Topic :: Software Development :: Testing", ], )
#!/usr/bin/env python from __future__ import unicode_literals from setuptools import setup, find_packages install_requires = [ "Jinja2", "boto>=2.36.0", "flask", "httpretty==0.8.10", "requests", "xmltodict", "six", "werkzeug", "sure", "freezegun" ] extras_require = { # No builtin OrderedDict before 2.7 ':python_version=="2.6"': ['ordereddict'], } setup( name='moto', version='0.4.28', description='A library that allows your python tests to easily' ' mock out the boto library', author='Steve Pulec', author_email='[email protected]', url='https://github.com/spulec/moto', entry_points={ 'console_scripts': [ 'moto_server = moto.server:main', ], }, packages=find_packages(exclude=("tests", "tests.*")), install_requires=install_requires, extras_require=extras_require, license="Apache", test_suite="tests", classifiers=[ "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "License :: OSI Approved :: Apache Software License", "Topic :: Software Development :: Testing", ], )
Fix crash on boot (Android 8.0 or later)
package jp.takke.datastats; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.preference.PreferenceManager; import jp.takke.util.MyLog; public class BootReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { MyLog.i("BootReceiver.onReceive"); if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) { // 端末起動時の処理 // 自動起動の確認 final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context); final boolean startOnBoot = pref.getBoolean(C.PREF_KEY_START_ON_BOOT, false); MyLog.i("start on boot[" + (startOnBoot ? "YES" : "NO") + "]"); if (startOnBoot) { // サービス起動 final Intent serviceIntent = new Intent(context, LayerService.class); if (Build.VERSION.SDK_INT >= 26) { context.startForegroundService(serviceIntent); } else { context.startService(serviceIntent); } } } } }
package jp.takke.datastats; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import jp.takke.util.MyLog; public class BootReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { MyLog.i("BootReceiver.onReceive"); if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) { // 端末起動時の処理 // 自動起動の確認 final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context); final boolean startOnBoot = pref.getBoolean(C.PREF_KEY_START_ON_BOOT, false); MyLog.i("start on boot[" + (startOnBoot ? "YES" : "NO") + "]"); if (startOnBoot) { // サービス起動 final Intent serviceIntent = new Intent(context, LayerService.class); context.startService(serviceIntent); } } } }
Fix path to the plugin Node 0.12 throws an error: Cannot find module '.' https://travis-ci.org/maltsev/gulp-htmlnano/jobs/103625617
import expect from 'expect'; import File from 'vinyl'; import es from 'event-stream'; import gulpHtmlnano from './index'; const html = '<div> <!-- test --> </div>'; const minifiedHtml = '<div></div>'; describe('gulp-htmlnano', () => { it('should minify HTML', (done) => { init(html, minifiedHtml, done); }); it('should not remove HTML comments if removeComments == false', (done) => { init(html, '<div><!-- test --></div>', done, {removeComments: false}); }); it('should throw an error in stream mode', () => { let htmlFile = new File({contents: es.readArray([html])}); let pluginInstance = gulpHtmlnano(); expect(() => pluginInstance.write(htmlFile)).toThrow(/Streaming not supported/); }); it('should catch htmlnano errors', (done) => { init(html, '', done, {notDefinedModule: true}).on('error', (error) => { expect(error.message).toBe('Module "notDefinedModule" is not defined'); done(); }); }); }); function init(html, expectedHtml, done, options = {}) { let htmlFile = new File({contents: new Buffer(html)}); let pluginInstance = gulpHtmlnano(options); pluginInstance.write(htmlFile); pluginInstance.once('data', file => { expect(file.isBuffer()).toBe(true); expect(file.contents.toString('utf8')).toBe(expectedHtml); done(); }); return pluginInstance; }
import expect from 'expect'; import File from 'vinyl'; import es from 'event-stream'; import gulpHtmlnano from '.'; const html = '<div> <!-- test --> </div>'; const minifiedHtml = '<div></div>'; describe('gulp-htmlnano', () => { it('should minify HTML', (done) => { init(html, minifiedHtml, done); }); it('should not remove HTML comments if removeComments == false', (done) => { init(html, '<div><!-- test --></div>', done, {removeComments: false}); }); it('should throw an error in stream mode', () => { let htmlFile = new File({contents: es.readArray([html])}); let pluginInstance = gulpHtmlnano(); expect(() => pluginInstance.write(htmlFile)).toThrow(/Streaming not supported/); }); it('should catch htmlnano errors', (done) => { init(html, '', done, {notDefinedModule: true}).on('error', (error) => { expect(error.message).toBe('Module "notDefinedModule" is not defined'); done(); }); }); }); function init(html, expectedHtml, done, options = {}) { let htmlFile = new File({contents: new Buffer(html)}); let pluginInstance = gulpHtmlnano(options); pluginInstance.write(htmlFile); pluginInstance.once('data', file => { expect(file.isBuffer()).toBe(true); expect(file.contents.toString('utf8')).toBe(expectedHtml); done(); }); return pluginInstance; }
Add comment to core libs, modify some comment error.
package in.srain.cube.views.ptr; import android.content.Context; import android.util.AttributeSet; /** * PtrFrameLayout which use {@link PtrClassicDefaultHeader} as header view. */ public class PtrClassicFrameLayout extends PtrFrameLayout { private PtrClassicDefaultHeader mPtrClassicHeader; public PtrClassicFrameLayout(Context context) { super(context); initViews(); } public PtrClassicFrameLayout(Context context, AttributeSet attrs) { super(context, attrs); initViews(); } public PtrClassicFrameLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initViews(); } private void initViews() { mPtrClassicHeader = new PtrClassicDefaultHeader(getContext()); setHeaderView(mPtrClassicHeader); addPtrUIHandler(mPtrClassicHeader); } public PtrClassicDefaultHeader getHeader() { return mPtrClassicHeader; } /** * Specify the last update time by this key string * * @param key */ public void setLastUpdateTimeKey(String key) { if (mPtrClassicHeader != null) { mPtrClassicHeader.setLastUpdateTimeKey(key); } } /** * Using an object to specify the last update time. * * @param object */ public void setLastUpdateTimeRelateObject(Object object) { if (mPtrClassicHeader != null) { mPtrClassicHeader.setLastUpdateTimeRelateObject(object); } } }
package in.srain.cube.views.ptr; import android.content.Context; import android.util.AttributeSet; /** * PtrFrameLayout which use {@link PtrClassicFrameLayout} as header view. */ public class PtrClassicFrameLayout extends PtrFrameLayout { private PtrClassicDefaultHeader mPtrClassicHeader; public PtrClassicFrameLayout(Context context) { super(context); initViews(); } public PtrClassicFrameLayout(Context context, AttributeSet attrs) { super(context, attrs); initViews(); } public PtrClassicFrameLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initViews(); } private void initViews() { mPtrClassicHeader = new PtrClassicDefaultHeader(getContext()); setHeaderView(mPtrClassicHeader); addPtrUIHandler(mPtrClassicHeader); } public PtrClassicDefaultHeader getHeader() { return mPtrClassicHeader; } /** * Specify the last update time by this key string * * @param key */ public void setLastUpdateTimeKey(String key) { if (mPtrClassicHeader != null) { mPtrClassicHeader.setLastUpdateTimeKey(key); } } /** * Using an object to specify the last update time. * * @param object */ public void setLastUpdateTimeRelateObject(Object object) { if (mPtrClassicHeader != null) { mPtrClassicHeader.setLastUpdateTimeRelateObject(object); } } }
Add delete icon to downloaded list
/** * View for viewing downloaded videos. */ export default class DownloadedList { /** * Default constructor for setting the values * * @param {HTMLElement} element - The HTML element to bind/adopt * @param {Array<Object>} [mediaItems=null] - The array containing media items */ constructor(element, mediaItems = null) { this.element = element; this.mediaItems = mediaItems; } /** * Render page. * * The cards should show the program name, episode number and * episode length. */ render() { let html = ` <section> <ul class="listaus"> `; this.mediaItems.forEach((episode) => { html += ` <li> <span class="lLeft"> <span class="lTitle">${episode.getTitle()}</span> <span class="lDur">Kesto ${episode.getDuration()}min</span> </span> <span class="lRight"> <a href="#download/${episode.getId()}/${episode.getMediaId()}"> <i class="material-icons media-control-buttons arial-label="Stream"> delete_forever </i> <i class="material-icons media-control-buttons" arial-label="Stream"> play_circle_filled </i> </a> </span> </li> <hr> `; }); html += ` </ul> </section> `; this.element.innerHTML = html; } }
/** * View for viewing downloaded videos. */ export default class DownloadedList { /** * Default constructor for setting the values * * @param {HTMLElement} element - The HTML element to bind/adopt * @param {Array<Object>} [mediaItems=null] - The array containing media items */ constructor(element, mediaItems = null) { this.element = element; this.mediaItems = mediaItems; } /** * Render page. * * The cards should show the program name, episode number and * episode length. */ render() { let html = ` <section> <ul class="listaus"> `; this.mediaItems.forEach((episode) => { html += ` <li> <span class="lLeft"> <span class="lTitle">${episode.getTitle()}</span> <span class="lDur">Kesto ${episode.getDuration()}min</span> </span> <span class="lRight"> <a href="#download/${episode.getId()}/${episode.getMediaId()}"> <i class="material-icons media-control-buttons" arial-label="Stream"> play_circle_filled </i> </a> </span> </li> <hr> `; }); html += ` </ul> </section> `; this.element.innerHTML = html; } }
MMCorePy: Add MMCore/Host.cpp to Unix build. Was missing. Note that build is still broken (even though it does not explicitly fail), at least on Mac OS X, because of missing libraries (IOKit, CoreFoundation, and boost.system, I think). Also removed MMDevice/Property.cpp, which is not needed here. git-svn-id: 03a8048b5ee8463be5048a3801110fb50f378627@11992 d0ab736e-dc22-4aeb-8dc9-08def0aa14fd
#!/usr/bin/env python """ This setup.py is intended for use from the Autoconf/Automake build system. It makes a number of assumtions, including that the SWIG sources have already been generated. """ from distutils.core import setup, Extension import numpy.distutils.misc_util import os os.environ['CC'] = 'g++' #os.environ['CXX'] = 'g++' #os.environ['CPP'] = 'g++' #os.environ['LDSHARED'] = 'g++' mmcorepy_module = Extension('_MMCorePy', sources=['MMCorePy_wrap.cxx', '../MMCore/CircularBuffer.cpp', '../MMCore/Configuration.cpp', '../MMCore/CoreCallback.cpp', '../MMCore/CoreProperty.cpp', '../MMCore/FastLogger.cpp', '../MMCore/Host.cpp', '../MMCore/MMCore.cpp', '../MMCore/PluginManager.cpp', '../MMDevice/DeviceUtils.cpp', '../MMDevice/ImgBuffer.cpp', ], language="c++", include_dirs=numpy.distutils.misc_util.get_numpy_include_dirs(), ) setup(name='MMCorePy', version='0.1', author="Micro-Manager", description="Micro-Manager Core Python wrapper", ext_modules=[mmcorepy_module], py_modules=["MMCorePy"], )
#!/usr/bin/env python """ setup.py file for SWIG example """ from distutils.core import setup, Extension import numpy.distutils.misc_util import os os.environ['CC'] = 'g++' #os.environ['CXX'] = 'g++' #os.environ['CPP'] = 'g++' #os.environ['LDSHARED'] = 'g++' mmcorepy_module = Extension('_MMCorePy', sources=['MMCorePy_wrap.cxx', '../MMDevice/DeviceUtils.cpp', '../MMDevice/ImgBuffer.cpp', '../MMDevice/Property.cpp', '../MMCore/CircularBuffer.cpp', '../MMCore/Configuration.cpp', '../MMCore/CoreCallback.cpp', '../MMCore/CoreProperty.cpp', '../MMCore/FastLogger.cpp', '../MMCore/MMCore.cpp', '../MMCore/PluginManager.cpp'], language = "c++", extra_objects = [], include_dirs=numpy.distutils.misc_util.get_numpy_include_dirs(), ) setup (name = 'MMCorePy', version = '0.1', author = "Micro-Manager", description = "Micro-Manager Core Python wrapper", ext_modules = [mmcorepy_module], py_modules = ["MMCorePy"], )
Kill running Skia processes in ChromeOS Install step (RunBuilders:Test-ChromeOS-Alex-GMA3150-x86-Debug,Test-ChromeOS-Alex-GMA3150-x86-Release,Perf-ChromeOS-Alex-GMA3150-x86-Release) [email protected] Review URL: https://codereview.chromium.org/17599009 git-svn-id: 32fc27f4dcfb6c0385cd9719852b95fe6680452d@9748 2bbb7eff-a529-9590-31e7-b0007b416f81
#!/usr/bin/env python # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Install all executables, and any runtime resources that are needed by *both* Test and Bench builders. """ from build_step import BuildStep from chromeos_build_step import ChromeOSBuildStep from install import Install from utils import ssh_utils import os import sys class ChromeOSInstall(ChromeOSBuildStep, Install): def _PutSCP(self, executable): # First, make sure that the program isn't running. ssh_utils.RunSSH(self._ssh_username, self._ssh_host, self._ssh_port, ['killall', 'skia_%s' % executable]) ssh_utils.PutSCP(local_path=os.path.join('out', 'config', 'chromeos-' + self._args['board'], self._configuration, executable), remote_path='/usr/local/bin/skia_%s' % executable, username=self._ssh_username, host=self._ssh_host, port=self._ssh_port) def _Run(self): super(ChromeOSInstall, self)._Run() self._PutSCP('tests') self._PutSCP('gm') self._PutSCP('render_pictures') self._PutSCP('render_pdfs') self._PutSCP('bench') self._PutSCP('bench_pictures') if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(ChromeOSInstall))
#!/usr/bin/env python # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Install all executables, and any runtime resources that are needed by *both* Test and Bench builders. """ from build_step import BuildStep from chromeos_build_step import ChromeOSBuildStep from install import Install from utils import ssh_utils import os import sys class ChromeOSInstall(ChromeOSBuildStep, Install): def _PutSCP(self, executable): ssh_utils.PutSCP(local_path=os.path.join('out', 'config', 'chromeos-' + self._args['board'], self._configuration, executable), remote_path='/usr/local/bin/skia_%s' % executable, username=self._ssh_username, host=self._ssh_host, port=self._ssh_port) def _Run(self): super(ChromeOSInstall, self)._Run() self._PutSCP('tests') self._PutSCP('gm') self._PutSCP('render_pictures') self._PutSCP('render_pdfs') self._PutSCP('bench') self._PutSCP('bench_pictures') if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(ChromeOSInstall))
Allow reassigning to function parameters here Should probably turn this off globally.
/* eslint no-param-reassign: 0 */ import passport from 'passport'; import LocalStrategy from 'passport-local'; import {User} from '../models'; passport.serializeUser((user, done) => { done(null, user._id); }); passport.deserializeUser((userId, done) => { User.findById(userId, (err, user) => { if (err) { return done(err.message, null); } if (!user) { return done(null, false); } done(null, user); }); }); passport.passportLocal = new LocalStrategy( { usernameField: 'email', passwordField: 'password', }, (email, password, done) => { email = email.toLowerCase(); User.findOne({email: email}, (err, user) => { if (err) { return done(err); } if (!user) { return done(null, false, { message: 'Unknown user with email ' + email }); } user.authenticate(password, (err, ok) => { if (err) { return done(err); } if (ok) { return done(null, user); } return done(null, false, { message: 'Invalid password' }); }); }); } ); passport.use(passport.passportLocal); export default passport;
import passport from 'passport'; import LocalStrategy from 'passport-local'; import {User} from '../models'; import log from './logger'; import settings from '../settings'; passport.serializeUser((user, done) => { done(null, user._id); }); passport.deserializeUser((userId, done) => { User.findById(userId, (err, user) => { if (err) { return done(err.message, null); } if (!user) { return done(null, false); } done(null, user); }); }); passport.passportLocal = new LocalStrategy( { usernameField: 'email', passwordField: 'password', }, (email, password, done) => { const _email = email.toLowerCase(); User.findOne({email: _email}, (err, user) => { if (err) { return done(err); } if (!user) { return done(null, false, { message: 'Unknown user with email ' + _email }); } user.authenticate(password, (err, ok) => { if (err) { return done(err); } if (ok) { return done(null, user); } return done(null, false, { message: 'Invalid password' }); }); }); } ); passport.use(passport.passportLocal); export default passport;
Set default duration of user satisfaction graph to 30 days
define([ 'extensions/controllers/module', 'common/views/visualisations/completion_rate', 'common/collections/user-satisfaction' ], function (ModuleController, UserSatisfactionView, UserSatisfactionCollection) { var UserSatisfactionModule = ModuleController.extend({ visualisationClass: UserSatisfactionView, collectionClass: UserSatisfactionCollection, clientRenderOnInit: true, requiresSvg: true, collectionOptions: function () { return { id: 'user_satisfaction', title: 'User satisfaction', sortBy: '_timestamp:ascending', limit: 0, min: 1, max: 5, totalAttr: 'totalRatings', valueAttr: this.model.get('value-attribute'), period: this.model.get('period') || 'day', duration: this.model.get('duration') || 30, trim: this.model.get('trim') || true, axes: _.merge({ x: { label: 'Date', key: '_start_at', format: 'date' }, y: [ { label: this.model.get('title'), key: 'rating', format: 'percent' } ] }, this.model.get('axes')) }; }, visualisationOptions: function () { return { totalAttr: 'totalRatings', valueAttr: this.model.get('value-attribute') }; } }); return UserSatisfactionModule; });
define([ 'extensions/controllers/module', 'common/views/visualisations/completion_rate', 'common/collections/user-satisfaction' ], function (ModuleController, UserSatisfactionView, UserSatisfactionCollection) { var UserSatisfactionModule = ModuleController.extend({ visualisationClass: UserSatisfactionView, collectionClass: UserSatisfactionCollection, clientRenderOnInit: true, requiresSvg: true, collectionOptions: function () { return { id: 'user_satisfaction', title: 'User satisfaction', sortBy: '_timestamp:ascending', limit: 0, min: 1, max: 5, totalAttr: 'totalRatings', valueAttr: this.model.get('value-attribute'), period: this.model.get('period') || 'day', duration: this.model.get('duration') || 63, trim: this.model.get('trim') || 8, axes: _.merge({ x: { label: 'Date', key: '_start_at', format: 'date' }, y: [ { label: this.model.get('title'), key: 'rating', format: 'percent' } ] }, this.model.get('axes')) }; }, visualisationOptions: function () { return { totalAttr: 'totalRatings', valueAttr: this.model.get('value-attribute') }; } }); return UserSatisfactionModule; });
Fix for case insensitive string comparison assertion in checkbox group field test In SilverStripe 4.4 field labels are sentence cased. This changes the assertion to be flexible and pass in 4.4+ as well as <=4.3
<?php namespace DNADesign\Elemental\Tests\Forms; use DNADesign\Elemental\Forms\TextCheckboxGroupField; use SilverStripe\Dev\SapphireTest; use SilverStripe\Forms\CheckboxField; use SilverStripe\Forms\CompositeField; use SilverStripe\Forms\TextField; class TextCheckboxGroupFieldTest extends SapphireTest { /** * @var TextCheckboxGroupField */ protected $field; protected function setUp() { parent::setUp(); $this->field = new TextCheckboxGroupField( new TextField('HelloWorld'), new CheckboxField('Display') ); } public function testFieldIsAssignedFirstFieldsTitleInConstructor() { // Note: SilverStripe 4.0-4.3 = "Hello World", 4.4+ "Hello world" $this->assertTrue(strcasecmp('Hello World', $this->field->Title()) === 0); } public function testFieldReturnsCompositeFieldTemplateOnReadonlyTransformation() { $this->assertSame( TextCheckboxGroupField::class, $this->field->getTemplates()[0], 'Uses a custom template by default' ); $readonly = $this->field->performReadonlyTransformation(); $this->assertSame( CompositeField::class, $readonly->getTemplate(), 'Uses CompositeField template for readonly' ); } }
<?php namespace DNADesign\Elemental\Tests\Forms; use DNADesign\Elemental\Forms\TextCheckboxGroupField; use SilverStripe\Dev\SapphireTest; use SilverStripe\Forms\CheckboxField; use SilverStripe\Forms\CompositeField; use SilverStripe\Forms\TextField; class TextCheckboxGroupFieldTest extends SapphireTest { /** * @var TextCheckboxGroupField */ protected $field; protected function setUp() { parent::setUp(); $this->field = new TextCheckboxGroupField( new TextField('HelloWorld'), new CheckboxField('Display') ); } public function testFieldIsAssignedFirstFieldsTitleInConstructor() { $this->assertSame('Hello World', $this->field->Title()); } public function testFieldReturnsCompositeFieldTemplateOnReadonlyTransformation() { $this->assertSame( TextCheckboxGroupField::class, $this->field->getTemplates()[0], 'Uses a custom template by default' ); $readonly = $this->field->performReadonlyTransformation(); $this->assertSame( CompositeField::class, $readonly->getTemplate(), 'Uses CompositeField template for readonly' ); } }
Remove logger warning in favor of print for now
import logging from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, HTML, Div, Submit logger = logging.getLogger("sheepdog_tables") class CSVExportForm(forms.Form): id = forms.CharField(widget=forms.HiddenInput) class EditTableSubmitForm(forms.Form): def __init__(self, table, table_key, *args, **kwargs): self.table = table if not any([c.editable for c in self.table.table_columns.values()]): print "Warning: Editable table has no editable columns" super(EditTableSubmitForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'POST' self.helper.form_class = 'form-horizontal' self.helper.layout = Layout( Div( HTML("<h4>Bulk Editing</h4>"), HTML("<p>This will submit all fields in the table.</p>"), Div( Div( Submit( name='submit', value="Save", data_edittable_form="edittable_%s" % table_key, css_class="btn btn-primary"), css_class="filter-btns btn-group"), css_class="filter-btns-row btn-toolbar"), css_class="well filtering-well"), )
import logging from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, HTML, Div, Submit logger = logging.getLogger("sheepdog_tables") class CSVExportForm(forms.Form): id = forms.CharField(widget=forms.HiddenInput) class EditTableSubmitForm(forms.Form): def __init__(self, table, table_key, *args, **kwargs): self.table = table if not any([c.editable for c in self.table.table_columns.values()]): print "Warning: Editable table has no editable columns" logger.warning("Editable table has no editable columns") super(EditTableSubmitForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'POST' self.helper.form_class = 'form-horizontal' self.helper.layout = Layout( Div( HTML("<h4>Bulk Editing</h4>"), HTML("<p>This will submit all fields in the table.</p>"), Div( Div( Submit( name='submit', value="Save", data_edittable_form="edittable_%s" % table_key, css_class="btn btn-primary"), css_class="filter-btns btn-group"), css_class="filter-btns-row btn-toolbar"), css_class="well filtering-well"), )
Add _send function for hacky-ness
(function() { 'use strict'; // This is my local Docker IRC server var defaultHost = '192.168.99.100:6667'; angular.module('app.factories.chat', []). factory('chat', Chat); Chat.$inject = ['$websocket', '$rootScope']; function Chat($websocket, $rootScope) { var ws = $websocket('ws://localhost:6060?server=' + defaultHost); $rootScope.logs = []; ws.onMessage(function(message) { console.log(message); var d = JSON.parse(message.data); $rootScope.logs.push(d); }); ws.onOpen(function() { console.log('WebSocket opened!'); ws.send({ name: 'SET', message: defaultHost + '/#roomtest' }); methods.setNick('paked'); }); var methods = { sendMessage: function(message) { ws.send({ name: 'SEND', message: message, channel: defaultHost + '/#roomtest' }); }, setNick: function(nick) { ws.send({ name: 'NICK', message: nick }); }, _send: function(obj) { ws.send(obj); } }; return methods; } })();
(function() { 'use strict'; // This is my local Docker IRC server var defaultHost = '192.168.99.100:6667'; angular.module('app.factories.chat', []). factory('chat', Chat); Chat.$inject = ['$websocket', '$rootScope']; function Chat($websocket, $rootScope) { var ws = $websocket('ws://localhost:6060?server=' + defaultHost); $rootScope.logs = []; ws.onMessage(function(message) { console.log(message); var d = JSON.parse(message.data); $rootScope.logs.push(d); }); ws.onOpen(function() { console.log('WebSocket opened!'); ws.send({ name: 'SET', message: defaultHost + '/#roomtest' }); methods.setNick('paked'); }); var methods = { sendMessage: function(message) { ws.send({ name: 'SEND', message: message, channel: defaultHost + '/#roomtest' }); }, setNick: function(nick) { ws.send({ name: 'NICK', message: nick }); } }; return methods; } })();
Update the email selection UI
var getThat = {}; getThat.controller = function() { }; getThat.header = function() { return m('.row', [ m('.col-md-10', [ m('.jumbotron', [ m('h1', [ m('a[href="//getthat.email"]', 'Get That Email') ]) ]) ]) ]); }; getThat.emailSelectBtn = function() { return m('button.btn.btn-default.dropdown-toggle[type="button"][data-toggle="dropdown"]', [ 'Select a Domain ', m('span.caret'), ]); }; getThat.emailSelectDropdown = function() { return m('ul.dropdown-menu[role="menu"]', [ m('li', [ m('a[href="#"]', 'Test') ]) ]); }; getThat.input = function() { return m('.row', [ m('.col-md-10', [ m('.input-group', [ m('input.form-control[type="text"'), m('.input-group-btn', [ this.emailSelectBtn(), this.emailSelectDropdown(), m('button.btn.btn-success[type="button"]', [ m('span.glyphicon.glyphicon-credit-card'), ' Get It!' ]) ]) ]) ]) ]); }; getThat.view = function() { return m('.container', [ this.header(), this.input() ]); }; //initialize m.module(document.body, getThat);
var getThat = {}; getThat.controller = function() { }; getThat.header = function() { return m('.row', [ m('.col-md-10', [ m('.jumbotron', [ m('h1', [ m('a[href="//getthat.email"]', 'Get That Email') ]) ]) ]) ]); }; getThat.input = function() { return m('.row', [ m('.col-md-10', [ m('.input-group', [ m('input.form-control[type="text"'), m('.input-group-btn', [ m('button.btn.btn-success[type="button"', [ m('span.glyphicon.glyphicon-credit-card'), ' Get It!' ]) ]) ]) ]) ]); }; getThat.view = function() { return m('.container', [ this.header(), this.input() ]); }; //initialize m.module(document.body, getThat);
Stop event bubbling when trigger is clicked
(function ($) { 'use strict'; var settings; $.fn.tuxedoMenu = function (options) { var self = this; // Extend default settings with options settings = $.extend({ triggerSelector: '.tuxedo-menu-trigger', menuSelector: '.tuxedo-menu', isFixed: true }, options); self.addClass('tuxedo-menu tuxedo-menu-pristine animated') .toggleClass('tuxedo-menu-visible', !settings.isFixed) .toggleClass('tuxedo-menu-fixed slideOutLeft', settings.isFixed); $(settings.triggerSelector).addClass('tuxedo-menu-trigger'); $(settings.triggerSelector).on('click', function () { if (!settings.isFixed) { return; } $(settings.menuSelector) .toggleClass('slideInLeft slideOutLeft') .addClass('tuxedo-menu-visible'); return false; }); $(document).click(function (event) { if (!settings.isFixed || $(event.target).is(settings.triggerSelector)) { return; } if (!$(event.target).is(settings.triggerSelector) && !$(event.target).closest(settings.menuSelector).length) { $(settings.menuSelector) .removeClass('slideInLeft') .addClass('slideOutLeft'); } }); return self; }; }(jQuery));
(function ($) { 'use strict'; var settings; $.fn.tuxedoMenu = function (options) { var self = this; // Extend default settings with options settings = $.extend({ triggerSelector: '.tuxedo-menu-trigger', menuSelector: '.tuxedo-menu', isFixed: true }, options); self.addClass('tuxedo-menu tuxedo-menu-pristine animated') .toggleClass('tuxedo-menu-visible', !settings.isFixed) .toggleClass('tuxedo-menu-fixed slideOutLeft', settings.isFixed); $(settings.triggerSelector).addClass('tuxedo-menu-trigger'); $(settings.triggerSelector).on('click', function () { if (!settings.isFixed) { return; } $(settings.menuSelector) .toggleClass('slideInLeft slideOutLeft') .addClass('tuxedo-menu-visible'); }); $(document).click(function (event) { if (!settings.isFixed || $(event.target).is(settings.triggerSelector)) { return; } if (!$(event.target).is(settings.triggerSelector) && !$(event.target).closest(settings.menuSelector).length) { $(settings.menuSelector) .removeClass('slideInLeft') .addClass('slideOutLeft'); } }); return self; }; }(jQuery));
Add id the link where the toggleUser is bind
import React from 'react'; import { Link } from 'react-router'; import './Menu.css'; import User from './User'; import language from '../language/language'; const menuLanguage = language.components.menu; let Menu = React.createClass ({ getInitialState() { return { showUser: false }; }, toggleUser() { if (!this.state.showUser) { this.setState({showUser : true}); } else { this.setState({showUser : false}); } }, render() { const { user } = this.props; let userElement; userElement = ( <User user={user} /> ); return ( <div> <ul> <li className="Menu__item"> <Link to="recent-tracks"> {menuLanguage.recentTracks} </Link> </li> <li className="Menu__item"> <Link to="top-artists"> {menuLanguage.topArtists} </Link> </li> <li className="Menu__item"> <Link id="toggleUser" onClick={this.toggleUser}> {menuLanguage.userInfo} </Link> </li> </ul> {this.state.showUser ? userElement : null} </div> ); } }); export default Menu;
import React from 'react'; import { Link } from 'react-router'; import './Menu.css'; import User from './User'; import language from '../language/language'; const menuLanguage = language.components.menu; let Menu = React.createClass ({ getInitialState() { return { showUser: false }; }, toggleUser() { if (!this.state.showUser) { this.setState({showUser : true}); } else { this.setState({showUser : false}); } }, render() { const { user } = this.props; let userElement; userElement = ( <User user={user} /> ); return ( <div> <ul> <li className="Menu__item"> <Link to="recent-tracks"> {menuLanguage.recentTracks} </Link> </li> <li className="Menu__item"> <Link to="top-artists"> {menuLanguage.topArtists} </Link> </li> <li className="Menu__item"> <Link to="#0" onClick={this.toggleUser}> {menuLanguage.userInfo} </Link> </li> </ul> {this.state.showUser ? userElement : null} </div> ); } }); export default Menu;
Add an initial rating to new links in the rss seeder.
from datetime import datetime from time import mktime from django.contrib.auth.models import User from django.core.management.base import BaseCommand from django.utils.timezone import get_default_timezone, make_aware from feedparser import parse from mezzanine.generic.models import Rating from ...models import Link class Command(BaseCommand): def handle(self, *urls, **options): try: user_id = User.objects.filter(is_superuser=1)[0].id except IndexError: return for url in urls: for entry in parse(url).entries: link = self.entry_to_link_dict(entry) link["user_id"] = user_id try: obj = Link.objects.get(link=link["link"]) except Link.DoesNotExist: obj = Link.objects.create(**link) obj.rating.add(Rating(value=1, user_id=user_id)) def entry_to_link_dict(self, entry): link = {"title": entry.title, "gen_description": False} try: link["link"] = entry.summary.split('href="')[2].split('"')[0] except IndexError: link["link"] = entry.link try: publish_date = entry.published_parsed except AttributeError: pass else: publish_date = datetime.fromtimestamp(mktime(publish_date)) publish_date = make_aware(publish_date, get_default_timezone()) link["publish_date"] = publish_date return link
from datetime import datetime from time import mktime from django.core.management.base import BaseCommand from django.utils.timezone import get_default_timezone, make_aware from feedparser import parse from ...models import Link class Command(BaseCommand): def handle(self, *urls, **options): for url in urls: for entry in parse(url).entries: link = self.entry_to_link_dict(entry) try: Link.objects.get(link=link["link"]) except Link.DoesNotExist: Link.objects.create(**link) def entry_to_link_dict(self, entry): link = {"title": entry.title, "user_id": 1, "gen_description": False} try: link["link"] = entry.summary.split('href="')[2].split('"')[0] except IndexError: link["link"] = entry.link try: publish_date = entry.published_parsed except AttributeError: pass else: publish_date = datetime.fromtimestamp(mktime(publish_date)) publish_date = make_aware(publish_date, get_default_timezone()) link["publish_date"] = publish_date return link
Update channel to send alerts to.
var express = require('express'); var router = express.Router(); var slackBot = require('slack-bot')(process.env.URL); router.post('/', function(req, res) { // Cheap security if (req.query.secret !== process.env.SECRET) { res.sendStatus(404).end(); return; } var alertMessage = req.query.alert || 'Some alert message'; var type = req.query.type; switch(type) { case 'boxerror': alertMessage = 'Box Error'; break; case 'elevatedclientalerts': alertMessage = 'Elevated Client Alerts'; break; case 'elevatedserveralerts': alertMessage = 'Elevated Server Alerts'; break; case 'jobfailed': alertMessage = 'Job Failed'; break; case 'memoryquotaexceeded': alertMessage = 'Memory Quota Exceeded'; break; case 'requesttimeouts': alertMessage = 'Request Timeouts'; break; case 'slowrequests': alertMessage = 'Slow Requests'; break; } slackBot.send({ channel: '#alerts', username: 'Loggly', icon_emoji: ':loggly:', attachments: [{ fallback: 'Alert', color: 'danger', text: '<!channel>', fields: [{ title: 'Type', value: alertMessage }] }] }, function() { res.sendStatus(201).end(); }); }); module.exports = router;
var express = require('express'); var router = express.Router(); var slackBot = require('slack-bot')(process.env.URL); router.post('/', function(req, res) { // Cheap security if (req.query.secret !== process.env.SECRET) { res.sendStatus(404).end(); return; } var alertMessage = req.query.alert || 'Some alert message'; var type = req.query.type; switch(type) { case 'boxerror': alertMessage = 'Box Error'; break; case 'elevatedclientalerts': alertMessage = 'Elevated Client Alerts'; break; case 'elevatedserveralerts': alertMessage = 'Elevated Server Alerts'; break; case 'jobfailed': alertMessage = 'Job Failed'; break; case 'memoryquotaexceeded': alertMessage = 'Memory Quota Exceeded'; break; case 'requesttimeouts': alertMessage = 'Request Timeouts'; break; case 'slowrequests': alertMessage = 'Slow Requests'; break; } slackBot.send({ channel: '#hackers', username: 'Loggly', icon_emoji: ':loggly:', attachments: [{ fallback: 'Alert', color: 'danger', text: '<!channel>', fields: [{ title: 'Type', value: alertMessage }] }] }, function() { res.sendStatus(201).end(); }); }); module.exports = router;
Use KDatabaseTableAbstract::getBehavior() to create behaviors using the behavior name instead of the full identifier. Component specific behaviors can now also be loaded using behavior names instead of identifier strings.
<?php /** * @version $Id$ * @category Nooku * @package Nooku_Server * @subpackage Newsfeeds * @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net). * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link http://www.nooku.org */ /** * Newsfeeds Database Table Class * * @author Babs Gsgens <http://nooku.assembla.com/profile/babsgosgens> * @category Nooku * @package Nooku_Server * @subpackage Newsfeeds */ class ComNewsfeedsDatabaseTableNewsfeeds extends KDatabaseTableDefault { public function _initialize(KConfig $config) { $sluggable = $this->getBehavior('sluggable', array('columns' => array('name'))); $config->append(array( 'identity_column' => 'id', 'base' => 'newsfeeds', 'name' => 'newsfeeds', 'behaviors' => array('lockable', 'orderable', $sluggable), 'column_map' => array( 'enabled' => 'published', 'locked_on' => 'checked_out_time', 'locked_by' => 'checked_out', 'slug' => 'alias' ) )); parent::_initialize($config); } }
<?php /** * @version $Id$ * @category Nooku * @package Nooku_Server * @subpackage Newsfeeds * @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net). * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link http://www.nooku.org */ /** * Newsfeeds Database Table Class * * @author Babs Gsgens <http://nooku.assembla.com/profile/babsgosgens> * @category Nooku * @package Nooku_Server * @subpackage Newsfeeds */ class ComNewsfeedsDatabaseTableNewsfeeds extends KDatabaseTableDefault { public function _initialize(KConfig $config) { $sluggable = KDatabaseBehavior::factory('sluggable', array('columns' => array('name'))); $config->append(array( 'identity_column' => 'id', 'base' => 'newsfeeds', 'name' => 'newsfeeds', 'behaviors' => array('lockable', 'orderable', $sluggable), 'column_map' => array( 'enabled' => 'published', 'locked_on' => 'checked_out_time', 'locked_by' => 'checked_out', 'slug' => 'alias' ) )); parent::_initialize($config); } }
:art: Remove margin around highlighted search match
/* @flow */ const LINE_BREAKS_REGEX = /(?:\r\n|\r|\n)/g export default document.registerElement('textual-velocity-preview', { prototype: Object.assign(Object.create(HTMLElement.prototype), { updatePreview (path: string, content: string, searchRegex?: RegExp) { this._path = path if (searchRegex) { const globalRegex = new RegExp(searchRegex, 'gi') content = content.replace(globalRegex, match => `<span class="highlight-success">${match}</span>`) } this.innerHTML = content.replace(LINE_BREAKS_REGEX, '<br />') }, attachedCallback () { this._clickListener = () => { if (this._path) { atom.workspace.open(this._path) } } this.addEventListener('click', this._clickListener) }, detachedCallback () { this.removeEventListener('click', this._clickListener) }, clear () { this._path = null this.innerHTML = '' }, getTitle () { return 'Preview (Textual Velocity)' }, getLongTitle () { return this.getTitle() }, getPath () { return this._path }, scrollToFirstHighlightedItem () { const el = this.querySelector('span') if (el) { el.scrollIntoViewIfNeeded() } }, dispose () { this.remove() } }) })
/* @flow */ const LINE_BREAKS_REGEX = /(?:\r\n|\r|\n)/g export default document.registerElement('textual-velocity-preview', { prototype: Object.assign(Object.create(HTMLElement.prototype), { updatePreview (path: string, content: string, searchRegex?: RegExp) { this._path = path if (searchRegex) { const globalRegex = new RegExp(searchRegex, 'gi') content = content.replace(globalRegex, match => `<span class="inline-block highlight-success">${match}</span>`) } this.innerHTML = content.replace(LINE_BREAKS_REGEX, '<br />') }, attachedCallback () { this._clickListener = () => { if (this._path) { atom.workspace.open(this._path) } } this.addEventListener('click', this._clickListener) }, detachedCallback () { this.removeEventListener('click', this._clickListener) }, clear () { this._path = null this.innerHTML = '' }, getTitle () { return 'Preview (Textual Velocity)' }, getLongTitle () { return this.getTitle() }, getPath () { return this._path }, scrollToFirstHighlightedItem () { const el = this.querySelector('span') if (el) { el.scrollIntoViewIfNeeded() } }, dispose () { this.remove() } }) })
Modify filter to show new computational sample templates.
class MCWorkflowProcessTemplatesComponentController { /*@ngInit*/ constructor(templates) { this.templates = templates.get(); this.templateTypes = [ { title: 'CREATE SAMPLES', cssClass: 'mc-create-samples-color', icon: 'fa-cubes', margin: true, templates: this.templates.filter(t => t.process_type === 'create') }, { title: 'TRANSFORMATION', cssClass: 'mc-transform-color', icon: 'fa-exclamation-triangle', templates: this.templates.filter(t => t.process_type === 'transform') }, { title: 'MEASUREMENT', cssClass: 'mc-measurement-color', icon: 'fa-circle', templates: this.templates.filter(t => t.process_type === 'measurement') }, { title: 'ANALYSIS', cssClass: 'mc-analysis-color', icon: 'fa-square', templates: this.templates.filter(t => t.process_type === 'analysis') } ]; } chooseTemplate(t) { if (this.onSelected) { this.onSelected({templateId: t.name, processId: ''}); } } } angular.module('materialscommons').component('mcWorkflowProcessTemplates', { templateUrl: 'app/project/experiments/experiment/components/processes/mc-workflow-process-templates.html', controller: MCWorkflowProcessTemplatesComponentController, bindings: { onSelected: '&' } });
class MCWorkflowProcessTemplatesComponentController { /*@ngInit*/ constructor(templates) { this.templates = templates.get(); this.templateTypes = [ { title: 'CREATE SAMPLES', cssClass: 'mc-create-samples-color', icon: 'fa-cubes', margin: true, templates: this.templates.filter(t => t.process_type === 'create' && t.name === 'Create Samples') }, { title: 'TRANSFORMATION', cssClass: 'mc-transform-color', icon: 'fa-exclamation-triangle', templates: this.templates.filter(t => t.process_type === 'transform' && t.name !== 'Create Samples') }, { title: 'MEASUREMENT', cssClass: 'mc-measurement-color', icon: 'fa-circle', templates: this.templates.filter(t => t.process_type === 'measurement') }, { title: 'ANALYSIS', cssClass: 'mc-analysis-color', icon: 'fa-square', templates: this.templates.filter(t => t.process_type === 'analysis') } ]; } chooseTemplate(t) { if (this.onSelected) { this.onSelected({templateId: t.name, processId: ''}); } } } angular.module('materialscommons').component('mcWorkflowProcessTemplates', { templateUrl: 'app/project/experiments/experiment/components/processes/mc-workflow-process-templates.html', controller: MCWorkflowProcessTemplatesComponentController, bindings: { onSelected: '&' } });
Set right source when not LTS
import { createAction } from 'redux-actions'; import { createThunkAction } from 'utils/redux'; const fetchNdcsCountryAccordionInit = createAction( 'fetchNdcsCountryAccordionInit' ); const fetchNdcsCountryAccordionReady = createAction( 'fetchNdcsCountryAccordionReady' ); const fetchNdcsCountryAccordionFailed = createAction( 'fetchNdcsCountryAccordionFailed' ); const fetchNdcsCountryAccordion = createThunkAction( 'fetchNdcsCountryAccordion', params => dispatch => { const { locations, category, compare, lts } = params; if (locations) { dispatch(fetchNdcsCountryAccordionInit()); fetch( `/api/v1/ndcs?location=${locations}&category=${category}${ lts ? '&source=LTS' : '&source[]=CAIT&source[]=WB&source[]=NDC Explore' }${!compare ? '&filter=overview' : ''}` ) .then(response => { if (response.ok) return response.json(); throw Error(response.statusText); }) .then(data => dispatch(fetchNdcsCountryAccordionReady(data))) .catch(error => { dispatch(fetchNdcsCountryAccordionFailed()); console.info(error); }); } } ); export default { fetchNdcsCountryAccordion, fetchNdcsCountryAccordionInit, fetchNdcsCountryAccordionReady, fetchNdcsCountryAccordionFailed };
import { createAction } from 'redux-actions'; import { createThunkAction } from 'utils/redux'; const fetchNdcsCountryAccordionInit = createAction( 'fetchNdcsCountryAccordionInit' ); const fetchNdcsCountryAccordionReady = createAction( 'fetchNdcsCountryAccordionReady' ); const fetchNdcsCountryAccordionFailed = createAction( 'fetchNdcsCountryAccordionFailed' ); const fetchNdcsCountryAccordion = createThunkAction( 'fetchNdcsCountryAccordion', params => dispatch => { const { locations, category, compare, lts } = params; if (locations) { dispatch(fetchNdcsCountryAccordionInit()); fetch( `/api/v1/ndcs?location=${locations}&category=${category}${ lts ? '&source=LTS' : '' }${!compare ? '&filter=overview' : ''}` ) .then(response => { if (response.ok) return response.json(); throw Error(response.statusText); }) .then(data => dispatch(fetchNdcsCountryAccordionReady(data))) .catch(error => { dispatch(fetchNdcsCountryAccordionFailed()); console.info(error); }); } } ); export default { fetchNdcsCountryAccordion, fetchNdcsCountryAccordionInit, fetchNdcsCountryAccordionReady, fetchNdcsCountryAccordionFailed };
Remove /irc status - now just doing /irc gets you the same thing.
package com.forgeessentials.chat.commands; import com.forgeessentials.chat.irc.IRCHelper; import com.forgeessentials.core.commands.ForgeEssentialsCommandBase; import com.forgeessentials.util.OutputHandler; import net.minecraft.command.ICommandSender; import net.minecraftforge.permissions.PermissionsManager.RegisteredPermValue; public class CommandIRC extends ForgeEssentialsCommandBase { @Override public String getCommandName() { return "irc"; } @Override public void processCommand(ICommandSender sender, String[] args) { if (args[0].equalsIgnoreCase("reconnect")) { IRCHelper.reconnect(sender); } else if (args[0].equalsIgnoreCase("disconnect")) { IRCHelper.shutdown(); } else { IRCHelper.status(sender); } } @Override public boolean canConsoleUseCommand() { return true; } @Override public String getPermissionNode() { return "fe.chat.irc"; } @Override public String getCommandUsage(ICommandSender sender) { return "/irc [reconnect|disconnect|status] Connect or disconnect the IRC server bot."; } @Override public RegisteredPermValue getDefaultPermission() { return RegisteredPermValue.OP; } }
package com.forgeessentials.chat.commands; import com.forgeessentials.chat.irc.IRCHelper; import com.forgeessentials.core.commands.ForgeEssentialsCommandBase; import net.minecraft.command.ICommandSender; import net.minecraftforge.permissions.PermissionsManager.RegisteredPermValue; public class CommandIRC extends ForgeEssentialsCommandBase { @Override public String getCommandName() { return "irc"; } @Override public void processCommand(ICommandSender sender, String[] args) { if (args[0].equalsIgnoreCase("reconnect")) { IRCHelper.reconnect(sender); } else if (args[0].equalsIgnoreCase("disconnect")) { IRCHelper.shutdown(); } else if (args[0].equalsIgnoreCase("staus")) { IRCHelper.status(sender); } } @Override public boolean canConsoleUseCommand() { return true; } @Override public String getPermissionNode() { return "fe.chat.irc"; } @Override public String getCommandUsage(ICommandSender sender) { return "/irc [reconnect|disconnect|status] Connect or disconnect the IRC server bot."; } @Override public RegisteredPermValue getDefaultPermission() { return RegisteredPermValue.OP; } }
BUG: Fix a bug introduced in rebasing
"""Test the 20news downloader, if the data is available.""" import numpy as np from nose.tools import assert_equal from nose.plugins.skip import SkipTest from scikits.learn import datasets def test_20news(): try: data = datasets.fetch_20newsgroups(subset='all', download_if_missing=False, shuffle=False) except IOError: raise SkipTest("Download 20 newsgroups to run this test") # Extract a reduced dataset data2cats = datasets.fetch_20newsgroups(subset='all', categories=data.target_names[-1:-3:-1], shuffle=False) # Check that the ordering of the target_names is the same # as the ordering in the full dataset assert_equal(data2cats.target_names, data.target_names[-2:]) # Assert that we have only 0 and 1 as labels assert_equal(np.unique(data2cats.target).tolist(), [0, 1]) # Check that the first entry of the reduced dataset corresponds to # the first entry of the corresponding category in the full dataset entry1 = data2cats.data[0] category = data2cats.target_names[data2cats.target[0]] label = data.target_names.index(category) entry2 = data.data[np.where(data.target == label)[0][0]] assert_equal(entry1, entry2)
"""Test the 20news downloader, if the data is available.""" import numpy as np from nose.tools import assert_equal from nose.tools import assert_true from nose.plugins.skip import SkipTest from scikits.learn import datasets def test_20news(): try: data = datasets.fetch_20newsgroups(subset='all', download_if_missing=False, shuffle=False) except IOError: raise SkipTest("Download 20 newsgroups to run this test") # Extract a reduced dataset data2cats = datasets.fetch_20newsgroups(subset='all', categories=data.target_names[-1:-3:-1], shuffle=False) # Check that the ordering of the target_names is the same # as the ordering in the full dataset assert_equal(data2cats.target_names, data.target_names[-2:]) # Assert that we have only 0 and 1 as labels assert_equal(np.unique(data2cats.target).tolist(), [0, 1]) # Check that the first entry of the reduced dataset corresponds to # the first entry of the corresponding category in the full dataset entry1 = data2cats.data[0] category = data2cats.target_names[data2cats.target[0]] label = data.target_names.index(category) entry2 = data.data[np.where(data.target == label)[0][0]] assert_equal(entry1, entry2) # check that the filenames are available too assert_true(data.filenames[0].endswith( "20news_home/20news-bydate-test/talk.politics.mideast/76560"))
Fix redirect param in sub-requests
<?php namespace AppBundle\Twig; use Symfony\Bridge\Twig\Extension\RoutingExtension as BaseRoutingExtension; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Symfony\Component\HttpFoundation\RequestStack; class RoutingExtension extends BaseRoutingExtension { /** * @var UrlGeneratorInterface */ private $generator; /** * @var RequestStack */ private $requestStack; public function __construct( UrlGeneratorInterface $generator, RequestStack $requestStack ) { $this->generator = $generator; $this->requestStack = $requestStack; parent::__construct($generator); } /** * @param string $name * @param array $parameters * @param bool $relative * * @return string */ public function getPath($name, $parameters = [], $relative = false) { if (!array_key_exists('redirect', $parameters)) { $parameters['redirect'] = '/'.$this->requestStack->getMasterRequest()->get('url'); } return parent::getPath($name, $parameters, $relative); } /** * @param string $name * @param array $parameters * @param bool $schemeRelative * * @return string */ public function getUrl($name, $parameters = [], $schemeRelative = false) { if (!array_key_exists('redirect', $parameters)) { $parameters['redirect'] = $this->requestStack->getCurrentRequest()->get('url'); } return parent::getUrl($name, $parameters, $relative); } }
<?php namespace AppBundle\Twig; use Symfony\Bridge\Twig\Extension\RoutingExtension as BaseRoutingExtension; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Symfony\Component\HttpFoundation\RequestStack; class RoutingExtension extends BaseRoutingExtension { /** * @var UrlGeneratorInterface */ private $generator; /** * @var RequestStack */ private $requestStack; public function __construct( UrlGeneratorInterface $generator, RequestStack $requestStack ) { $this->generator = $generator; $this->requestStack = $requestStack; parent::__construct($generator); } /** * @param string $name * @param array $parameters * @param bool $relative * * @return string */ public function getPath($name, $parameters = [], $relative = false) { if (!array_key_exists('redirect', $parameters)) { $parameters['redirect'] = '/'.$this->requestStack->getCurrentRequest()->get('url'); } return parent::getPath($name, $parameters, $relative); } /** * @param string $name * @param array $parameters * @param bool $schemeRelative * * @return string */ public function getUrl($name, $parameters = [], $schemeRelative = false) { if (!array_key_exists('redirect', $parameters)) { $parameters['redirect'] = $this->requestStack->getCurrentRequest()->get('url'); } return parent::getUrl($name, $parameters, $relative); } }
Update test case for new version of IUCN
<?php namespace Tests\AppBundle\API\Listing; use Symfony\Component\HttpFoundation\ParameterBag; use Tests\AppBundle\API\WebserviceTestCase; class OverviewTest extends WebserviceTestCase { const NICKNAME = 'listingOverviewTestUser'; const USERID = 'listingOverviewTestUser'; const PROVIDER = 'listingOverviewTestUser'; public function testExecute() { //Test for overview if user is not logged in $default_db = $this->default_db; $session = $this->session; $overview = $this->webservice->factory('listing', 'overview'); $parameterBag = new ParameterBag(array('dbversion' => $default_db)); $results = $overview->execute($parameterBag, $session); $expected = array( "projects" => 0, "organisms" => 198102, "trait_entries" => 88846, "trait_types" => 3 ); $this->assertEquals($expected, $results); //Test of correct project if the user has only one project $session->set('user', array( 'nickname' => OverviewTest::NICKNAME, 'id' => OverviewTest::USERID, 'provider' => OverviewTest::PROVIDER, 'token' => 'listingOverviewTestUserToken' )); $results = $overview->execute($parameterBag, $session); $expected['projects'] = 1; $this->assertEquals($expected, $results); } }
<?php namespace Tests\AppBundle\API\Listing; use Symfony\Component\HttpFoundation\ParameterBag; use Tests\AppBundle\API\WebserviceTestCase; class OverviewTest extends WebserviceTestCase { const NICKNAME = 'listingOverviewTestUser'; const USERID = 'listingOverviewTestUser'; const PROVIDER = 'listingOverviewTestUser'; public function testExecute() { //Test for overview if user is not logged in $default_db = $this->default_db; $session = $this->session; $overview = $this->webservice->factory('listing', 'overview'); $parameterBag = new ParameterBag(array('dbversion' => $default_db)); $results = $overview->execute($parameterBag, $session); $expected = array( "projects" => 0, "organisms" => 198102, "trait_entries" => 88855, "trait_types" => 3 ); $this->assertEquals($expected, $results); //Test of correct project if the user has only one project $session->set('user', array( 'nickname' => OverviewTest::NICKNAME, 'id' => OverviewTest::USERID, 'provider' => OverviewTest::PROVIDER, 'token' => 'listingOverviewTestUserToken' )); $results = $overview->execute($parameterBag, $session); $expected['projects'] = 1; $this->assertEquals($expected, $results); } }
Exclude directories during copy process
module.exports = function( grunt ) { "use strict"; var pkg = grunt.file.readJSON( "package.json" ); grunt.initConfig( { pkg: pkg, clean: [ "dist/" ], copy: { build: { options: { process: function( content ) { return content.replace( /@VERSION/g, pkg.version ); } }, files: [ { expand: true, flatten: true, filter: "isFile", cwd: "src/", src: [ "**" ], dest: "dist/" } ] } }, uglify: { options: { banner: "/*! <%=pkg.name %> | <%= pkg.version %> | <%= grunt.template.today('yyyy-mm-dd') %> */\n" }, build: { files: { "dist/jquery.ui.pinpad.min.js": "dist/jquery.ui.pinpad.js" } } }, cssmin: { build: { src: "dist/jquery.ui.pinpad.css", dest: "dist/jquery.ui.pinpad.min.css" } } }); grunt.loadNpmTasks( "grunt-contrib-clean" ); grunt.loadNpmTasks( "grunt-contrib-copy" ); grunt.loadNpmTasks( "grunt-contrib-uglify" ); grunt.loadNpmTasks( "grunt-contrib-cssmin" ); grunt.registerTask( "default", [ "clean", "copy", "uglify", "cssmin" ] ); };
module.exports = function( grunt ) { "use strict"; var pkg = grunt.file.readJSON( "package.json" ); grunt.initConfig( { pkg: pkg, clean: [ "dist/" ], copy: { build: { options: { process: function( content ) { return content.replace( /@VERSION/g, pkg.version ); } }, files: [ { expand: true, flatten: true, cwd: "src/", src: [ "**" ], dest: "dist/" } ] } }, uglify: { options: { banner: "/*! <%=pkg.name %> | <%= pkg.version %> | <%= grunt.template.today('yyyy-mm-dd') %> */\n" }, build: { files: { "dist/jquery.ui.pinpad.min.js": "dist/jquery.ui.pinpad.js" } } }, cssmin: { build: { src: "dist/jquery.ui.pinpad.css", dest: "dist/jquery.ui.pinpad.min.css" } } }); grunt.loadNpmTasks( "grunt-contrib-clean" ); grunt.loadNpmTasks( "grunt-contrib-copy" ); grunt.loadNpmTasks( "grunt-contrib-uglify" ); grunt.loadNpmTasks( "grunt-contrib-cssmin" ); grunt.registerTask( "default", [ "clean", "copy", "uglify", "cssmin" ] ); };
Add url to before navigation event
import Router from '@ember/routing/router'; export function initialize() { const isEmbedded = window !== window.top; if (isEmbedded) { Router.reopen({ notifyTopFrame: function() { window.top.postMessage({ action: 'did-transition', url: this.currentURL }) }.on('didTransition'), willTranstionNotify: function(transition) { const router = window.ls('router'); window.top.postMessage({ action: 'before-navigation', target: transition.targetName, url: router.urlFor(transition.targetName) }) }.on('willTransition') }); // Add listener for post messages to change the route in the application window.addEventListener('message', (event) => { const msg = event.data || {}; // Navigate when asked to if (msg.action === 'navigate') { const router = window.ls('router'); // If the route being asked for is already loaded, then if (router.currentRouteName === msg.name) { window.top.postMessage({ action: 'did-transition', url: router.urlFor(msg.name) }) } router.transitionTo(msg.name); } }); } } export default { name: 'route-spy', initialize, };
import Router from '@ember/routing/router'; export function initialize() { const isEmbedded = window !== window.top; if (isEmbedded) { Router.reopen({ notifyTopFrame: function() { window.top.postMessage({ action: 'did-transition', url: this.currentURL }) }.on('didTransition'), willTranstionNotify: function(transition) { window.top.postMessage({ action: 'before-navigation', target: transition.targetName }) }.on('willTransition') }); // Add listener for post messages to change the route in the application window.addEventListener('message', (event) => { const msg = event.data || {}; // Navigate when asked to if (msg.action === 'navigate') { const router = window.ls('router'); // If the route being asked for is already loaded, then if (router.currentRouteName === msg.name) { window.top.postMessage({ action: 'did-transition', url: router.urlFor(msg.name) }) } router.transitionTo(msg.name); } }); } } export default { name: 'route-spy', initialize, };
Set textAlign of delete button as right
import React, { Component } from 'react' import PropTypes from 'prop-types' import QuizInput from './QuizInput' import styled from 'styled-components' import IconButton from 'material-ui/IconButton' import ActionDelete from 'material-ui/svg-icons/action/delete' import Paper from 'material-ui/Paper' const PaperStyled = styled(Paper)` text-align: left; ` export const Element = ({ idx, quest, deleteQuiz, editQuiz }) => { function handleSave (id, quiz, isChoice) { editQuiz(`${id}`, quiz, isChoice) } return ( <div> <QuizInput idx={idx} quest={quest} onSave={(quiz, isChoice) => handleSave(quest.id, quiz, isChoice)} /> <div style={{ textAlign: 'right' }}> <IconButton tooltip='Delete'> <ActionDelete onTouchTap={() => deleteQuiz(quest.id)} /> </IconButton> </div> </div> ) } class QuizItem extends Component { render () { const { idx, quest, deleteQuiz, editQuiz } = this.props return ( <PaperStyled zDepth={2}> <Element idx={idx} quest={quest} deleteQuiz={deleteQuiz} editQuiz={editQuiz} /> </PaperStyled> ) } } QuizItem.propTypes = { idx: PropTypes.number, quest: PropTypes.object, editQuiz: PropTypes.func, deleteQuiz: PropTypes.func } export default QuizItem
import React, { Component } from 'react' import PropTypes from 'prop-types' import QuizInput from './QuizInput' import styled from 'styled-components' import IconButton from 'material-ui/IconButton' import ActionDelete from 'material-ui/svg-icons/action/delete' import Paper from 'material-ui/Paper' const PaperStyled = styled(Paper)` text-align: left; ` export const Element = ({ idx, quest, deleteQuiz, editQuiz }) => { function handleSave (id, quiz, isChoice) { editQuiz(`${id}`, quiz, isChoice) } return ( <div> <QuizInput idx={idx} quest={quest} onSave={(quiz, isChoice) => handleSave(quest.id, quiz, isChoice)} /> <div style={{ textAlign: 'center' }}> <IconButton tooltip='Delete'> <ActionDelete onTouchTap={() => deleteQuiz(quest.id)} /> </IconButton> </div> </div> ) } class QuizItem extends Component { render () { const { idx, quest, deleteQuiz, editQuiz } = this.props return ( <PaperStyled zDepth={2}> <Element idx={idx} quest={quest} deleteQuiz={deleteQuiz} editQuiz={editQuiz} /> </PaperStyled> ) } } QuizItem.propTypes = { idx: PropTypes.number, quest: PropTypes.object, editQuiz: PropTypes.func, deleteQuiz: PropTypes.func } export default QuizItem
Rename the DB from mydb to rose
var debug = require('debug')('rose'); var mongoose = require('mongoose'); var mongoURI = process.env.MONGOLAB_URI || 'mongodb://localhost/rose'; debug('Connecting to MongoDB at ' + mongoURI + '...'); mongoose.connect(mongoURI); var featureSchema = new mongoose.Schema({ name: { type: String, required: true }, examples: { type: [{ technology: { type: String, required: true }, snippets: { type: [String], required: true } }], required: true } }); featureSchema.statics.search = function (query) { return this.find({ $or: [ { name: new RegExp(query, 'i') }, { examples: { $elemMatch: { $or: [ { technology: new RegExp(query, 'i') }, { snippets: new RegExp(query, 'i') } ] }}}, ]}) .lean() .select('-__v -_id -examples._id') .exec(); }; module.exports = mongoose.model('Feature', featureSchema);
var debug = require('debug')('rose'); var mongoose = require('mongoose'); var mongoURI = process.env.MONGOLAB_URI || 'mongodb://localhost/mydb'; debug('Connecting to MongoDB at ' + mongoURI + '...'); mongoose.connect(mongoURI); var featureSchema = new mongoose.Schema({ name: { type: String, required: true }, examples: { type: [{ technology: { type: String, required: true }, snippets: { type: [String], required: true } }], required: true } }); featureSchema.statics.search = function (query) { return this.find({ $or: [ { name: new RegExp(query, 'i') }, { examples: { $elemMatch: { $or: [ { technology: new RegExp(query, 'i') }, { snippets: new RegExp(query, 'i') } ] }}}, ]}) .lean() .select('-__v -_id -examples._id') .exec(); }; module.exports = mongoose.model('Feature', featureSchema);
Change default value for mode to FTP_ASCII (in order to have the same default value with the constructor of Ftp.php)
<?php namespace Knp\Bundle\GaufretteBundle\DependencyInjection\Factory; use Symfony\Component\Config\Definition\Builder\NodeDefinition; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\DefinitionDecorator; /** * Ftp Adapter Factory */ class FtpAdapterFactory implements AdapterFactoryInterface { /** * {@inheritDoc} */ function create(ContainerBuilder $container, $id, array $config) { $container ->setDefinition($id, new DefinitionDecorator('knp_gaufrette.adapter.ftp')) ->addArgument($config['directory']) ->addArgument($config['host']) ->addArgument($config['username']) ->addArgument($config['password']) ->addArgument($config['port']) ->addArgument($config['passive']) ->addArgument($config['create']) ->addArgument($config['mode']) ; } /** * {@inheritDoc} */ function getKey() { return 'ftp'; } /** * {@inheritDoc} */ function addConfiguration(NodeDefinition $builder) { $builder ->children() ->scalarNode('directory')->isRequired()->end() ->scalarNode('host')->isRequired()->end() ->scalarNode('port')->defaultValue(21)->end() ->scalarNode('username')->defaultNull()->end() ->scalarNode('password')->defaultNull()->end() ->booleanNode('passive')->defaultFalse()->end() ->booleanNode('create')->defaultFalse()->end() ->scalarNode('mode')->defaultValue(FTP_ASCII)->end() ->end() ; } }
<?php namespace Knp\Bundle\GaufretteBundle\DependencyInjection\Factory; use Symfony\Component\Config\Definition\Builder\NodeDefinition; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\DefinitionDecorator; /** * Ftp Adapter Factory */ class FtpAdapterFactory implements AdapterFactoryInterface { /** * {@inheritDoc} */ function create(ContainerBuilder $container, $id, array $config) { $container ->setDefinition($id, new DefinitionDecorator('knp_gaufrette.adapter.ftp')) ->addArgument($config['directory']) ->addArgument($config['host']) ->addArgument($config['username']) ->addArgument($config['password']) ->addArgument($config['port']) ->addArgument($config['passive']) ->addArgument($config['create']) ->addArgument($config['mode']) ; } /** * {@inheritDoc} */ function getKey() { return 'ftp'; } /** * {@inheritDoc} */ function addConfiguration(NodeDefinition $builder) { $builder ->children() ->scalarNode('directory')->isRequired()->end() ->scalarNode('host')->isRequired()->end() ->scalarNode('port')->defaultValue(21)->end() ->scalarNode('username')->defaultNull()->end() ->scalarNode('password')->defaultNull()->end() ->booleanNode('passive')->defaultFalse()->end() ->booleanNode('create')->defaultFalse()->end() ->scalarNode('mode')->defaultValue(FTP_BINARY)->end() ->end() ; } }
Fix lat/long on autocomplete search
/** * Created by dough on 2017-02-09. */ $(function () { var latitudeInput = $('#siteLatitude'); var longitudeInput = $('#siteLongitude'); function initMap() { var address = document.getElementById('address'); var autocomplete = new google.maps.places.Autocomplete(address); var myMap = createMap(); myMap.on('click', function(e) { latitudeInput.val(e.latlng.lat); longitudeInput.val(e.latlng.lng); markLocation(myMap, latitudeInput.val(), longitudeInput.val()); }); /* User entered autocomplete results */ autocomplete.addListener('place_changed', function() { var place = autocomplete.getPlace(); if (!place.geometry) { /* User entered the name of a Place that was not suggested and pressed the Enter key, or the Place Details request failed. */ window.alert("No details available for input: '" + place.name + "'"); return; } latitudeInput.val(place.geometry.location.lat()); longitudeInput.val(place.geometry.location.lng()); markLocation(myMap, place.geometry.location.lat(), place.geometry.location.lng()); }); } _.defer(initMap) }); /* Prevent enter key from submitting form */ $(document).ready(function() { $(window).keydown(function(event){ if(event.keyCode == 13) { event.preventDefault(); return false; } }); });
/** * Created by dough on 2017-02-09. */ $(function () { var latitudeInput = $('#siteLatitude'); var longitudeInput = $('#siteLongitude'); function initMap() { var address = document.getElementById('address'); var autocomplete = new google.maps.places.Autocomplete(address); var myMap = createMap(); myMap.on('click', function(e) { latitudeInput.val(e.latlng.lat); longitudeInput.val(e.latlng.lng); markLocation(myMap, latitudeInput.val(), longitudeInput.val()); }); /* User entered autocomplete results */ autocomplete.addListener('place_changed', function() { var place = autocomplete.getPlace(); if (!place.geometry) { /* User entered the name of a Place that was not suggested and pressed the Enter key, or the Place Details request failed. */ window.alert("No details available for input: '" + place.name + "'"); return; } markLocation(myMap, place.geometry.location.lat(), place.geometry.location.lng()); }); } _.defer(initMap) }); /* Prevent enter key from submitting form */ $(document).ready(function() { $(window).keydown(function(event){ if(event.keyCode == 13) { event.preventDefault(); return false; } }); });
Add debug to handle date case (need to test).
angular.module('materialscommons').directive('processSettings', processSettingsDirective); function processSettingsDirective() { return { restrict: 'E', scope: { settings: '=', taskId: '=', templateId: '=', attribute: '=' }, controller: ProcessSettingsDirectiveController, controllerAs: 'ctrl', bindToController: true, templateUrl: 'app/project/processes/process/create/components/process-settings.html' } } /*@ngInject*/ function ProcessSettingsDirectiveController(experimentsService, toast, $stateParams) { var ctrl = this; ctrl.datePickerOptions = { formatYear: 'yy', startingDay: 1 }; ctrl.openDatePicker = openDatePicker; ctrl.updateSettingProperty = (property) => { if (!property.value) { return; } if (property._type === "date") { console.dir(property); return; } property.setup_attribute = ctrl.attribute; let propertyArgs = { template_id: ctrl.templateId, properties: [property] }; experimentsService.updateTaskTemplateProperties($stateParams.project_id, $stateParams.experiment_id, ctrl.taskId, propertyArgs) .then( () => null, () => toast.error('Unable to update property') ); }; /////////////////////////////////////// function openDatePicker($event, prop) { $event.preventDefault(); $event.stopPropagation(); prop.opened = true; } }
angular.module('materialscommons').directive('processSettings', processSettingsDirective); function processSettingsDirective() { return { restrict: 'E', scope: { settings: '=', taskId: '=', templateId: '=', attribute: '=' }, controller: ProcessSettingsDirectiveController, controllerAs: 'ctrl', bindToController: true, templateUrl: 'app/project/processes/process/create/components/process-settings.html' } } /*@ngInject*/ function ProcessSettingsDirectiveController(experimentsService, toast, $stateParams) { var ctrl = this; ctrl.datePickerOptions = { formatYear: 'yy', startingDay: 1 }; ctrl.openDatePicker = openDatePicker; ctrl.updateSettingProperty = (property) => { if (!property.value) { return; } property.setup_attribute = ctrl.attribute; let propertyArgs = { template_id: ctrl.templateId, properties: [property] }; experimentsService.updateTaskTemplateProperties($stateParams.project_id, $stateParams.experiment_id, ctrl.taskId, propertyArgs) .then( () => null, () => toast.error('Unable to update property') ); }; /////////////////////////////////////// function openDatePicker($event, prop) { $event.preventDefault(); $event.stopPropagation(); prop.opened = true; } }
Make sockets listen to parent namespaces as well. For example, /live/test will now receive messages destined for /live/test, /live and /. This allows us to send messages to multiple endpoints at once such as refreshing all liveupdate threads or the like.
import posixpath import random import gevent.queue def _walk_namespace_hierarchy(namespace): assert namespace.startswith("/") yield namespace while namespace != "/": namespace = posixpath.dirname(namespace) yield namespace class MessageDispatcher(object): def __init__(self, stats): self.consumers = {} self.stats = stats def get_connection_count(self): return sum(len(sockets) for sockets in self.consumers.itervalues()) def on_message_received(self, namespace, message): consumers = self.consumers.get(namespace, []) with self.stats.timer("sutro.dispatch"): for consumer in consumers: consumer.put(message) def listen(self, namespace, max_timeout): queue = gevent.queue.Queue() namespace = namespace.rstrip("/") for ns in _walk_namespace_hierarchy(namespace): self.consumers.setdefault(ns, []).append(queue) try: while True: # jitter the timeout a bit to ensure we don't herd timeout = max_timeout - random.uniform(0, max_timeout / 2) try: yield queue.get(block=True, timeout=timeout) except gevent.queue.Empty: yield None # ensure we're not starving others by spinning gevent.sleep() finally: for ns in _walk_namespace_hierarchy(namespace): self.consumers[ns].remove(queue) if not self.consumers[ns]: del self.consumers[ns]
import random import gevent.queue class MessageDispatcher(object): def __init__(self, stats): self.consumers = {} self.stats = stats def get_connection_count(self): return sum(len(sockets) for sockets in self.consumers.itervalues()) def on_message_received(self, namespace, message): consumers = self.consumers.get(namespace, []) with self.stats.timer("sutro.dispatch"): for consumer in consumers: consumer.put(message) def listen(self, namespace, max_timeout): queue = gevent.queue.Queue() self.consumers.setdefault(namespace, []).append(queue) try: while True: # jitter the timeout a bit to ensure we don't herd timeout = max_timeout - random.uniform(0, max_timeout / 2) try: yield queue.get(block=True, timeout=timeout) except gevent.queue.Empty: yield None # ensure we're not starving others by spinning gevent.sleep() finally: self.consumers[namespace].remove(queue) if not self.consumers[namespace]: del self.consumers[namespace]
Reset seller password when eject
'use strict'; /* global define */ define('ejecter', () => { let ejecter = {}; ejecter.methods = { /** * Resets variables when user/seller disconnects */ onEject() { if (!this.userConnected) { console.info('-> Eject seller'); this.currentSeller = {}; this.sellerConnected = false; this.sellerPasswordInput = ''; this.sellerAuth = false; return; } console.info('-> Eject user'); this.currentUser = {}; this.userConnected = false; this.basket = []; this.basketPromotions = []; this.totalCost = 0; this.totalReload = 0; this.detailedReloads = []; this.reloadMethod = 'card'; this.tab = null; } }; return ejecter; });
'use strict'; /* global define */ define('ejecter', () => { let ejecter = {}; ejecter.methods = { /** * Resets variables when user/seller disconnects */ onEject() { if (!this.userConnected) { console.info('-> Eject seller'); this.currentSeller = {}; this.sellerConnected = false; this.sellerAuth = false; return; } console.info('-> Eject user'); this.currentUser = {}; this.userConnected = false; this.basket = []; this.basketPromotions = []; this.totalCost = 0; this.totalReload = 0; this.detailedReloads = []; this.reloadMethod = 'card'; this.tab = null; } }; return ejecter; });
Add --nowait option to resubmit-tasks cmd In some use cases, waiting till the tasks finish is undesirable. Nowait option should be provided.
# -*- coding: utf-8 -*- from __future__ import print_function import sys from kobo.client.task_watcher import TaskWatcher from kobo.client import ClientCommand class Resubmit_Tasks(ClientCommand): """resubmit failed tasks""" enabled = True def options(self): self.parser.usage = "%%prog %s task_id [task_id...]" % self.normalized_name self.parser.add_option("--force", action="store_true", help="Resubmit also tasks which are closed properly.") self.parser.add_option("--nowait", default=False, action="store_true", help="Don't wait until tasks finish.") def run(self, *args, **kwargs): if len(args) == 0: self.parser.error("At least one task id must be specified.") username = kwargs.pop("username", None) password = kwargs.pop("password", None) tasks = args self.set_hub(username, password) resubmitted_tasks = [] failed = False for task_id in tasks: try: resubmitted_id = self.hub.client.resubmit_task(task_id, kwargs.pop("force", False)) resubmitted_tasks.append(resubmitted_id) except Exception as ex: failed = True print(ex) if not kwargs.get('nowait'): TaskWatcher.watch_tasks(self.hub, resubmitted_tasks) if failed: sys.exit(1)
# -*- coding: utf-8 -*- from __future__ import print_function import sys from kobo.client.task_watcher import TaskWatcher from kobo.client import ClientCommand class Resubmit_Tasks(ClientCommand): """resubmit failed tasks""" enabled = True def options(self): self.parser.usage = "%%prog %s task_id [task_id...]" % self.normalized_name self.parser.add_option("--force", action="store_true", help="Resubmit also tasks which are closed properly.") def run(self, *args, **kwargs): if len(args) == 0: self.parser.error("At least one task id must be specified.") username = kwargs.pop("username", None) password = kwargs.pop("password", None) tasks = args self.set_hub(username, password) resubmitted_tasks = [] failed = False for task_id in tasks: try: resubmitted_id = self.hub.client.resubmit_task(task_id, kwargs.pop("force", False)) resubmitted_tasks.append(resubmitted_id) except Exception as ex: failed = True print(ex) TaskWatcher.watch_tasks(self.hub, resubmitted_tasks) if failed: sys.exit(1)
Truncate address table before import, only import from one file
import os import glob from django.apps import apps from django.db import connection from django.core.management.base import BaseCommand class Command(BaseCommand): """ Turn off auto system check for all apps We will maunally run system checks only for the 'addressbase' and 'pollingstations' apps """ requires_system_checks = False def add_arguments(self, parser): parser.add_argument( 'cleaned_ab_path', help='The path to the folder containing the cleaned AddressBase CSVs' ) def handle(self, *args, **kwargs): """ Manually run system checks for the 'addressbase' and 'pollingstations' apps Management commands can ignore checks that only apply to the apps supporting the website part of the project """ self.check([ apps.get_app_config('addressbase'), apps.get_app_config('pollingstations') ]) cursor = connection.cursor() print("clearing existing data..") cursor.execute("TRUNCATE TABLE addressbase_address;") cleaned_file_path = os.path.abspath(os.path.join( kwargs['cleaned_ab_path'], "addressbase_cleaned.csv" )) print("importing from %s.." % (cleaned_file_path)) cursor.execute(""" COPY addressbase_address (UPRN,address,postcode,location) FROM '{}' (FORMAT CSV, DELIMITER ',', quote '"'); """.format(cleaned_file_path)) print("...done")
import os import glob from django.apps import apps from django.db import connection from django.core.management.base import BaseCommand class Command(BaseCommand): """ Turn off auto system check for all apps We will maunally run system checks only for the 'addressbase' and 'pollingstations' apps """ requires_system_checks = False def add_arguments(self, parser): parser.add_argument( 'cleaned_ab_path', help='The path to the folder containing the cleaned AddressBase CSVs' ) def handle(self, *args, **kwargs): """ Manually run system checks for the 'addressbase' and 'pollingstations' apps Management commands can ignore checks that only apply to the apps supporting the website part of the project """ self.check([ apps.get_app_config('addressbase'), apps.get_app_config('pollingstations') ]) glob_str = os.path.join( kwargs['cleaned_ab_path'], "*_cleaned.csv" ) for cleaned_file_path in glob.glob(glob_str): cleaned_file_path = os.path.abspath(cleaned_file_path) print(cleaned_file_path) cursor = connection.cursor() cursor.execute(""" COPY addressbase_address (UPRN,address,postcode,location) FROM '{}' (FORMAT CSV, DELIMITER ',', quote '"'); """.format(cleaned_file_path))
Save site details during install
<?php namespace BoomCMS\Installer; use BoomCMS\Core\Auth; use Illuminate\Http\Request; use Illuminate\Support\ServiceProvider as BaseServiceProvider; class ServiceProvider extends BaseServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot(Request $request, Auth\Auth $auth) { $installer = new Installer(); if ( ! $installer->isInstalled()) { $this->dispatch('Illuminate\Database\Console\Migrations\InstallCommand'); $this->dispatch('Illuminate\Database\Console\Migrations\MigrateCommand'); $installer->saveSiteDetails($request->input('site_name'), $request->input('site_email')); $person = $this->dispatch('BoomCMS\Core\Commands\CreatePerson', [$request->input('user_name'), $request->input('user_email'), []]); $auth->login($person); $page = $this->dispatch('BoomCMS\Core\Commands\CreatePage', $this->app['boomcms.page.provider'], $auth); $this->dispatch('BoomCMS\Core\Commands\CreatePagePrimaryUri', $this->app['boomcms.page.provider'], $page, '', ''); $installer->markInstalled(); } } /** * * @return void */ public function register() { $installer = new Installer(); if (php_sapi_name() !== 'cli' && ! $installer->isInstalled()) { require __DIR__ . '/../../install.php'; } $this->publishes([__DIR__.'/../../../public' => public_path('vendor/boomcms/boom-installer')], 'boomcms'); } }
<?php namespace BoomCMS\Installer; use BoomCMS\Core\Auth; use Illuminate\Http\Request; use Illuminate\Support\ServiceProvider as BaseServiceProvider; class ServiceProvider extends BaseServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot(Request $request, Auth\Auth $auth) { $installer = new Installer(); if ( ! $installer->isInstalled()) { $this->dispatch('Illuminate\Database\Console\Migrations\InstallCommand'); $this->dispatch('Illuminate\Database\Console\Migrations\MigrateCommand'); $person = $this->dispatch('BoomCMS\Core\Commands\CreatePerson', [$request->input('user_name'), $request->input('user_email'), []]); $auth->login($person); $page = $this->dispatch('BoomCMS\Core\Commands\CreatePage', $this->app['boomcms.page.provider'], $auth); $this->dispatch('BoomCMS\Core\Commands\CreatePagePrimaryUri', $this->app['boomcms.page.provider'], $page, '', ''); $installer->markInstalled(); } } /** * * @return void */ public function register() { $installer = new Installer(); if (php_sapi_name() !== 'cli' && ! $installer->isInstalled()) { require __DIR__ . '/../../install.php'; } $this->publishes([__DIR__.'/../../../public' => public_path('vendor/boomcms/boom-installer')], 'boomcms'); } }
Add notifications for changes in the user module
var _ = require('underscore'); var Mosaic = require('mosaic-commons'); var App = require('mosaic-core').App; var Api = App.Api; var Teleport = require('mosaic-teleport'); /** This module manages resource statistics. */ module.exports = Api.extend({ /** * Initializes internal fields. */ _initFields : function() { this._user = null; }, /** * Loads information about selected/active entities. */ start : function() { }, /** Closes this module. */ stop : function() { }, _http : function(url, method) { method = method || 'GET'; var client = Teleport.HttpClient.newInstance({ baseUrl : url }); return client.exec({ path : '', method : method }).then(function(json) { try { return _.isObject(json) ? json : JSON.parse(json); } catch (err) { return; } }); }, logout : function() { var that = this; return this._http(this.app.options.logoutApiUrl).then(function(user) { return that.notify(); }).then(function() { return user; }); }, getUserInfo : function() { return this._http(this.app.options.userInfoApiUrl).then(function(user) { if (!user || !user.displayName) return; return user; }); }, });
var _ = require('underscore'); var Mosaic = require('mosaic-commons'); var App = require('mosaic-core').App; var Api = App.Api; var Teleport = require('mosaic-teleport'); /** This module manages resource statistics. */ module.exports = Api.extend({ /** * Initializes internal fields. */ _initFields : function() { this._user = null; }, /** * Loads information about selected/active entities. */ start : function() { }, /** Closes this module. */ stop : function() { }, _http : function(url, method) { method = method || 'GET'; var client = Teleport.HttpClient.newInstance({ baseUrl : url }); return client.exec({ path : '', method : method }).then(function(json) { try { return _.isObject(json) ? json : JSON.parse(json); } catch (err) { return; } }); }, logout : function() { return this._http(this.app.options.logoutApiUrl).then(function(user) { return user; }); }, getUserInfo : function() { return this._http(this.app.options.userInfoApiUrl).then(function(user) { if (!user || !user.displayName) return; return user; }); }, });
Add Travis CI build number to Sauce Labs jobs
module.exports = function(config) { var commonConfig = (require("./karma-common.conf"))(config); var customLaunchers = { sl_chrome: { base: "SauceLabs", browserName: "chrome", platform: "Windows 8.1" }, //sl_firefox: { // base: "SauceLabs", // browserName: "firefox", // platform: "Windows 8.1" //}, sl_safari: { base: "SauceLabs", browserName: "safari", platform: "OS X 10.10" }, sl_ie_11: { base: "SauceLabs", browserName: "internet explorer", platform: "Windows 8.1" } }; var options = { reporters: ["verbose", "saucelabs"], sauceLabs: { build: process.env.TRAVIS_BUILD_NUMBER, testName: "Vivliostyle.js", recordScreenshots: false, startConnect: false, // Sauce Connect is started by Travis CI tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER }, captureTimeout: 120000, customLaunchers: customLaunchers, browsers: Object.keys(customLaunchers), singleRun: true }; for (var key in commonConfig) { if (commonConfig.hasOwnProperty(key)) { options[key] = commonConfig[key]; } } config.set(options); };
module.exports = function(config) { var commonConfig = (require("./karma-common.conf"))(config); var customLaunchers = { sl_chrome: { base: "SauceLabs", browserName: "chrome", platform: "Windows 8.1" }, //sl_firefox: { // base: "SauceLabs", // browserName: "firefox", // platform: "Windows 8.1" //}, sl_safari: { base: "SauceLabs", browserName: "safari", platform: "OS X 10.10" }, sl_ie_11: { base: "SauceLabs", browserName: "internet explorer", platform: "Windows 8.1" } }; var options = { reporters: ["verbose", "saucelabs"], sauceLabs: { testName: "Vivliostyle.js", recordScreenshots: false, startConnect: false, // Sauce Connect is started by Travis CI tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER }, captureTimeout: 120000, customLaunchers: customLaunchers, browsers: Object.keys(customLaunchers), singleRun: true }; for (var key in commonConfig) { if (commonConfig.hasOwnProperty(key)) { options[key] = commonConfig[key]; } } config.set(options); };
Add python-magic as a requirement for mime detection.
import os import sys from setuptools import setup with open("./pushbullet/__version__.py") as version_file: version = version_file.read().split("\"")[1] if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() def read(fname): try: with open(os.path.join(os.path.dirname(__file__), fname)) as f: return f.read() except IOError: return "" setup( name = "pushbullet.py", version = version, author = "Richard Borcsik", author_email = "[email protected]", description = ("A simple python client for pushbullet.com"), license = "MIT", keywords = "push android pushbullet notification", url = "https://github.com/randomchars/pushbullet.py", download_url="https://github.com/randomchars/pushbullet.py/tarball/" + version, packages=['pushbullet'], long_description=read('readme.md'), classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Programming Language :: Python", "Natural Language :: English", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.2", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Utilities" ], install_requires=[ 'requests>=1.0.0', 'python-magic', ] )
import os import sys from setuptools import setup with open("./pushbullet/__version__.py") as version_file: version = version_file.read().split("\"")[1] if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() def read(fname): try: with open(os.path.join(os.path.dirname(__file__), fname)) as f: return f.read() except IOError: return "" setup( name = "pushbullet.py", version = version, author = "Richard Borcsik", author_email = "[email protected]", description = ("A simple python client for pushbullet.com"), license = "MIT", keywords = "push android pushbullet notification", url = "https://github.com/randomchars/pushbullet.py", download_url="https://github.com/randomchars/pushbullet.py/tarball/" + version, packages=['pushbullet'], long_description=read('readme.md'), classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Programming Language :: Python", "Natural Language :: English", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.2", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Utilities" ], install_requires=[ 'requests>=1.0.0', ] )
Fix bogus identifier name throughout file
<?php namespace Quickshiftin\Assetorderer\View\Asset; use Magento\Framework\View\Asset\Remote as RemoteAsset, Magento\Framework\View\Asset\LocalInterface; class Remote implements LocalInterface { private $_iOrder = 1, $_oRealRemoteFile; public function __call($sMethod, array $aArgs=[]) { return call_user_func_array([$this->_oRealRemoteFile, $sMethod], $aArgs); } public function setRealRemoteFile(RemoteAsset $oRealRemoteFile) { $this->_oRealRemoteFile = $oRealRemoteFile; } public function getOrder() { return $this->_iOrder; } public function setOrder($iOrder) { $this->_iOrder = $iOrder; } // Boilerplate to implement interface ----------------------------------- // AssetInterface; public function getUrl() { return $this->_oRealRemoteFile->getUrl(); } public function getContentType() { return $this->_oRealRemoteFile->getContentType(); } public function getSourceContentType() { return $this->_oRealRemoteFile->getSourceContentType(); } // LocalInterface public function getSourceFile() { return $this->_oRealRemoteFile->getSourceFile(); } public function getContent() { return $this->_oRealRemoteFile->getContent(); } public function getFilePath() { return $this->_oRealRemoteFile->getFilePath(); } public function getContext() { return $this->_oRealRemoteFile->getContext(); } public function getModule() { return $this->_oRealRemoteFile->getModule(); } public function getPath() { return $this->_oRealRemoteFile->getPath(); } }
<?php namespace Quickshiftin\Assetorderer\View\Asset; use Magento\Framework\View\Asset\Remote as RemoteAsset, Magento\Framework\View\Asset\LocalInterface; class Remote implements LocalInterface { private $_iOrder = 1, $_oRealRemoteFile; public function __call($sMethod, array $aArgs=[]) { return call_user_func_array([$this->_oRealRemoteFile, $sMethod], $aArgs); } public function setRealRemoteFile(RemoteAsset $oRealRemoteFile) { $this->_oRealRemoteFile = $oRealRemoteFile; } public function getOrder() { return $this->_iOrder; } public function setOrder($iOrder) { $this->_iOrder = $iOrder; } // Boilerplate to implement interface ----------------------------------- // AssetInterface; public function getUrl() { return $this->_oRealFile->getUrl(); } public function getContentType() { return $this->_oRealFile->getContentType(); } public function getSourceContentType() { return $this->_oRealFile->getSourceContentType(); } // LocalInterface public function getSourceFile() { return $this->_oRealFile->getSourceFile(); } public function getContent() { return $this->_oRealFile->getContent(); } public function getFilePath() { return $this->_oRealFile->getFilePath(); } public function getContext() { return $this->_oRealFile->getContext(); } public function getModule() { return $this->_oRealFile->getModule(); } public function getPath() { return $this->_oRealFile->getPath(); } }
Fix bug - when clicking "Join" on a project - it now goes to the project's page.
Template.projectItem.helpers({ joinProject: function(projectId) { var projectOwnerOrMember = Projects.find({ $or: [{ 'owner.userId': Meteor.userId(), _id: projectId}, { members: { $elemMatch: { userId: Meteor.userId() } } } ] } ); return projectOwnerOrMember.count() === 0 && Meteor.userId(); }, isPending: function(projectId) { // console.log(Meteor.userId() + " " + projectId); //console.log(hasRequestPending(Meteor.userId(), projectId)); return hasRequestPending(Meteor.userId(), projectId); } }); Template.projectItem.events({ 'click .join-button': function(e) { e.preventDefault(); var that = this; var request = { user: { userId: Meteor.userId(), username: Meteor.user().username }, project: { name: this.name, projectId: this._id, ownerId: this.owner.userId } }; Meteor.call('addRequest', request, function (err, result) { if (err) { console.log(err.reason); } else { console.log(that._id); Router.go('projectPage', { _id: that._id } ); } }); }, 'click .project-name': function(e) { Router.go('projectPage', { _id: this._id } ); } });
Template.projectItem.helpers({ joinProject: function(projectId) { var projectOwnerOrMember = Projects.find({ $or: [{ 'owner.userId': Meteor.userId(), _id: projectId}, { members: { $elemMatch: { userId: Meteor.userId() } } } ] } ); return projectOwnerOrMember.count() === 0 && Meteor.userId(); }, isPending: function(projectId) { console.log(Meteor.userId() + " " + projectId); console.log(hasRequestPending(Meteor.userId(), projectId)); return hasRequestPending(Meteor.userId(), projectId); } }); Template.projectItem.events({ 'click .join-button': function(e) { e.preventDefault(); var request = { user: { userId: Meteor.userId(), username: Meteor.user().username }, project: { name: this.name, projectId: this._id, ownerId: this.owner.userId } }; Meteor.call('addRequest', request, function (err, result) { if (err) { console.log(err.reason); } else { Router.go('projectPage', { _id: this._id } ); } }); }, 'click .project-name': function(e) { Router.go('projectPage', { _id: this._id } ); } });
Fix trn to phn script
#!/usr/bin/env python3 import os import sys def main(langdat_dir, trn_file, phn_dir): phone_map = {v[0]: v[1].strip() for v in (l.split(None, 1) for l in open('{}/phones'.format(langdat_dir), encoding='utf-8'))} for line in open(trn_file): parts = line.split() sentence = parts[:-1] sid = parts[-1][1:-1] phn = open(os.path.join(phn_dir,sid+".phn"), "w", encoding="iso8859-15") print("0 0 __", file=phn) phones = '_' for word in sentence: for c in word: phones += phone_map[c] phones += '_' for j in range(1, len(phones)-1): if phones[j] == '_': print("0 0 _", file=phn) continue lci = j -1 while lci > 0 and phones[lci] == '_': lci -= 1 rci = j +1 while rci < len(phones) - 1 and phones[rci] == '_': rci += 1 print("0 0 {}-{}+{}".format(phones[lci], phones[j], phones[rci]), file=phn) print("0 0 __", file=phn) phn.close() if __name__ == "__main__": main(sys.argv[1], sys.argv[2], sys.argv[3])
#!/usr/bin/env python3 import os import sys def main(trn_file, phn_dir): phone_map = {v[0]: v[1].strip() for v in (l.split(None, 1) for l in open('data/phone_map', encoding='utf-8'))} for line in open(trn_file): parts = line.split() sentence = parts[:-1] sid = parts[-1][1:-1] phn = open(os.path.join(phn_dir,sid+".phn"), "w", encoding="iso8859-15") print("0 0 __", file=phn) phones = '_' for word in sentence: for c in word: phones += phone_map[c] phones += '_' for j in range(1, len(phones)-1): if phones[j] == '_': print("0 0 _", file=phn) continue lci = j -1 while lci > 0 and phones[lci] == '_': lci -= 1 rci = j +1 while rci < len(phones) - 1 and phones[rci] == '_': rci += 1 print("0 0 {}-{}+{}".format(phones[lci], phones[j], phones[rci]), file=phn) print("0 0 __", file=phn) phn.close() if __name__ == "__main__": main(sys.argv[1], sys.argv[2])
Add self to list of filtered users for editors Closes #4412
import AuthenticatedRoute from 'ghost/routes/authenticated'; import PaginationRouteMixin from 'ghost/mixins/pagination-route'; import styleBody from 'ghost/mixins/style-body'; var paginationSettings, UsersIndexRoute; paginationSettings = { page: 1, limit: 20, status: 'active' }; UsersIndexRoute = AuthenticatedRoute.extend(styleBody, PaginationRouteMixin, { classNames: ['settings-view-users'], setupController: function (controller, model) { this._super(controller, model); this.setupPagination(paginationSettings); }, model: function () { var self = this; return self.store.find('user', {limit: 'all', status: 'invited'}).then(function () { return self.store.find('user', 'me').then(function (currentUser) { if (currentUser.get('isEditor')) { // Editors only see authors in the list paginationSettings.role = 'Author'; } return self.store.filter('user', paginationSettings, function (user) { if (currentUser.get('isEditor')) { return user.get('isAuthor') || user === currentUser; } return true; }); }); }); }, actions: { reload: function () { this.refresh(); } } }); export default UsersIndexRoute;
import AuthenticatedRoute from 'ghost/routes/authenticated'; import PaginationRouteMixin from 'ghost/mixins/pagination-route'; import styleBody from 'ghost/mixins/style-body'; var paginationSettings, UsersIndexRoute; paginationSettings = { page: 1, limit: 20, status: 'active' }; UsersIndexRoute = AuthenticatedRoute.extend(styleBody, PaginationRouteMixin, { classNames: ['settings-view-users'], setupController: function (controller, model) { this._super(controller, model); this.setupPagination(paginationSettings); }, model: function () { var self = this; return self.store.find('user', {limit: 'all', status: 'invited'}).then(function () { return self.store.find('user', 'me').then(function (currentUser) { if (currentUser.get('isEditor')) { // Editors only see authors in the list paginationSettings.role = 'Author'; } return self.store.filter('user', paginationSettings, function (user) { if (currentUser.get('isEditor')) { return user.get('isAuthor'); } return true; }); }); }); }, actions: { reload: function () { this.refresh(); } } }); export default UsersIndexRoute;
Modify test to test for nested JSON
"""Tests for respite.middleware.""" from nose.tools import * from urllib import urlencode from django.utils import simplejson as json from django.test.client import Client, RequestFactory from respite.middleware import * client = Client() def test_json_middleware(): request = RequestFactory().post( path = '/', data = json.dumps({ 'foo': 'foo', 'bar': 'bar', 'baz': 'baz', 'hogera': [ {'hoge': 'hoge'}, {'fuga': 'fuga'} ] }), content_type = 'application/json' ) JsonMiddleware().process_request(request) assert_equal(request.POST, { 'foo': ['foo'], 'bar': ['bar'], 'baz': ['baz'], 'hogera': [ {'hoge': ['hoge']}, {'fuga': ['fuga']} ] }) def test_http_method_override_middleware(): request = RequestFactory().post( path = '/', data = { 'foo': 'bar', '_method': 'PUT' } ) HttpMethodOverrideMiddleware().process_request(request) assert_equal(request.method, 'PUT') assert_equal(request.POST, {}) def test_http_put_middleware(): request = RequestFactory().put( path = '/', data = urlencode({ 'foo': 'bar' }), content_type = "application/x-www-form-urlencoded" ) HttpPutMiddleware().process_request(request) assert_equal(request.PUT, { 'foo': ['bar'] })
"""Tests for respite.middleware.""" from nose.tools import * from urllib import urlencode from django.utils import simplejson as json from django.test.client import Client, RequestFactory from respite.middleware import * client = Client() def test_json_middleware(): request = RequestFactory().post( path = '/', data = json.dumps({ 'foo': 'foo', 'bar': 'bar', 'baz': 'baz' }), content_type = 'application/json' ) JsonMiddleware().process_request(request) assert_equal(request.POST, { 'foo': ['foo'], 'bar': ['bar'], 'baz': ['baz'] }) def test_http_method_override_middleware(): request = RequestFactory().post( path = '/', data = { 'foo': 'bar', '_method': 'PUT' } ) HttpMethodOverrideMiddleware().process_request(request) assert_equal(request.method, 'PUT') assert_equal(request.POST, {}) def test_http_put_middleware(): request = RequestFactory().put( path = '/', data = urlencode({ 'foo': 'bar' }), content_type = "application/x-www-form-urlencoded" ) HttpPutMiddleware().process_request(request) assert_equal(request.PUT, { 'foo': ['bar'] })
Add option to include specified tech(bemhtml, bh)
module.exports = function() { return this .title('Benchmarks') .helpful() .arg() .name('treeish-list') .title('List of revisions to compare (git treeish)') .arr() .end() .opt() .name('benchmarks') .short('b').long('benchmark') .arr() .title('List of benchmarks to run') .end() .opt() .name('no-wc') .short('w').long('no-wc') .flag() .title('Run benchmarks without using working copy, use only specified revisions') .end() .opt() .name('rerun') .long('rerun') .flag() .title('Reuse previously checked out and made revisions, run benchmarks only') .end() .opt() .name('techs') .long('techs') .short('t') .title('Tech to run testing') .arr() .end() .opt() .name('rme') .short('r').long('rme') .title('Delta for RME') .end() .opt() .name('delay') .short('d').long('delay') .title('Delay between benchmarks') .end() .act(function(opts,args) { return require('../bench')(opts, args).start(); }) .end(); };
module.exports = function() { return this .title('Benchmarks') .helpful() .arg() .name('treeish-list') .title('List of revisions to compare (git treeish)') .arr() .end() .opt() .name('benchmarks') .short('b').long('benchmark') .arr() .title('List of benchmarks to run') .end() .opt() .name('no-wc') .short('w').long('no-wc') .flag() .title('Run benchmarks without using working copy, use only specified revisions') .end() .opt() .name('rerun') .long('rerun') .flag() .title('Reuse previously checked out and made revisions, run benchmarks only') .end() .opt() .name('rme') .short('r').long('rme') .title('Delta for RME') .end() .opt() .name('delay') .short('d').long('delay') .title('Delay between benchmarks') .end() .act(function(opts,args) { return require('../bench')(opts, args).start(); }) .end(); };