text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Set dev email backend back to consol
# SECURITY WARNING: keep the secret key used in production secret! # You should change this key before you go live! DEBUG = True SECRET_KEY = 'uxprsdhk^gzd-r=_287byolxn)$k6tsd8_cepl^s^tms2w1qrv' # This is the default redirect if no other sites are found. DEFAULT_HOST = 'https://www.example.org' EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' URL_CONFIG = 'path' # path or domain MIDDLEWARE_CLASSES = ( 'utils.middleware.TimeMonitoring', 'debug_toolbar.middleware.DebugToolbarMiddleware' ) INSTALLED_APPS = ['debug_toolbar', 'django_nose'] def show_toolbar(request): return True DEBUG_TOOLBAR_CONFIG = { "SHOW_TOOLBAR_CALLBACK": show_toolbar, } TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
# SECURITY WARNING: keep the secret key used in production secret! # You should change this key before you go live! DEBUG = True SECRET_KEY = 'uxprsdhk^gzd-r=_287byolxn)$k6tsd8_cepl^s^tms2w1qrv' # This is the default redirect if no other sites are found. DEFAULT_HOST = 'https://www.example.org' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' URL_CONFIG = 'path' # path or domain MIDDLEWARE_CLASSES = ( 'utils.middleware.TimeMonitoring', 'debug_toolbar.middleware.DebugToolbarMiddleware' ) INSTALLED_APPS = ['debug_toolbar', 'django_nose'] def show_toolbar(request): return True DEBUG_TOOLBAR_CONFIG = { "SHOW_TOOLBAR_CALLBACK": show_toolbar, } TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
Add create and delete permissions to mysql user in wordpress example
#!/usr/bin/env python import sys import os import simplejson as json f = open("bootconf.json", "r") vals_dict = json.load(f) f.close() os.putenv('DEBIAN_FRONTEND', 'noninteractive') os.putenv('TERM', 'dumb') password=vals_dict['dbpassword'] dbname=vals_dict['dbname'] commands = [] commands.append('sudo -E apt-get -y -q install mysql-server-5.1') commands.append('sudo -E mysqladmin -u root password %s' % (password)) commands.append('sudo -E mysqladmin --password=%s create %s' % (password, dbname)) commands.append("sudo -E mysql --password=%s -e \"GRANT Select, Insert, Update, Create, Delete ON *.* TO 'root'@'%%' IDENTIFIED BY '%s';\"" % (password, password)) commands.append("sudo -E sed -i 's/bind-address.*/bind-address = 0.0.0.0/' /etc/mysql/my.cnf") commands.append("sudo -E restart mysql") for cmd in commands: print cmd rc = os.system(cmd) if rc != 0: print "ERROR! %d" % (rc) sys.exit(rc) print "SUCCESS" sys.exit(0)
#!/usr/bin/env python import sys import os import simplejson as json f = open("bootconf.json", "r") vals_dict = json.load(f) f.close() os.putenv('DEBIAN_FRONTEND', 'noninteractive') os.putenv('TERM', 'dumb') password=vals_dict['dbpassword'] dbname=vals_dict['dbname'] commands = [] commands.append('sudo -E apt-get -y -q install mysql-server-5.1') commands.append('sudo -E mysqladmin -u root password %s' % (password)) commands.append('sudo -E mysqladmin --password=%s create %s' % (password, dbname)) commands.append("sudo -E mysql --password=%s -e \"GRANT Select, Insert, Update ON *.* TO 'root'@'%%' IDENTIFIED BY '%s';\"" % (password, password)) commands.append("sudo -E sed -i 's/bind-address.*/bind-address = 0.0.0.0/' /etc/mysql/my.cnf") commands.append("sudo -E restart mysql") for cmd in commands: print cmd rc = os.system(cmd) if rc != 0: print "ERROR! %d" % (rc) sys.exit(rc) print "SUCCESS" sys.exit(0)
Update concatenation algorithm to prevent strings larger than the max length From https://github.com/ljharb/proposal-string-pad-left-right/commit/7b6261b9a23cbc00daf0b232c1b40243adcce7d8
'use strict'; var bind = require('function-bind'); var ES = require('es-abstract/es7'); var slice = bind.call(Function.call, String.prototype.slice); module.exports = function padRight(maxLength) { var O = ES.RequireObjectCoercible(this); var S = ES.ToString(O); var stringLength = ES.ToLength(S.length); var fillString; if (arguments.length > 1) { fillString = arguments[1]; } var F = typeof fillString === 'undefined' ? '' : ES.ToString(fillString); if (F === '') { F = ' '; } var intMaxLength = ES.ToLength(maxLength); if (intMaxLength <= stringLength) { return S; } var fillLen = intMaxLength - stringLength; while (F.length < fillLen) { var fLen = F.length; var remainingCodeUnits = fillLen - fLen; F += fLen > remainingCodeUnits ? slice(F, 0, remainingCodeUnits) : F; } var truncatedStringFiller = F.length > fillLen ? slice(F, 0, fillLen) : F; return S + truncatedStringFiller; };
'use strict'; var bind = require('function-bind'); var ES = require('es-abstract/es7'); var slice = bind.call(Function.call, String.prototype.slice); module.exports = function padRight(maxLength) { var O = ES.RequireObjectCoercible(this); var S = ES.ToString(O); var stringLength = ES.ToLength(S.length); var fillString; if (arguments.length > 1) { fillString = arguments[1]; } var F = typeof fillString === 'undefined' ? '' : ES.ToString(fillString); if (F === '') { F = ' '; } var intMaxLength = ES.ToLength(maxLength); if (intMaxLength <= stringLength) { return S; } var fillLen = intMaxLength - stringLength; while (F.length < fillLen) { F += F; } var truncatedStringFiller = F.length > fillLen ? slice(F, 0, fillLen) : F; return S + truncatedStringFiller; };
Fix fromEmisions filtering for completion cutoff
import React from 'react' import ObservableView from './view' import { isEmissionsArr } from '../../utils/isEmissionsArr' const selectValue = obj => obj.x function fromEmissions(arr, range, completion) { if (!isEmissionsArr(arr)) { throw new Error([ 'Expected each value in `emissions` to be an emission', '({ x: [number], d: [string] })' ].join('. ')) } const min = Math.min.apply(null, arr.map(selectValue)) const max = typeof range === 'number' ? range : Math.max.apply(null, arr.map(selectValue)) const emissions = arr .filter(({ x }) => x <= completion) .sort((a, b) => a.x - b.x) .map(({ x, ...rest }) => ({ ...rest, x: x / max })) return props => ( <ObservableView {...props} completion={completion ? Math.min(completion / max, 1) : 0} emissions={emissions} /> ) } export default fromEmissions
import React from 'react' import ObservableView from './view' import { isEmissionsArr } from '../../utils/isEmissionsArr' const selectValue = obj => obj.x function fromEmissions(arr, range, completion) { if (!isEmissionsArr(arr)) { throw new Error([ 'Expected each value in `emissions` to be an emission', '({ x: [number], d: [string] })' ].join('. ')) } const min = Math.min.apply(null, arr.map(selectValue)) const max = typeof range === 'number' ? range : Math.max.apply(null, arr.map(selectValue)) const emissions = arr .filter(({ x }) => x <= max) .sort((a, b) => a.x - b.x) .map(({ x, ...rest }) => ({ ...rest, x: x / max })) return props => ( <ObservableView {...props} completion={completion ? Math.min(completion / max, 1) : 0} emissions={emissions} /> ) } export default fromEmissions
Fix issue with component manager role and side menu.
define(function (require) { 'use strict'; var modules = require('modules'); var _ = require('lodash'); var alien4cloud = modules.get('alien4cloud'); // defines layout controller alien4cloud.controller('LayoutCtrl', ['$scope', 'menu', 'authService', 'context', function( $scope, menu, authService, context) { $scope.context = context; _.each(menu, function(menuItem) { menuItem.show = false; if (authService.hasRole('ADMIN')) { menuItem.show = true; } else if(_.has(menuItem, 'roles')) { _.every(menuItem.roles, function(role){ if (authService.hasRole(role)) { menuItem.show = true; return false; // stop the every loop } }); } else { // if there is no roles requirement or if it's an ADMIN then the menu is visible menuItem.show = true; } }); $scope.menu = menu; } ]); return alien4cloud; });
define(function (require) { 'use strict'; var modules = require('modules'); var _ = require('lodash'); var alien4cloud = modules.get('alien4cloud'); // defines layout controller alien4cloud.controller('LayoutCtrl', ['$scope', 'menu', 'authService', 'context', function( $scope, menu, authService, context) { $scope.context = context; _.each(menu, function(menuItem) { menuItem.show = false; if (authService.hasRole('ADMIN')) { menuItem.show = true; } else if(_.has(menuItem, 'roles')) { for (var role in menuItem.roles) { if (authService.hasRole(role)) { menuItem.show = true; break; } } } else { // if there is no roles requirement or if it's an ADMIN then the menu is visible menuItem.show = true; } }); $scope.menu = menu; } ]); return alien4cloud; });
Make sure that we are only processing messages that are of type request
'use strict'; var _ = require('lodash'); var glimpse = require('glimpse'); var processMessages = function(messages) { // NOTE: currently filtering out messages that aren't of type "request" messages = _.filter(messages, 'context.type', 'request'); return { messages: messages, groupedById: _.groupBy(messages, 'context.id') }; }; // republish Found Summary (function () { function republishFoundSummary(messages) { var payload = processMessages(messages); glimpse.emit('data.message.summary.found', payload); } glimpse.on('data.message.summary.found.stream', republishFoundSummary); glimpse.on('data.message.summary.found.remote', republishFoundSummary); })(); // republish Found Details (function () { function republishFoundDetail(messages) { var payload = processMessages(messages); glimpse.emit('data.message.detail.found', payload); } glimpse.on('data.message.detail.found.stream', republishFoundDetail); glimpse.on('data.message.detail.found.remote', republishFoundDetail); })();
'use strict'; var _ = require('lodash'); var glimpse = require('glimpse'); var processMessages = function(messages) { return { messages: messages, groupedById: _.groupBy(messages, 'context.id') }; }; // republish Found Summary (function () { function republishFoundSummary(messages) { var payload = processMessages(messages); glimpse.emit('data.message.summary.found', payload); } glimpse.on('data.message.summary.found.stream', republishFoundSummary); glimpse.on('data.message.summary.found.remote', republishFoundSummary); })(); // republish Found Details (function () { function republishFoundDetail(messages) { var payload = processMessages(messages); glimpse.emit('data.message.detail.found', payload); } glimpse.on('data.message.detail.found.stream', republishFoundDetail); glimpse.on('data.message.detail.found.remote', republishFoundDetail); })();
Make class final to meet PMD rule: ClassWithOnlyPrivateConstructorsShouldBeFinal See pmd.sourceforge.net/rules/design.html#ClassWithOnlyPrivateConstructorsShouldBeFinal
package net.folab.entitybrowser; /** * Controls models & views. This is responsible to C from MVC pattern. This * class is singleton. * * @author leafriend */ public final class Controller { /** * Instance of this class. This is a part of singleton pattern. */ private static final Controller INSTANCE = new Controller(); /** * Returns instance of this class. This is a part of singleton pattern. * * @return instance of this class. It's always same instance. */ public synchronized static Controller getInstance() { return INSTANCE; } /** * Access modifier is set to <code>private</code> to restrict instantiation * from outside of class. This is a part of singleton pattern. */ private Controller() { // DO NOTHING } }
package net.folab.entitybrowser; /** * Controls models & views. This is responsible to C from MVC pattern. This * class is singleton. * * @author leafriend */ public class Controller { /** * Instance of this class. This is a part of singleton pattern. */ private static final Controller INSTANCE = new Controller(); /** * Returns instance of this class. This is a part of singleton pattern. * * @return instance of this class. It's always same instance. */ public synchronized static Controller getInstance() { return INSTANCE; } /** * Access modifier is set to <code>private</code> to restrict instantiation * from outside of class. This is a part of singleton pattern. */ private Controller() { // DO NOTHING } }
Revert "[5.1] Add new middleware"
<?php namespace App\Http; use Illuminate\Foundation\Http\Kernel as HttpKernel; class Kernel extends HttpKernel { /** * The application's global HTTP middleware stack. * * @var array */ protected $middleware = [ 'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode', 'Illuminate\Cookie\Middleware\EncryptCookies', 'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse', 'Illuminate\Session\Middleware\StartSession', 'Illuminate\View\Middleware\ShareErrorsFromSession', 'App\Http\Middleware\VerifyCsrfToken', ]; /** * The application's route middleware. * * @var array */ protected $routeMiddleware = [ 'auth' => 'App\Http\Middleware\Authenticate', 'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth', 'guest' => 'App\Http\Middleware\RedirectIfAuthenticated', ]; }
<?php namespace App\Http; use Illuminate\Foundation\Http\Kernel as HttpKernel; class Kernel extends HttpKernel { /** * The application's global HTTP middleware stack. * * @var array */ protected $middleware = [ 'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode', 'Illuminate\Foundation\Http\Middleware\VerifyPostSize', 'Illuminate\Cookie\Middleware\EncryptCookies', 'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse', 'Illuminate\Session\Middleware\StartSession', 'Illuminate\View\Middleware\ShareErrorsFromSession', 'App\Http\Middleware\VerifyCsrfToken', ]; /** * The application's route middleware. * * @var array */ protected $routeMiddleware = [ 'auth' => 'App\Http\Middleware\Authenticate', 'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth', 'guest' => 'App\Http\Middleware\RedirectIfAuthenticated', ]; }
Add regex to know if one field is use in a model where this field is not declared
"""Analyse the tests log file given as argument. Print a report and return status code 1 if failures are detected """ import sys import re FAILURE_REGEXPS = { 'Failure in Python block': re.compile(r'WARNING:tests[.].*AssertionError'), 'Errors during x/yml tests': re.compile(r'ERROR:tests[.]'), 'Errors or failures during unittest2 tests': re.compile( r'at least one error occurred in a test'), 'Errors loading addons': re.compile(r'ERROR.*openerp: Failed to load'), 'Critical logs': re.compile(r'CRITICAL'), 'Error init db': re.compile(r'Failed to initialize database'), 'Tests failed to excute': re.compile( r'openerp.modules.loading: Tests failed to execute'), 'WARNING no field in model': re.compile('No such field(s) in model'), } test_log = open(sys.argv[1], 'r') failures = {} # label -> extracted line for line in test_log.readlines(): for label, regexp in FAILURE_REGEXPS.items(): if regexp.search(line): failures.setdefault(label, []).append(line) if not failures: print "No failure detected" sys.exit(0) total = 0 print 'FAILURES DETECTED' print for label, failed_lines in failures.items(): print label + ':' for line in failed_lines: print ' ' + line print total += len(failed_lines) print "Total: %d failures " % total sys.exit(1)
"""Analyse the tests log file given as argument. Print a report and return status code 1 if failures are detected """ import sys import re FAILURE_REGEXPS = { 'Failure in Python block': re.compile(r'WARNING:tests[.].*AssertionError'), 'Errors during x/yml tests': re.compile(r'ERROR:tests[.]'), 'Errors or failures during unittest2 tests': re.compile( r'at least one error occurred in a test'), 'Errors loading addons': re.compile(r'ERROR.*openerp: Failed to load'), 'Critical logs': re.compile(r'CRITICAL'), 'Error init db': re.compile(r'Failed to initialize database'), 'Tests failed to excute': re.compile( r'openerp.modules.loading: Tests failed to execute'), } test_log = open(sys.argv[1], 'r') failures = {} # label -> extracted line for line in test_log.readlines(): for label, regexp in FAILURE_REGEXPS.items(): if regexp.search(line): failures.setdefault(label, []).append(line) if not failures: print "No failure detected" sys.exit(0) total = 0 print 'FAILURES DETECTED' print for label, failed_lines in failures.items(): print label + ':' for line in failed_lines: print ' ' + line print total += len(failed_lines) print "Total: %d failures " % total sys.exit(1)
Change command result receive part
var express = require('express'), router = express.Router(), net = require('net'), fs = require('fs'), socketPath = '/tmp/haproxy'; /* GET home page. */ router.post('/', function(req, res) { // console.log(req.body); // you can get commit information from request body var client = net.createConnection(socketPath); client.on('connect', function () { client.write('show health'); client.on('data', function (data) { winston.debug('DATA: '+data); }); }); /* fs.stat(socketPath, function (err) { if (!err) { fs.unlinkSync(socketPath); return; } var unixServer = net.createServer(function (sock) { sock.write('show health'); sock.on('data', function (data) { winston.debug('DATA: '+data); sock.destroy(); }); }).listen(socketPath); }); */ res.send('complete'); }); module.exports = router;
var express = require('express'), router = express.Router(), net = require('net'), fs = require('fs'), socketPath = '/tmp/haproxy'; /* GET home page. */ router.post('/', function(req, res) { // console.log(req.body); // you can get commit information from request body var client = net.createConnection(socketPath); client.on('connect', function () { client.write('show health'); }); client.on('data', function (data) { winston.debug('DATA: '+data); }); /* fs.stat(socketPath, function (err) { if (!err) { fs.unlinkSync(socketPath); return; } var unixServer = net.createServer(function (sock) { sock.write('show health'); sock.on('data', function (data) { winston.debug('DATA: '+data); sock.destroy(); }); }).listen(socketPath); }); */ res.send('complete'); }); module.exports = router;
Set subscription to both for colorful avatars
<?php namespace OCA\OJSXC\Db; use Sabre\Xml\Reader; use Sabre\Xml\Writer; use Sabre\Xml\XmlDeserializable; use Sabre\Xml\XmlSerializable; /** * This is an entity used by the IqHandler, but not stored/mapped in the database. * Class IQRoster * * @package OCA\OJSXC\Db */ class IQRoster extends Stanza implements XmlSerializable{ public $type; public $qid; public $items; public function xmlSerialize(Writer $writer) { $writer->write([ [ 'name' => 'iq', 'attributes' => [ 'to' => $this->to, 'type' => $this->type, 'id' => $this->qid ], 'value' => [[ 'name' => 'query', 'attributes' => [ 'xmlns' => 'jabber:iq:roster', ], 'value' => $this->items ]] ] ]); } public function addItem($jid, $name){ $this->items[] = [ "name" => "item", "attributes" => [ "jid" => $jid, "name" => $name, "subscription" => "both" ], "value" => '' ]; } }
<?php namespace OCA\OJSXC\Db; use Sabre\Xml\Reader; use Sabre\Xml\Writer; use Sabre\Xml\XmlDeserializable; use Sabre\Xml\XmlSerializable; /** * This is an entity used by the IqHandler, but not stored/mapped in the database. * Class IQRoster * * @package OCA\OJSXC\Db */ class IQRoster extends Stanza implements XmlSerializable{ public $type; public $qid; public $items; public function xmlSerialize(Writer $writer) { $writer->write([ [ 'name' => 'iq', 'attributes' => [ 'to' => $this->to, 'type' => $this->type, 'id' => $this->qid ], 'value' => [[ 'name' => 'query', 'attributes' => [ 'xmlns' => 'jabber:iq:roster', ], 'value' => $this->items ]] ] ]); } public function addItem($jid, $name){ $this->items[] = [ "name" => "item", "attributes" => [ "jid" => $jid, "name" => $name ], "value" => '' ]; } }
Update Flame Leviathan to use draw script
from ..utils import * ## # Minions # Snowchugger class GVG_002: events = Damage().on( lambda self, target, amount, source: source is self and Freeze(target) ) # Goblin Blastmage class GVG_004: play = Find(FRIENDLY_MINIONS + MECH) & Hit(RANDOM_ENEMY_CHARACTER, 1) * 4 # Flame Leviathan class GVG_007: draw = Hit(ALL_CHARACTERS, 2) # Illuminator class GVG_089: events = OWN_TURN_END.on(Find(FRIENDLY_SECRETS) & Heal(FRIENDLY_HERO, 4)) ## # Spells # Flamecannon class GVG_001: play = Hit(RANDOM_ENEMY_MINION, 4) # Unstable Portal class GVG_003: play = Buff(Give(CONTROLLER, RandomMinion()), "GVG_003e") # Echo of Medivh class GVG_005: play = Give(CONTROLLER, Copy(FRIENDLY_MINIONS))
from ..utils import * ## # Minions # Snowchugger class GVG_002: events = Damage().on( lambda self, target, amount, source: source is self and Freeze(target) ) # Goblin Blastmage class GVG_004: play = Find(FRIENDLY_MINIONS + MECH) & Hit(RANDOM_ENEMY_CHARACTER, 1) * 4 # Flame Leviathan class GVG_007: in_hand = Draw(CONTROLLER, SELF).on(Hit(ALL_CHARACTERS, 2)) # Illuminator class GVG_089: events = OWN_TURN_END.on(Find(FRIENDLY_SECRETS) & Heal(FRIENDLY_HERO, 4)) ## # Spells # Flamecannon class GVG_001: play = Hit(RANDOM_ENEMY_MINION, 4) # Unstable Portal class GVG_003: play = Buff(Give(CONTROLLER, RandomMinion()), "GVG_003e") # Echo of Medivh class GVG_005: play = Give(CONTROLLER, Copy(FRIENDLY_MINIONS))
Make sure the task fails whenever an error is found in any file and not only the last one
/* * grunt-puglint * https://github.com/mrmlnc/grunt-puglint */ 'use strict'; var PugLint = require('pug-lint'); var linter = new PugLint(); var formatter = require('../lib/formatter'); module.exports = function(grunt) { grunt.registerMultiTask('puglint', 'Grunt plugin for pug-lint', function () { var done = this.async(); var options = this.options({ preset: 'clock' }); if (typeof options.preset === 'object') { options = options.preset; } var pugLintRc = options.puglintrc; if (pugLintRc) { if (grunt.file.exists(pugLintRc)) { options = grunt.file.readJSON(pugLintRc); } else { grunt.log.error('Configuration file not found. Used a standard config: `clock`.'); } } linter.configure(options); if (this.filesSrc.length === 0) { done(); return; } var errors = []; var failed = false; this.filesSrc.forEach(function(filepath) { errors = linter.checkFile(filepath); if (errors.length) { failed = true; formatter.formatOutput(errors); } }); done(!failed); }); };
/* * grunt-puglint * https://github.com/mrmlnc/grunt-puglint */ 'use strict'; var PugLint = require('pug-lint'); var linter = new PugLint(); var formatter = require('../lib/formatter'); module.exports = function(grunt) { grunt.registerMultiTask('puglint', 'Grunt plugin for pug-lint', function () { var done = this.async(); var options = this.options({ preset: 'clock' }); if (typeof options.preset === 'object') { options = options.preset; } var pugLintRc = options.puglintrc; if (pugLintRc) { if (grunt.file.exists(pugLintRc)) { options = grunt.file.readJSON(pugLintRc); } else { grunt.log.error('Configuration file not found. Used a standard config: `clock`.'); } } linter.configure(options); if (this.filesSrc.length === 0) { done(); return; } var errors = []; this.filesSrc.forEach(function(filepath) { errors = linter.checkFile(filepath); if (errors.length) { formatter.formatOutput(errors); } }); done(errors.length === 0); }); };
Use Go logger instead of fmt print methods
package main import ( "encoding/json" "io" "log" "net/http" "time" ) type AliveRequest struct { DeviceID string `json:"device_id"` Timeout int32 `json:"timeout"` } type DeviceTimer struct { DeviceID string DeviceTimer *time.Timer DeviceTimeout int32 } var timers_map = make(map[string]DeviceTimer) func handleAlivePost(rw http.ResponseWriter, request *http.Request) { aliverequest := parseAlivePost(request.Body) log.Printf("DeviceID: %s, Timeout: %d\n", aliverequest.DeviceID, aliverequest.Timeout) } func parseAlivePost(body io.ReadCloser) AliveRequest { aliverequest_decoder := json.NewDecoder(body) var aliverequest AliveRequest err_aliverequest := aliverequest_decoder.Decode(&aliverequest) if err_aliverequest != nil { log.Fatalf("Error decoding aliverequest: %s", err_aliverequest) } return aliverequest } func main() { log.Println("Starting AliveIM service...") http.HandleFunc("/", handleAlivePost) http.ListenAndServe("localhost:5000", nil) }
package main import ( "encoding/json" "fmt" "io" "log" "net/http" "time" ) type AliveRequest struct { DeviceID string `json:"device_id"` Timeout int32 `json:"timeout"` } type DeviceTimer struct { DeviceID string DeviceTimer *time.Timer DeviceTimeout int32 } var timers_map = make(map[string]DeviceTimer) func handleAlivePost(rw http.ResponseWriter, request *http.Request) { aliverequest := parseAlivePost(request.Body) fmt.Printf("DeviceID: %s, Timeout: %d", aliverequest.DeviceID, aliverequest.Timeout) } func parseAlivePost(body io.ReadCloser) AliveRequest { aliverequest_decoder := json.NewDecoder(body) var aliverequest AliveRequest err_aliverequest := aliverequest_decoder.Decode(&aliverequest) if err_aliverequest != nil { log.Fatalf("Error decoding aliverequest: %s", err_aliverequest) } return aliverequest } func main() { fmt.Println("Starting AliveIM service...") http.HandleFunc("/", handleAlivePost) http.ListenAndServe("localhost:5000", nil) }
Add version. Note this will cause the file to be modified in your working copy. This change is gitignored
#!/usr/bin/env python2 # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import version import AMTDevice import AMTBoot import AMTPower import AMTKVM import AMTOptIn import AMTRedirection AMTDevice = AMTDevice.AMTDevice AMTBoot = AMTBoot.AMTBoot AMTPower = AMTPower.AMTPower AMTKVM = AMTKVM.AMTKVM AMTOptin = AMTOptIn.AMTOptIn AMTRedirection = AMTRedirection.AMTRedirection # For backwards compatibility device = { 'AMTDevice': AMTDevice, 'AMTBoot': AMTBoot, 'AMTPower': AMTPower, 'AMTKVM': AMTKVM, 'AMTOptIn': AMTOptIn, 'AMTRedirection': AMTRedirection, } __all__ = [AMTDevice, AMTBoot, AMTPower, AMTKVM, AMTOptIn, AMTRedirection]
#!/usr/bin/env python2 # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import AMTDevice import AMTBoot import AMTPower import AMTKVM import AMTOptIn import AMTRedirection AMTDevice = AMTDevice.AMTDevice AMTBoot = AMTBoot.AMTBoot AMTPower = AMTPower.AMTPower AMTKVM = AMTKVM.AMTKVM AMTOptin = AMTOptIn.AMTOptIn AMTRedirection = AMTRedirection.AMTRedirection # For backwards compatibility device = { 'AMTDevice': AMTDevice, 'AMTBoot': AMTBoot, 'AMTPower': AMTPower, 'AMTKVM': AMTKVM, 'AMTOptIn': AMTOptIn, 'AMTRedirection': AMTRedirection, } __all__ = [AMTDevice, AMTBoot, AMTPower, AMTKVM, AMTOptIn, AMTRedirection]
Exclude secure false from example
<?php /* * Include the composer autoload file. */ include('../vendor/autoload.php'); /* * Load in the configuration information. * Make sure to replace the keys with your own. */ $configuration = new \Ziftr\ApiClient\Configuration(); $configuration->load_from_array(array( 'host' => 'sandbox.fpa.bz', 'port' => 443, 'private_key' => '...', 'publishable_key' => '...' )); /* * Create a new order request. */ $order = new \Ziftr\ApiClient\Request('/orders/', $configuration); try { /* * POST the request with the order data. * See the documentation for possible fields. */ $order = $order->post( array( 'order' => array( 'currency_code' => 'USD', 'is_shipping_required' => true ) ) ); print_r($order->getResponse()); /* * Create a new request object for the items endpoint. * This method is preffered to creating a URL directly. */ $itemsReq = $order->linkRequest('items'); /* * Add an order item. */ $itemsReq->post(array( 'order_item' => array( 'name' => 'Test Item', 'price' => 100, 'quantity' => 1, 'currency_code' => 'USD' ) )); print_r($itemsReq->getResponse()); } catch( Exception $e ) { }
<?php /* * Include the composer autoload file. */ include('../vendor/autoload.php'); /* * Load in the configuration information. * Make sure to replace the keys with your own. */ $configuration = new \Ziftr\ApiClient\Configuration(); $configuration->load_from_array(array( 'host' => 'sandbox.fpa.bz', 'port' => 443, 'private_key' => '...', 'publishable_key' => '...' )); /* * Create a new order request. */ $order = new \Ziftr\ApiClient\Request('/orders/', $configuration, false); try { /* * POST the request with the order data. * See the documentation for possible fields. */ $order = $order->post( array( 'order' => array( 'currency_code' => 'USD', 'is_shipping_required' => true ) ) ); print_r($order->getResponse()); /* * Create a new request object for the items endpoint. * This method is preffered to creating a URL directly. */ $itemsReq = $order->linkRequest('items'); /* * Add an order item. */ $itemsReq->post(array( 'order_item' => array( 'name' => 'Test Item', 'price' => 100, 'quantity' => 1, 'currency_code' => 'USD' ) )); print_r($itemsReq->getResponse()); } catch( Exception $e ) { }
Use browser agnostic stop propagation of events
/* ================================================================================================== Lowland - JavaScript low level functions Copyright (C) 2012 Sebatian Fastner ================================================================================================== */ /** * #require(ext.sugar.Object) */ (function(window) { var hasPostMessage = !!window.postMessage; var slice = Array.prototype.slice; var timeouts = []; var messageName = "$$lowland-zero-timeout-message"; var handleMessage = function(event) { if (event.source == window && event.data == messageName) { lowland.bom.Events.stopPropagation(event); if (timeouts.length > 0) { var timeout = timeouts.shift(); timeout[0].apply(timeout[1], timeout[2]); } } }; lowland.bom.Events.set(window, "message", handleMessage, true); core.Main.addMembers("Function", { delay : function(time, context) { var func = this; return setTimeout(function(context, args) { func.apply(context, args); }, time, context, slice.call(arguments, 2)); }, /** * Based upon work of http://dbaron.org/log/20100309-faster-timeouts */ lazy : function(context) { context = context || this; //timeouts.push([func, slice.call(arguments,1)]); timeouts.push([this, context, slice.call(arguments,1)]); postMessage(messageName, "*"); } }); })(window);
/* ================================================================================================== Lowland - JavaScript low level functions Copyright (C) 2012 Sebatian Fastner ================================================================================================== */ /** * #require(ext.sugar.Object) */ (function(window) { var hasPostMessage = !!window.postMessage; var slice = Array.prototype.slice; var timeouts = []; var messageName = "$$lowland-zero-timeout-message"; var handleMessage = function(event) { if (event.source == window && event.data == messageName) { event.stopPropagation(); if (timeouts.length > 0) { var timeout = timeouts.shift(); timeout[0].apply(timeout[1], timeout[2]); } } }; lowland.bom.Events.set(window, "message", handleMessage, true); core.Main.addMembers("Function", { delay : function(time, context) { var func = this; return setTimeout(function(context, args) { func.apply(context, args); }, time, context, slice.call(arguments, 2)); }, /** * Based upon work of http://dbaron.org/log/20100309-faster-timeouts */ lazy : function(context) { context = context || this; //timeouts.push([func, slice.call(arguments,1)]); timeouts.push([this, context, slice.call(arguments,1)]); postMessage(messageName, "*"); } }); })(window);
Use junctions instead of dir linking for windows
var rimraf = require("rimraf"); var async = require("async"); var path = require("path"); var fs = require("fs"); function symlinkDep(src, dest, callback) { fs.symlink(src, dest, "junction", callback); } function createLinkedDep(src, dest, name, callback) { rimraf(dest, function (err) { if (err) return callback(err); symlinkDep(src, dest, callback); }); } module.exports = function linkDependenciesForPackage( pkg, packages, packagesLoc, nodeModulesLoc, currentVersion, callback ) { async.each(packages, function (sub, done) { var ver = false; if (pkg.dependencies) ver = pkg.dependencies[sub.name]; if (pkg.devDependencies && !ver) ver = pkg.devDependencies[sub.name]; if (!ver) return done(); // ensure that this is referring to a local package if (ver[0] !== "^" || ver[1] !== currentVersion[0]) return done(); var linkSrc = path.join(packagesLoc, sub.folder); var linkDest = path.join(nodeModulesLoc, sub.name); createLinkedDep(linkSrc, linkDest, sub.name, done); }, callback); }
var rimraf = require("rimraf"); var async = require("async"); var path = require("path"); var fs = require("fs"); function symlinkDep(src, dest, callback) { fs.symlink(src, dest, "dir", callback); } function createLinkedDep(src, dest, name, callback) { rimraf(dest, function (err) { if (err) return callback(err); symlinkDep(src, dest, callback); }); } module.exports = function linkDependenciesForPackage( pkg, packages, packagesLoc, nodeModulesLoc, currentVersion, callback ) { async.each(packages, function (sub, done) { var ver = false; if (pkg.dependencies) ver = pkg.dependencies[sub.name]; if (pkg.devDependencies && !ver) ver = pkg.devDependencies[sub.name]; if (!ver) return done(); // ensure that this is referring to a local package if (ver[0] !== "^" || ver[1] !== currentVersion[0]) return done(); var linkSrc = path.join(packagesLoc, sub.folder); var linkDest = path.join(nodeModulesLoc, sub.name); createLinkedDep(linkSrc, linkDest, sub.name, done); }, callback); }
Add form for /attack with victim id
from django.forms import ModelForm from breach.models import Target, Victim class TargetForm(ModelForm): class Meta: model = Target fields = ( 'name', 'endpoint', 'prefix', 'alphabet', 'secretlength', 'alignmentalphabet', 'recordscardinality', 'method' ) class VictimForm(ModelForm): class Meta: model = Victim fields = ( 'sourceip', ) class AttackForm(ModelForm): class Meta: model = Victim fields = ( 'id', )
from django.forms import ModelForm from breach.models import Target, Victim class TargetForm(ModelForm): class Meta: model = Target fields = ( 'name', 'endpoint', 'prefix', 'alphabet', 'secretlength', 'alignmentalphabet', 'recordscardinality', 'method' ) class VictimForm(ModelForm): class Meta: model = Victim fields = ( 'sourceip', )
Fix path to test file.
""" Run this file to check your python installation. """ from os.path import dirname, join HERE = dirname(__file__) def test_import_pandas(): import pandas def test_pandas_version(): import pandas version_found = pandas.__version__.split(".") version_found = tuple(int(num) for num in version_found) assert version_found > (0, 15) def test_import_numpy(): import numpy def test_import_matplotlib(): import matplotlib.pyplot as plt plt.figure plt.plot plt.legend plt.imshow def test_import_statsmodels(): import statsmodels as sm from statsmodels.formula.api import ols from statsmodels.tsa.ar_model import AR def test_read_html(): import pandas pandas.read_html(join(HERE, "climate_timeseries", "data", "sea_levels", "Obtaining Tide Gauge Data.html")) def test_scrape_web(): import pandas as pd pd.read_html("http://en.wikipedia.org/wiki/World_population") if __name__ == "__main__": import nose nose.run(defaultTest=__name__)
""" Run this file to check your python installation. """ from os.path import dirname, join HERE = dirname(__file__) def test_import_pandas(): import pandas def test_pandas_version(): import pandas version_found = pandas.__version__.split(".") version_found = tuple(int(num) for num in version_found) assert version_found > (0, 15) def test_import_numpy(): import numpy def test_import_matplotlib(): import matplotlib.pyplot as plt plt.figure plt.plot plt.legend plt.imshow def test_import_statsmodels(): import statsmodels as sm from statsmodels.formula.api import ols from statsmodels.tsa.ar_model import AR def test_read_html(): import pandas pandas.read_html(join(HERE, "demos", "climate_timeseries", "data", "sea_levels", "Obtaining Tide Gauge Data.html")) def test_scrape_web(): import pandas as pd pd.read_html("http://en.wikipedia.org/wiki/World_population") if __name__ == "__main__": import nose nose.run(defaultTest=__name__)
Fix a stupid bug where gain read the value for the channel, not the sample
/** * @depends ../core/AudioletNode.js */ var Gain = new Class({ Extends: AudioletNode, initialize: function(audiolet, gain) { AudioletNode.prototype.initialize.apply(this, [audiolet, 2, 1]); this.outputs[0].link(this.inputs[0]); this.gain = new AudioletParameter(this, 1, gain || 1); }, generate: function(inputBuffers, outputBuffers) { var inputBuffer = inputBuffers[0]; var outputBuffer = outputBuffers[0]; if (inputBuffer.isEmpty) { outputBuffer.isEmpty = true; return; } // Local processing variables var gain = this.gain; var numberOfChannels = inputBuffer.numberOfChannels; for (var i = 0; i < numberOfChannels; i++) { var inputChannel = inputBuffer.getChannelData(i); var outputChannel = outputBuffer.getChannelData(i); var bufferLength = inputBuffer.length; for (var j = 0; j < bufferLength; j++) { outputChannel[j] = inputChannel[j] * gain.getValue(j); } } } });
/** * @depends ../core/AudioletNode.js */ var Gain = new Class({ Extends: AudioletNode, initialize: function(audiolet, gain) { AudioletNode.prototype.initialize.apply(this, [audiolet, 2, 1]); this.outputs[0].link(this.inputs[0]); this.gain = new AudioletParameter(this, 1, gain || 1); }, generate: function(inputBuffers, outputBuffers) { var inputBuffer = inputBuffers[0]; var outputBuffer = outputBuffers[0]; if (inputBuffer.isEmpty) { outputBuffer.isEmpty = true; return; } // Local processing variables var gain = this.gain; var numberOfChannels = inputBuffer.numberOfChannels; for (var i = 0; i < numberOfChannels; i++) { var inputChannel = inputBuffer.getChannelData(i); var outputChannel = outputBuffer.getChannelData(i); var bufferLength = inputBuffer.length; for (var j = 0; j < bufferLength; j++) { outputChannel[j] = inputChannel[j] * gain.getValue(i); } } } });
Remove firmware version as it's not provided
import { make } from 'vuex-pathify' import { version } from '../../package.json' const state = { version: '', platform: 'all', // either 'android', 'ios', or 'all' hardware: 'basalt', appVersion: '', inApp: false, devMode: false } export default { namespaced: true, state: state, mutations: { ...make.mutations(state), INIT (state) { if (localStorage.getItem('rebbleUserParameters')) { let cacheState = JSON.parse(localStorage.getItem('rebbleUserParameters')) if (cacheState.version === version) { Object.assign(state, cacheState) } else { state.version = version } } else { state.version = version } } } }
import { make } from 'vuex-pathify' import { version } from '../../package.json' const state = { version: '', platform: 'all', // either 'android', 'ios', or 'all' hardware: 'basalt', firmwareVersion: '', appVersion: '', inApp: false, devMode: false } export default { namespaced: true, state: state, mutations: { ...make.mutations(state), INIT (state) { if (localStorage.getItem('rebbleUserParameters')) { let cacheState = JSON.parse(localStorage.getItem('rebbleUserParameters')) if (cacheState.version === version) { Object.assign(state, cacheState) } else { state.version = version } } else { state.version = version } } } }
Add "Loading..." text to editor window.
function browseSuccess(r, stat, jqXHR) { $('#editor-panel').html(r); $('.igt-panel').each(function(index, elem) { $(elem).panel({ title: 'Instance '+$(elem).attr('id') }); }); $('.button').button(); } function browseError(r, stat, jqXHR) { $('#editor-panel').text("An error occurred."); } function browseToPage(val, page) { $('#editor-panel').text("Loading..."); $.ajax({ url: 'browse/'+val+'?page='+page, success: browseSuccess, error: browseError, dataType: "text" }) } function browseTo(rowIndex, rowData) { browseToPage(rowData['value'], 0); }
function browseSuccess(r, stat, jqXHR) { $('#editor-panel').html(r); $('.igt-panel').each(function(index, elem) { $(elem).panel({ title: 'Instance '+$(elem).attr('id') }); }); $('.button').button(); } function browseError(r, stat, jqXHR) { $('#editor-panel').text("An error occurred."); } function browseToPage(val, page) { $.ajax({ url: 'browse/'+val+'?page='+page, success: browseSuccess, error: browseError, dataType: "text" }) } function browseTo(rowIndex, rowData) { browseToPage(rowData['value'], 0); }
Fix test that checks queues
import yaml from app.config import QueueNames def test_queue_names_set_in_manifest_delivery_base_correctly(): with open("manifest-delivery-base.yml", 'r') as stream: search = ' -Q ' yml_commands = [y['command'] for y in yaml.load(stream)['applications']] watched_queues = set() for command in yml_commands: start_of_queue_arg = command.find(search) if start_of_queue_arg > 0: start_of_queue_names = start_of_queue_arg + len(search) queues = command[start_of_queue_names:].split(',') for q in queues: if "2>" in q: q = q.split("2>")[0].strip() watched_queues.add(q) # ses-callbacks isn't used in api (only used in SNS lambda) ignored_queues = {'ses-callbacks'} watched_queues -= ignored_queues assert watched_queues == set(QueueNames.all_queues())
import yaml from app.config import QueueNames def test_queue_names_set_in_manifest_delivery_base_correctly(): with open("manifest-delivery-base.yml", 'r') as stream: search = ' -Q ' yml_commands = [y['command'] for y in yaml.load(stream)['applications']] watched_queues = set() for command in yml_commands: start_of_queue_arg = command.find(search) if start_of_queue_arg > 0: start_of_queue_names = start_of_queue_arg + len(search) queues = command[start_of_queue_names:].split(',') watched_queues.update(queues) # ses-callbacks isn't used in api (only used in SNS lambda) ignored_queues = {'ses-callbacks'} watched_queues -= ignored_queues assert watched_queues == set(QueueNames.all_queues())
Print welcome message when IRC connects
'use strict'; const irc = require('irc'); const server = process.env.IRC_SERVER; const user = process.env.IRC_USER; const channel = process.env.IRC_CHANNEL; const client = module.exports.client = new irc.Client(server, user, { channels: [channel], }); if (process.env.NODE_ENV !== 'testing') { client.on('registered', function(message) { console.log(new Date(), '[IRC]', message.args[1]); }); } client.on('error', function(error) { console.error(error); console.error('Shutting Down...'); process.exit(1); }); module.exports.post = function(nodes, callback) { nodes.forEach(function(node) { // let name = `[${node.name}](${jenkins}/computer/${node.name})`; if (node.offline) { client.say(channel, `Jenkins slave ${node.name} is offline`); } else { client.say(channel, `Jenkins slave ${node.name} is online`); } }); callback(null); };
'use strict'; const irc = require('irc'); const server = process.env.IRC_SERVER; const user = process.env.IRC_USER; const channel = process.env.IRC_CHANNEL; const client = module.exports.client = new irc.Client(server, user, { channels: [channel], }); client.on('error', function(error) { console.error(error); console.error('Shutting Down...'); process.exit(1); }); module.exports.post = function(nodes, callback) { nodes.forEach(function(node) { // let name = `[${node.name}](${jenkins}/computer/${node.name})`; if (node.offline) { client.say(channel, `Jenkins slave ${node.name} is offline`); } else { client.say(channel, `Jenkins slave ${node.name} is online`); } }); callback(null); };
Add tests for zoom and travelMode attributes
'use strict'; var chai = require('chai'); var Backbone = require('backbone'); var sinon = require('sinon'); var expect = chai.expect; var MapModel = require('../../app/js/models/map-model'); describe('Map Model', function() { var map; before(function(done) { this.mock = sinon.mock(Backbone); map = new MapModel(); done(); }); it('Should be a backbone model', function(done) { expect(map).to.be.an.instanceof(Backbone.Model); done(); }); it('Should have a zoom attribute', function(done) { expect(map.attributes).to.have.property('end'); done(); }); it('Should have a start attribute', function(done) { expect(map.attributes).to.have.property('start'); done(); }); it('Should have an end attribute', function(done) { expect(map.attributes).to.have.property('end'); done(); }); it('Should have a travelMode attribute', function(done) { expect(map.attributes).to.have.property('end'); done(); }); after(function() { this.mock.verify(); }); });
'use strict'; var chai = require('chai'); var Backbone = require('backbone'); var sinon = require('sinon'); var expect = chai.expect; var MapModel = require('../../app/js/models/map-model'); describe('Map Model', function() { var map; before(function(done) { this.mock = sinon.mock(Backbone); map = new MapModel(); done(); }); it('Should be a backbone model', function(done) { expect(map).to.be.an.instanceof(Backbone.Model); done(); }); it('Should have a start attribute', function(done) { expect(map.attributes).to.have.property('start'); done(); }); it('Should have an end attribute', function(done) { expect(map.attributes).to.have.property('end'); done(); }); after(function() { this.mock.verify(); }); });
Add log for Twilio ICE servers.
var twilio = require('twilio') var winston = require('winston') if (process.env.TWILIO_SID && process.env.TWILIO_TOKEN) { var client = twilio(process.env.TWILIO_SID, process.env.TWILIO_TOKEN) } else { var client = null } var DEFAULT_ICE_SERVERS = [ { url: 'stun:23.21.150.121', // deprecated, replaced by `urls` urls: 'stun:23.21.150.121' } ] var CACHE_LIFETIME = 5 * 60 * 1000 // 5 minutes var cachedPromise = null function clearCache() { cachedPromise = null } exports.getICEServers = function () { if (client == null) return Promise.resolve(DEFAULT_ICE_SERVERS) if (cachedPromise) return cachedPromise cachedPromise = new Promise(function (resolve, reject) { client.tokens.create({}, function(err, token) { if (err) { winston.error(err.message) return resolve({}) } winston.info('Retrieved ICE servers from Twilio', token.ice_servers) setTimeout(clearCache, CACHE_LIFETIME) resolve(token.ice_servers) }) }) return cachedPromise }
var twilio = require('twilio') var winston = require('winston') if (process.env.TWILIO_SID && process.env.TWILIO_TOKEN) { var client = twilio(process.env.TWILIO_SID, process.env.TWILIO_TOKEN) } else { var client = null } var DEFAULT_ICE_SERVERS = [ { url: 'stun:23.21.150.121', // deprecated, replaced by `urls` urls: 'stun:23.21.150.121' } ] var CACHE_LIFETIME = 5 * 60 * 1000 // 5 minutes var cachedPromise = null function clearCache() { cachedPromise = null } exports.getICEServers = function () { if (client == null) return Promise.resolve(DEFAULT_ICE_SERVERS) if (cachedPromise) return cachedPromise cachedPromise = new Promise(function (resolve, reject) { client.tokens.create({}, function(err, token) { if (err) { winston.error(err.message) return resolve({}) } setTimeout(clearCache, CACHE_LIFETIME) resolve(token.ice_servers) }) }) return cachedPromise }
Fix dependency to mis_builder_budget to remove runbot warning
# Copyright 2018 Camptocamp SA # Copyright 2015 Agile Business Group # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { 'name': 'Switzerland - MIS reports', 'summary': 'Specific MIS reports for switzerland localization', 'version': '11.0.1.1.0', 'author': "Camptocamp,Odoo Community Association (OCA)", 'category': 'Localization', 'website': 'https://github.com/OCA/l10n-switzerland', 'license': 'AGPL-3', 'depends': [ 'l10n_ch', 'mis_builder_budget', 'l10n_ch_account_tags', ], 'data': [ 'data/mis_report_style.xml', 'data/mis_report.xml', 'data/mis_report_kpi.xml', ], }
# Copyright 2018 Camptocamp SA # Copyright 2015 Agile Business Group # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { 'name': 'Switzerland - MIS reports', 'summary': 'Specific MIS reports for switzerland localization', 'version': '11.0.1.0.0', 'author': "Camptocamp,Odoo Community Association (OCA)", 'category': 'Localization', 'website': 'https://github.com/OCA/l10n-switzerland', 'license': 'AGPL-3', 'depends': [ 'l10n_ch', 'mis_builder', 'l10n_ch_account_tags', ], 'data': [ 'data/mis_report_style.xml', 'data/mis_report.xml', 'data/mis_report_kpi.xml', ], }
Update sample spring security config Disabling csrf: See https://docs.spring.io/spring-security/site/docs/5.3.0.RELEASE/reference/html5/#csrf-when > Our recommendation is to use CSRF protection for any request that could be processed by a browser > by normal users. If you are only creating a service that is used by non-browser clients, > you will likely want to disable CSRF protection. When CSRF is not explicitly disable, OSB endpoint with PUT/POST http methods get rejected Using noop password encoder See https://github.com/spring-cloud/spring-cloud-open-service-broker/issues/80#issuecomment-390252132
package com.example.servicebroker; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.provisioning.InMemoryUserDetailsManager; @Configuration @EnableWebSecurity public class ExampleSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() .authorizeRequests() .antMatchers("/v2/**").hasRole("ADMIN") .and() .httpBasic(); } @Bean public InMemoryUserDetailsManager userDetailsService() { return new InMemoryUserDetailsManager(adminUser()); } private UserDetails adminUser() { return User .withUsername("admin") .password("{noop}supersecret") .roles("ADMIN") .build(); } }
package com.example.servicebroker; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.provisioning.InMemoryUserDetailsManager; @Configuration @EnableWebSecurity public class ExampleSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/v2/**").hasRole("ADMIN") .and() .httpBasic(); } @Bean public InMemoryUserDetailsManager userDetailsService() { return new InMemoryUserDetailsManager(adminUser()); } private UserDetails adminUser() { return User .withUsername("admin") .password("supersecret") .roles("ADMIN") .build(); } }
BB-4508: Add is null operator to search index - add missed phpdocs
<?php namespace Oro\Bundle\SearchBundle\Query\Criteria; use Doctrine\Common\Collections\Expr\Value; use Doctrine\Common\Collections\ExpressionBuilder as BaseExpressionBuilder; class ExpressionBuilder extends BaseExpressionBuilder { /** * @param string $field * @param string $value * * @return Comparison */ public function notContains($field, $value) { return new Comparison($field, Comparison::NOT_CONTAINS, new Value($value)); } /** * @param string $field * @return Comparison */ public function exists($field) { return new Comparison($field, Comparison::EXISTS, new Value(null)); } /** * @param string $field * @return Comparison */ public function notExists($field) { return new Comparison($field, Comparison::NOT_EXISTS, new Value(null)); } }
<?php namespace Oro\Bundle\SearchBundle\Query\Criteria; use Doctrine\Common\Collections\Expr\Value; use Doctrine\Common\Collections\ExpressionBuilder as BaseExpressionBuilder; class ExpressionBuilder extends BaseExpressionBuilder { /** * @param string $field * @param string $value * * @return Comparison */ public function notContains($field, $value) { return new Comparison($field, Comparison::NOT_CONTAINS, new Value($value)); } public function exists($field) { return new Comparison($field, Comparison::EXISTS, new Value(null)); } public function notExists($field) { return new Comparison($field, Comparison::NOT_EXISTS, new Value(null)); } }
Set some fields as tranlate
# -*- encoding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models, fields class CrmTurnoverRange(models.Model): _name = 'crm.turnover_range' _order = "parent_left" _parent_order = "name" _parent_store = True _description = "Turnover range" name = fields.Char(required=True, translate=True) parent_id = fields.Many2one(comodel_name='crm.turnover_range') children = fields.One2many(comodel_name='crm.turnover_range', inverse_name='parent_id') parent_left = fields.Integer('Parent Left', select=True) parent_right = fields.Integer('Parent Right', select=True)
# -*- encoding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models, fields class CrmTurnoverRange(models.Model): _name = 'crm.turnover_range' _order = "parent_left" _parent_order = "name" _parent_store = True _description = "Turnover range" name = fields.Char(required=True) parent_id = fields.Many2one(comodel_name='crm.turnover_range') children = fields.One2many(comodel_name='crm.turnover_range', inverse_name='parent_id') parent_left = fields.Integer('Parent Left', select=True) parent_right = fields.Integer('Parent Right', select=True)
Set CHROME_BIN on DDC bot Noticed the Linux bot is failing on this: https://build.chromium.org/p/client.dart.fyi/builders/ddc-linux-release-be/builds/1724/steps/ddc%20tests/logs/stdio R=whesse@google.com Review-Url: https://codereview.chromium.org/2640093002 .
#!/usr/bin/env python # # Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. import os import os.path import shutil import sys import subprocess import bot import bot_utils utils = bot_utils.GetUtils() BUILD_OS = utils.GuessOS() (bot_name, _) = bot.GetBotName() CHANNEL = bot_utils.GetChannelFromName(bot_name) if __name__ == '__main__': with utils.ChangedWorkingDirectory('pkg/dev_compiler'): dart_exe = utils.CheckedInSdkExecutable() # These two calls mirror pkg/dev_compiler/tool/test.sh. bot.RunProcess([dart_exe, 'tool/build_pkgs.dart', 'test']) bot.RunProcess([dart_exe, 'test/all_tests.dart']) # These mirror pkg/dev_compiler/tool/browser_test.sh. bot.RunProcess(['npm', 'install']) bot.RunProcess(['npm', 'test'], {'CHROME_BIN': 'chrome'})
#!/usr/bin/env python # # Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. import os import os.path import shutil import sys import subprocess import bot import bot_utils utils = bot_utils.GetUtils() BUILD_OS = utils.GuessOS() (bot_name, _) = bot.GetBotName() CHANNEL = bot_utils.GetChannelFromName(bot_name) if __name__ == '__main__': with utils.ChangedWorkingDirectory('pkg/dev_compiler'): dart_exe = utils.CheckedInSdkExecutable() # These two calls mirror pkg/dev_compiler/tool/test.sh. bot.RunProcess([dart_exe, 'tool/build_pkgs.dart', 'test']) bot.RunProcess([dart_exe, 'test/all_tests.dart']) # These mirror pkg/dev_compiler/tool/browser_test.sh. bot.RunProcess(['npm', 'install']) bot.RunProcess(['npm', 'test'])
Use the Spring Cloud Context version from jhipster-dependencies
/** * Copyright 2013-2018 the original author or authors from the JHipster project. * * This file is part of the JHipster project, see http://www.jhipster.tech/ * for more information. * * 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. */ const AWS_SSM_VERSION = '1.11.247'; const configuration = { aws: 'aws' }; const constants = { conf: configuration, AWS_SSM_VERSION }; module.exports = constants;
/** * Copyright 2013-2018 the original author or authors from the JHipster project. * * This file is part of the JHipster project, see http://www.jhipster.tech/ * for more information. * * 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. */ const AWS_SSM_VERSION = '1.11.247'; const SPRING_CLOUD_CTX_VERSION = '1.3.0.RELEASE'; const configuration = { aws: 'aws' }; const constants = { conf: configuration, AWS_SSM_VERSION, SPRING_CLOUD_CTX_VERSION }; module.exports = constants;
Add avatar_url and owner field for User
from app import db from flask import Flask from datetime import datetime class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) email = db.Column(db.String(120), unique=True) name = db.Column(db.String(80)) bio = db.Column(db.String(180)) avatar_url = db.Column(db.String(256)) owner = db.Column(db.String(32), nullable=False, default='user') github_id = db.Column(db.Integer, unique=True) github_username = db.Column(db.String(64), unique=True) github_token = db.Column(db.String(300), unique=True) password = db.Column(db.String(300)) created_at = db.Column(db.DateTime) def __init__(self, username, email, password, name=None): self.email = email self.username = username self.password = password if name is None: self.name = username else: self.name = name self.created_at = datetime.now() is_authenticated = True is_anonymous = False is_active = True def get_id(self): return unicode(self.id) def __repr__(self): return '<User %r>' % self.username
from app import db from flask import Flask from datetime import datetime class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) email = db.Column(db.String(120), unique=True) name = db.Column(db.String(80)) bio = db.Column(db.String(180)) github_id = db.Column(db.Integer, unique=True) github_username = db.Column(db.String(64), unique=True) github_token = db.Column(db.String(300), unique=True) password = db.Column(db.String(300)) created_at = db.Column(db.DateTime) def __init__(self, username, email, password, name=None): self.email = email self.username = username self.password = password if name is None: self.name = username else: self.name = name self.created_at = datetime.now() is_authenticated = True is_anonymous = False is_active = True def get_id(self): return unicode(self.id) def __repr__(self): return '<User %r>' % self.username
Add block ui to ajax call for signing up to a session
var studentSignUp = function(timeslot_id){ $("#modal_remote").modal('hide'); $.ajax({ type: "PATCH", url: "/api/timeslots/" + timeslot_id, beforeSend: customBlockUi(this) }).done(function(){ swal({ title: "Great!", text: "You have scheduled a tutoring session!", confirmButtonColor: "#66BB6A", type: "success" }); $('#tutor-cal').fullCalendar( 'refetchEvents' ); }).fail(function() { swal({ title: "Oops...", text: "Something went wrong!", confirmButtonColor: "#EF5350", type: "error" }); }); }
var studentSignUp = function(timeslot_id){ $("#modal_remote").modal('hide'); $.ajax({ type: "PATCH", url: "/api/timeslots/" + timeslot_id }).done(function(){ swal({ title: "Great!", text: "You have scheduled a tutoring session!", confirmButtonColor: "#66BB6A", type: "success" }); $('#tutor-cal').fullCalendar( 'refetchEvents' ); }).fail(function() { swal({ title: "Oops...", text: "Something went wrong!", confirmButtonColor: "#EF5350", type: "error" }); }); }
Make use of (new) Turkish support in output formats
#!/usr/bin/env node var readline = require('readline'); var bcv_parser = require('bible-passage-reference-parser/js/tr_bcv_parser').bcv_parser; var bcv = new bcv_parser(); var formatter = require('bible-reference-formatter/es6/tr'); bcv.set_options({ 'sequence_combination_strategy': 'separate' }); bcv.include_apocrypha(true); var rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: false }); var references = []; function extract_references (data) { var res = bcv.parse(data).osis_and_indices(); res.forEach(function(match) { var ref = {}; ref.original = data.slice(match.indices[0], match.indices[1]); ref.osis = match.osis; ref.reformat = formatter('yc-long', match.osis); references.push(ref); }); } function output_references () { var output = JSON.stringify(references, null, ' '); process.stdout.write(output); } rl.on('line', extract_references); rl.on('close', output_references);
#!/usr/bin/env node var readline = require('readline'); var bcv_parser = require('bible-passage-reference-parser/js/tr_bcv_parser').bcv_parser; var bcv = new bcv_parser(); var formatter = require('bible-reference-formatter/es6/en'); bcv.set_options({ 'sequence_combination_strategy': 'separate' }); bcv.include_apocrypha(true); var rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: false }); var references = []; function extract_references (data) { var res = bcv.parse(data).osis_and_indices(); res.forEach(function(match) { var ref = {}; ref.original = data.slice(match.indices[0], match.indices[1]); ref.osis = match.osis; ref.reformat = formatter('niv-long', match.osis); references.push(ref); }); } function output_references () { var output = JSON.stringify(references, null, ' '); process.stdout.write(output); } rl.on('line', extract_references); rl.on('close', output_references);
Create new isEmpty utility method to check for empty objects/arrays
export function getRepoById(repos, id){ const repo = repos.find(repo => repo.id == id); if (repo){ return repo; }else{ return {}; } } export function getBranchByName(branches, branchName){ const branch = branches.find(branch => branch.name == branchName); if (branch){ return branch; }else{ return {}; } } export function findCommitBySha(commits, sha){ const commit = commits.find(commit => commit.sha == sha); if (commit){ return commit; }else{ return {}; } } export function firstSevenOfSha(sha){ return sha.slice(0, 7); } export function makeOptionsArrayFromStrings(stringArray){ let optionsArray = stringArray.map(string => { return { value: string, text: string }; }); return optionsArray; } export function validateObjectExists(obj){ let isValid = true; if(obj === null){ isValid = false; } if(obj === undefined){ isValid = false; } return isValid; } export function isEmpty(obj) { for(let key in obj) { if(obj.hasOwnProperty(key)) { return false; } } return true; }
export function getRepoById(repos, id){ const repo = repos.find(repo => repo.id == id); if (repo){ return repo; }else{ return {}; } } export function getBranchByName(branches, branchName){ const branch = branches.find(branch => branch.name == branchName); if (branch){ return branch; }else{ return {}; } } export function findCommitBySha(commits, sha){ const commit = commits.find(commit => commit.sha == sha); if (commit){ return commit; }else{ return {}; } } export function firstSevenOfSha(sha){ return sha.slice(0, 7); } export function makeOptionsArrayFromStrings(stringArray){ let optionsArray = stringArray.map(string => { return { value: string, text: string }; }); return optionsArray; } export function validateObjectExists(obj){ let isValid = true; if(obj === null){ isValid = false; } if(obj === undefined){ isValid = false; } return isValid; }
Replace "More Information" with "Who We Serve"
import React, { Component } from 'react'; import Section from 'shared/components/section/section'; import ClipPathImage from 'shared/components/clipPathImage/clipPathImage'; import familyImage from 'images/Family-1.jpg'; import milImage from 'images/Mil-1.jpg'; import volunteerImage from 'images/Volunteer-1.jpg'; import styles from './moreInformation.css'; class MoreInformation extends Component { render() { return ( <Section title="Who We Serve" theme="gray"> <div className={styles.moreInformation}> <ClipPathImage title="Military Families and Spouses" image={familyImage} altText="Military Families and Spouses" /> <ClipPathImage title="Veterans, Active Duty, and Reservists" image={milImage} altText="Veterans, Active Duty, and Reservists" /> <ClipPathImage title="Volunteers and Sponsors" image={volunteerImage} altText="Volunteers and Sponsors" /> </div> </Section> ); } } export default MoreInformation;
import React, { Component } from 'react'; import Section from 'shared/components/section/section'; import ClipPathImage from 'shared/components/clipPathImage/clipPathImage'; import familyImage from 'images/Family-1.jpg'; import milImage from 'images/Mil-1.jpg'; import volunteerImage from 'images/Volunteer-1.jpg'; import styles from './moreInformation.css'; class MoreInformation extends Component { render() { return ( <Section title="More Information" theme="gray"> <div className={styles.moreInformation}> <ClipPathImage title="Military Families and Spouses" image={familyImage} altText="Military Families and Spouses" /> <ClipPathImage title="Veterans, Active Duty, and Reservists" image={milImage} altText="Veterans, Active Duty, and Reservists" /> <ClipPathImage title="Volunteers and Sponsors" image={volunteerImage} altText="Volunteers and Sponsors" /> </div> </Section> ); } } export default MoreInformation;
Add attribute name to themeContext object
package org.xcolab.view.theme; import org.springframework.stereotype.Component; import org.springframework.util.Assert; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import org.springframework.web.servlet.view.RedirectView; import org.xcolab.view.auth.AuthenticationService; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Component public class ThemeVariableInterceptor extends HandlerInterceptorAdapter { private final AuthenticationService authenticationService; public ThemeVariableInterceptor(AuthenticationService authenticationService) { Assert.notNull(authenticationService, "AuthenticationContext is required"); this.authenticationService = authenticationService; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) { if (modelAndView != null && !isRedirectView(modelAndView)) { ThemeContext themeContext = new ThemeContext(); themeContext.init(authenticationService, request); modelAndView.addObject("_themeContext", themeContext); } } private boolean isRedirectView(ModelAndView modelAndView) { return (modelAndView.getView() != null && modelAndView.getView() instanceof RedirectView) || modelAndView.getViewName().startsWith("redirect:"); } }
package org.xcolab.view.theme; import org.springframework.stereotype.Component; import org.springframework.util.Assert; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import org.springframework.web.servlet.view.RedirectView; import org.xcolab.view.auth.AuthenticationService; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Component public class ThemeVariableInterceptor extends HandlerInterceptorAdapter { private final AuthenticationService authenticationService; public ThemeVariableInterceptor(AuthenticationService authenticationService) { Assert.notNull(authenticationService, "AuthenticationContext is required"); this.authenticationService = authenticationService; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) { if (modelAndView != null && !isRedirectView(modelAndView)) { ThemeContext themeContext = new ThemeContext(); themeContext.init(authenticationService, request); modelAndView.addObject(themeContext); } } private boolean isRedirectView(ModelAndView modelAndView) { return (modelAndView.getView() != null && modelAndView.getView() instanceof RedirectView) || modelAndView.getViewName().startsWith("redirect:"); } }
Remove FakeEnv from Greedy test suite
import unittest from capstone.policy import GreedyPolicy class TestGreedy(unittest.TestCase): def setUp(self): self.policy = GreedyPolicy() def test_max_action(self): state = 1 actions = [1, 5, 8] fake_qf = { (state, 1): 5, (state, 5): 33, (state, 8): 23, } action = self.policy.action(fake_qf, state, actions) self.assertEqual(action, 5) def test_raises_value_error_if_no_actions_available(self): state = 1 actions = [] with self.assertRaises(ValueError): self.policy.action({}, state, actions)
import unittest from capstone.policy import GreedyPolicy from capstone.util import play_match class FakeEnv(object): def __init__(self): self._actions = [] def cur_state(self): return 'FakeState' def actions(self, state): return self._actions class TestGreedy(unittest.TestCase): def setUp(self): self.policy = GreedyPolicy() self.env = FakeEnv() def test_max_action(self): state = 1 actions = [1, 5, 8] fake_qf = { (state, 1): 5, (state, 5): 33, (state, 8): 23, } action = self.policy.action(fake_qf, state, actions) self.assertEqual(action, 5) def test_raises_value_error_if_no_actions_available(self): state = 1 actions = [] with self.assertRaises(ValueError): self.policy.action({}, state, actions)
Refactor the code to be a pre-processing task.
/*! * stylus-initial * Copyright (c) 2014 Pierre-Antoine "Leny" Delnatte <info@flatland.be> * (Un)Licensed */ "use strict"; var utils = require( "stylus" ).utils, rInitial = /([a-z\-]+)\s*:\s*(initial);/gi, oInitialValues = require( "./values.json" ); var plugin = function() { return function( stylus ) { var oEvaluator = this.evaluator, nodes = this.nodes, _fVisitProperty = oEvaluator.visitProperty; oEvaluator.visitProperty = function( oNode ) { var oCurrentValue, mInitialValue; _fVisitProperty.call( oEvaluator, oNode ); if( oNode.nodeName !== "property" || oNode.expr.isList || ( oCurrentValue = oNode.expr.first ).nodeName !== "ident" || oCurrentValue.string !== "initial" ) { return oNode; } if( ( mInitialValue = oInitialValues[ oNode.name ] ) != null ) { oNode.expr = new nodes.Literal( mInitialValue ); } return oNode; }; }; }; module.exports = plugin; module.exports.version = require( "../package.json" ).version;
/*! * stylus-initial * Copyright (c) 2014 Pierre-Antoine "Leny" Delnatte <info@flatland.be> * (Un)Licensed */ "use strict"; var utils = require( "stylus" ).utils, rInitial = /([a-z\-]+)\s*:\s*(initial);/gi, oInitialValues = require( "./values.json" ); var plugin = function() { return function( stylus ) { stylus.on( "end", function( err, css ) { return css.replace( rInitial, function( sRule, sProperty ) { var mInitialValue; if( ( mInitialValue = oInitialValues[ sProperty ] ) != null ) { return sProperty + ": " + mInitialValue + ";"; } return sRule; } ); } ); }; }; module.exports = plugin; module.exports.version = require( "../package.json" ).version;
Remove deprecated 'zip_safe' flag. It's probably safe anyhow.
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup setup( name='yg.emanate', use_scm_version=True, description="Lightweight event system for Python", author="YouGov, plc", author_email='dev@yougov.com', url='https://github.com/yougov/yg.emanate', packages=[ 'yg.emanate', ], namespace_packages=['yg'], include_package_data=True, setup_requires=['setuptools_scm>=1.15'], keywords='emanate', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', ], test_suite='tests', python_requires=">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*", )
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup setup( name='yg.emanate', use_scm_version=True, description="Lightweight event system for Python", author="YouGov, plc", author_email='dev@yougov.com', url='https://github.com/yougov/yg.emanate', packages=[ 'yg.emanate', ], namespace_packages=['yg'], include_package_data=True, setup_requires=['setuptools_scm>=1.15'], zip_safe=False, keywords='emanate', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', ], test_suite='tests', python_requires=">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*", )
Use event characteristics in causal ordering
package com.opencredo.concourse.mapping.events.methods.ordering; import com.opencredo.concourse.domain.events.Event; import com.opencredo.concourse.domain.events.EventCharacteristics; import com.opencredo.concourse.domain.events.EventType; import java.util.Comparator; import java.util.Map; public final class CausalOrdering { public static final int INITIAL = Integer.MIN_VALUE; public static final int TERMINAL = Integer.MAX_VALUE; public static final int PRE_TERMINAL = TERMINAL - 1; private CausalOrdering() { } public static Comparator<Event> onEventTypes(Map<EventType, Integer> eventTypeMap) { return Comparator.comparing((Event evt) -> eventTypeMap.getOrDefault(EventType.of(evt), getDefaultOrderBasedOnCharacteristics(evt))) .thenComparing(Event::getEventTimestamp); } private static int getDefaultOrderBasedOnCharacteristics(Event evt) { return evt.hasCharacteristic(EventCharacteristics.IS_INITIAL) ? INITIAL : evt.hasCharacteristic(EventCharacteristics.IS_TERMINAL) ? TERMINAL : PRE_TERMINAL; } }
package com.opencredo.concourse.mapping.events.methods.ordering; import com.opencredo.concourse.domain.events.Event; import com.opencredo.concourse.domain.events.EventType; import java.util.Comparator; import java.util.Map; public final class CausalOrdering { public static final int INITIAL = Integer.MIN_VALUE; public static final int TERMINAL = Integer.MAX_VALUE; public static final int PRE_TERMINAL = TERMINAL - 1; private CausalOrdering() { } public static Comparator<Event> onEventTypes(Map<EventType, Integer> eventTypeMap) { return Comparator.comparing((Event evt) -> eventTypeMap.getOrDefault(EventType.of(evt), PRE_TERMINAL)) .thenComparing(Event::getEventTimestamp); } }
Add output option to list of allowed parameters
package com.phsshp.config; import org.apache.commons.cli.*; public class CommandLineParser { private final Options options; public CommandLineParser() { options = new Options(); options.addOption("output", true, "Filename to save output (default is stdout)"); } public String parse(String args[]) { DefaultParser parser = new DefaultParser(); try { CommandLine commandLine = parser.parse(options, args); if (commandLine.getArgList().size() == 0) { printHelpAndExit(); } return commandLine.getArgList().get(0); } catch (ParseException e) { System.out.println("Could not parse: " + e.getMessage()); printHelpAndExit(); return null; } } private void printHelpAndExit() { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("java-code-metrics [OPTION]... [FILE]", "Code metrics for Java source code", options, ""); System.exit(1); } }
package com.phsshp.config; import org.apache.commons.cli.*; public class CommandLineParser { private final Options options; public CommandLineParser() { options = new Options(); } public String parse(String args[]) { DefaultParser parser = new DefaultParser(); try { CommandLine commandLine = parser.parse(options, args); if (commandLine.getArgList().size() == 0) { printHelpAndExit(); } return commandLine.getArgList().get(0); } catch (ParseException e) { System.out.println("Could not parse: " + e.getMessage()); printHelpAndExit(); return null; } } private void printHelpAndExit() { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("java-code-metrics", "Code metrics for Java source code", options, ""); System.exit(1); } }
Replace pre-emptive trimming with double slash removal filter
<?php namespace TightenCo\Jigsaw; class BasicOutputPathResolver { public function link($path, $name, $type, $page = 1) { if ($page > 1) { return $this->clean('/' . $path . '/' . $page . '/' . $name . '.' . $type); } return $this->clean('/' . $path . '/' . $name . '.' . $type); } public function path($path, $name, $type, $page = 1) { return $this->link($path, $name, $type, $page); } public function directory($path, $name, $type, $page = 1) { if ($page > 1) { return $this->clean($path . '/' . $page); } return $this->clean($path); } private function clean($path) { return str_replace('//', '/', $path); } }
<?php namespace TightenCo\Jigsaw; class BasicOutputPathResolver { public function link($path, $name, $type, $page = 1) { if ($page > 1) { return sprintf('%s%s%s%s%s.%s', $this->trimPath($path), '/', $page, '/', $name, $type); } return sprintf('%s%s%s.%s', $this->trimPath($path), '/', $name, $type); } public function path($path, $name, $type, $page = 1) { return $this->link($path, $name, $type, $page); } public function directory($path, $name, $type, $page = 1) { if ($page > 1) { return $this->trimPath($path) . '/' . $page; } return $this->trimPath($path); } private function trimPath($path) { return rtrim(ltrim($path, '/'), '/'); } }
Add comments for the JS task configuration
"use strict"; /** * @typedef {{ * input: string, * output: string, * ignoreLintFor: Array.<(string|RegExp)>, * }} JsTaskConfig */ let fs = require("fs"); let JsTask = require("./js/js-task"); const _ = require("lodash"); /** * Main task for Sass * * @param {JsTaskConfig} config * * @returns {Function} */ module.exports = function (config = {}) { config = _.assign({ // input directory (can be a glob to multiple directories) input: "src/**/Resources/assets/js/", // output directory (relative to input directory) output: "../../public/js", // list of file path paths (string or regex). If the file path matches one of these entries, the file won't be linted ignoreLintFor: ["/node_modules/", "/vendor/"] }, config); // ensure one trailing slash config.input = config.input.replace(/\/+$/, "") + "/"; return function (done, debug) { let task = new JsTask(config); task.run(debug); } };
"use strict"; /** * @typedef {{ * input: string, * output: string, * ignoreLintFor: Array.<(string|RegExp)>, * }} JsTaskConfig */ let fs = require("fs"); let JsTask = require("./js/js-task"); const _ = require("lodash"); /** * Main task for Sass * * @param {JsTaskConfig} config * * @returns {Function} */ module.exports = function (config = {}) { config = _.assign({ input: "src/**/Resources/assets/js/", output: "../../public/js", // list of file path paths (string or regex). If the file path matches one of these entries, the file won't be linted ignoreLintFor: ["/node_modules/", "/vendor/"] }, config); // build internal config config.input = config.input.replace(/\/+$/, "") + "/"; return function (done, debug) { let task = new JsTask(config); task.run(debug); } };
Add build step to PyPI publish command.
import os import sys from setuptools import setup if sys.argv[-1] == 'publish': os.system('make build') os.system('python setup.py sdist upload') sys.exit() import quill with open('README.md', 'r') as readme_file: readme = readme_file.read() os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-quill', version=quill.__version__, author='Ryan Senkbeil', author_email='ryan.senkbeil@gsdesign.com', description='Reusable components for the Django admin.', long_description=readme, packages=['quill'], zip_safe=False, include_package_data=True, platforms='any', install_requires=[], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Internet :: WWW/HTTP', ] )
import os import sys from setuptools import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() import quill with open('README.md', 'r') as readme_file: readme = readme_file.read() os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-quill', version=quill.__version__, author='Ryan Senkbeil', author_email='ryan.senkbeil@gsdesign.com', description='Reusable components for the Django admin.', long_description=readme, packages=['quill'], zip_safe=False, include_package_data=True, platforms='any', install_requires=[], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Internet :: WWW/HTTP', ] )
Insert role_id field after the primary key
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddRoleToUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('users', function ($table) { $table->integer('role_id')->unsigned()->nullable()->after('id'); $table->foreign('role_id')->references('id')->on('roles')->onDelete('set null')->onUpdate('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('users', function ($table) { $table->dropForeign('users_role_id_foreign'); $table->dropColumn('role_id'); }); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddRoleToUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('users', function ($table) { $table->integer('role_id')->unsigned()->nullable(); $table->foreign('role_id')->references('id')->on('roles')->onDelete('set null')->onUpdate('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('users', function ($table) { $table->dropForeign('users_role_id_foreign'); $table->dropColumn('role_id'); }); } }
Move responsibility for appending nodes into variant generators themselves
import _ from 'lodash' import postcss from 'postcss' const variantGenerators = { hover: (container, config) => { const cloned = container.clone() cloned.walkRules(rule => { rule.selector = `.hover${config.options.separator}${rule.selector.slice(1)}:hover` }) container.before(cloned.nodes) }, focus: (container, config) => { const cloned = container.clone() cloned.walkRules(rule => { rule.selector = `.focus${config.options.separator}${rule.selector.slice(1)}:focus` }) container.before(cloned.nodes) }, } export default function(config) { return function(css) { const unwrappedConfig = config() css.walkAtRules('variants', atRule => { const variants = postcss.list.comma(atRule.params) if (variants.includes('responsive')) { const responsiveParent = postcss.atRule({ name: 'responsive' }) atRule.before(responsiveParent) responsiveParent.append(atRule) } atRule.before(atRule.clone().nodes) _.forEach(['focus', 'hover'], variant => { if (variants.includes(variant)) { variantGenerators[variant](atRule, unwrappedConfig) } }) atRule.remove() }) } }
import _ from 'lodash' import postcss from 'postcss' const variantGenerators = { hover: (container, config) => { const cloned = container.clone() cloned.walkRules(rule => { rule.selector = `.hover${config.options.separator}${rule.selector.slice(1)}:hover` }) return cloned.nodes }, focus: (container, config) => { const cloned = container.clone() cloned.walkRules(rule => { rule.selector = `.focus${config.options.separator}${rule.selector.slice(1)}:focus` }) return cloned.nodes }, } export default function(config) { return function(css) { const unwrappedConfig = config() css.walkAtRules('variants', atRule => { const variants = postcss.list.comma(atRule.params) if (variants.includes('responsive')) { const responsiveParent = postcss.atRule({ name: 'responsive' }) atRule.before(responsiveParent) responsiveParent.append(atRule) } atRule.before(atRule.clone().nodes) _.forEach(['focus', 'hover'], variant => { if (variants.includes(variant)) { atRule.before(variantGenerators[variant](atRule, unwrappedConfig)) } }) atRule.remove() }) } }
Make mpi4py required for this package.
from setuptools import setup, find_packages setup( name = 'compdb', version = '0.1', package_dir = {'': 'src'}, packages = find_packages('src'), author = 'Carl Simon Adorf', author_email = 'csadorf@umich.edu', description = "Computational Database.", keywords = 'simulation tools mc md monte-carlo mongodb jobmanagement materials database', classifiers=[ "Development Status :: 2 - Pre-Alpha", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Topic :: Scientific/Engineering :: Physics", ], install_requires=['pymongo', 'mpi4py'], entry_points = { 'console_scripts': [ 'compdb = compdb.contrib.script:main', 'compdb_init = compdb.contrib.init_project:main', 'compdb_configure = compdb.contrib.configure:main', ], }, )
from setuptools import setup, find_packages setup( name = 'compdb', version = '0.1', package_dir = {'': 'src'}, packages = find_packages('src'), author = 'Carl Simon Adorf', author_email = 'csadorf@umich.edu', description = "Computational Database.", keywords = 'simulation tools mc md monte-carlo mongodb jobmanagement materials database', classifiers=[ "Development Status :: 2 - Pre-Alpha", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Topic :: Scientific/Engineering :: Physics", ], install_requires=['pymongo'], entry_points = { 'console_scripts': [ 'compdb = compdb.contrib.script:main', 'compdb_init = compdb.contrib.init_project:main', 'compdb_configure = compdb.contrib.configure:main', ], }, )
Correct path to peer.AddrInfo in deprecation
package peerstore import ( core "github.com/libp2p/go-libp2p-core/peer" ma "github.com/multiformats/go-multiaddr" ) // Deprecated: use github.com/libp2p/go-libp2p-core/peer.AddrInfo instead. type PeerInfo = core.AddrInfo // Deprecated: use github.com/libp2p/go-libp2p-core/peer.ErrInvalidAddr instead. var ErrInvalidAddr = core.ErrInvalidAddr // Deprecated: use github.com/libp2p/go-libp2p-core/peer.AddrInfoFromP2pAddr instead. func InfoFromP2pAddr(m ma.Multiaddr) (*core.AddrInfo, error) { return core.AddrInfoFromP2pAddr(m) } // Deprecated: use github.com/libp2p/go-libp2p-core/peer.AddrInfoToP2pAddrs instead. func InfoToP2pAddrs(pi *core.AddrInfo) ([]ma.Multiaddr, error) { return core.AddrInfoToP2pAddrs(pi) }
package peerstore import ( core "github.com/libp2p/go-libp2p-core/peer" ma "github.com/multiformats/go-multiaddr" ) // Deprecated: use github.com/libp2p/go-libp2p-core/peer.Info instead. type PeerInfo = core.AddrInfo // Deprecated: use github.com/libp2p/go-libp2p-core/peer.ErrInvalidAddr instead. var ErrInvalidAddr = core.ErrInvalidAddr // Deprecated: use github.com/libp2p/go-libp2p-core/peer.AddrInfoFromP2pAddr instead. func InfoFromP2pAddr(m ma.Multiaddr) (*core.AddrInfo, error) { return core.AddrInfoFromP2pAddr(m) } // Deprecated: use github.com/libp2p/go-libp2p-core/peer.AddrInfoToP2pAddrs instead. func InfoToP2pAddrs(pi *core.AddrInfo) ([]ma.Multiaddr, error) { return core.AddrInfoToP2pAddrs(pi) }
Add missing copyright and license header
/* * mochify.js * * Copyright (c) 2014 Maximilian Antoni <mail@maxantoni.de> * * @license MIT */ 'use strict'; var fs = require('fs'); var through = require('through2'); var consolify = require('consolify'); module.exports = function (b, opts) { consolify(b, { bundle: opts.bundle }); function apply() { var file = ''; b.pipeline.get('wrap').push(through(function (chunk, enc, next) { /*jslint unparam: true*/ file += chunk; next(); }, function (next) { fs.writeFileSync(opts.consolify, file); if (opts.watch) { console.log('Generated ' + opts.consolify); } next(); })); } apply(); b.on('reset', apply); };
'use strict'; var fs = require('fs'); var through = require('through2'); var consolify = require('consolify'); module.exports = function (b, opts) { consolify(b, { bundle: opts.bundle }); function apply() { var file = ''; b.pipeline.get('wrap').push(through(function (chunk, enc, next) { /*jslint unparam: true*/ file += chunk; next(); }, function (next) { fs.writeFileSync(opts.consolify, file); if (opts.watch) { console.log('Generated ' + opts.consolify); } next(); })); } apply(); b.on('reset', apply); };
Fix production ID and run command without sudo
from fabric.api import ( cd, env, put, run, sudo, task ) PRODUCTION_IP = '54.154.235.243' PROJECT_DIRECTORY = '/home/ubuntu/ztm/' COMPOSE_FILE = 'compose-production.yml' @task def production(): env.run = sudo env.hosts = [ 'ubuntu@' + PRODUCTION_IP + ':22', ] def create_project_directory(): run('mkdir -p ' + PROJECT_DIRECTORY) def update_compose_file(): put('./' + COMPOSE_FILE, PROJECT_DIRECTORY) @task def deploy(): create_project_directory() update_compose_file() with cd(PROJECT_DIRECTORY): env.run('docker-compose -f ' + COMPOSE_FILE + ' pull') env.run('docker-compose -f ' + COMPOSE_FILE + ' up -d')
from fabric.api import ( cd, env, put, sudo, task ) PRODUCTION_IP = '' PROJECT_DIRECTORY = '/home/ubuntu/ztm/' COMPOSE_FILE = 'compose-production.yml' @task def production(): env.run = sudo env.hosts = [ 'ubuntu@' + PRODUCTION_IP + ':22', ] def create_project_directory(): env.run('mkdir -p ' + PROJECT_DIRECTORY) def update_compose_file(): put('./' + COMPOSE_FILE, PROJECT_DIRECTORY) @task def deploy(): create_project_directory() update_compose_file() with cd(PROJECT_DIRECTORY): env.run('docker-compose -f ' + COMPOSE_FILE + ' pull') env.run('docker-compose -f ' + COMPOSE_FILE + ' up -d')
Remove unseless title/wrong English, etc
<?php /** * @author Pierre-Henry Soria <ph7software@gmail.com> * @copyright (c) 2012-2016, 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 / User / Controller */ namespace PH7; class SearchController extends Controller { public function index() { Framework\Url\Header::redirect(Framework\Mvc\Router\Uri::get('user', 'search', 'quick')); } public function quick() { $this->view->page_title = $this->view->h1_title = t('Quick Search'); $this->output(); } public function advanced() { $this->view->page_title = $this->view->h1_title = t('Advanced Search'); $this->output(); } }
<?php /** * @author Pierre-Henry Soria <ph7software@gmail.com> * @copyright (c) 2012-2016, 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 / User / Controller */ namespace PH7; class SearchController extends Controller { public function index() { Framework\Url\Header::redirect(Framework\Mvc\Router\Uri::get('user', 'search', 'quick')); } public function quick() { $this->view->page_title = t('Search Quick Profiles'); $this->view->h1_title = t('The Search Members | Quick Search'); $this->output(); } public function advanced() { $this->view->page_title = t('Search Advanced Profiles'); $this->view->h1_title = t('The Search Members | Advanced Search'); $this->output(); } }
Support environment variables for the extraction
from subgraph_extractor.cli import extract_from_config import click from cloudpathlib import AnyPath import os @click.command() @click.option( "--subgraph-config-folder", help="The folder containing the subgraph config files", default="config", ) @click.option( "--database-string", default=os.environ.get( "SE_DATABASE_STRING", "postgresql://graph-node:let-me-in@localhost:5432/graph-node", ), help="The database string for connections. Defaults to SE_DATABASE_STRING if set, otherwise a local graph-node", ) @click.option( "--output-location", default=os.environ.get("SE_OUTPUT_LOCATION", "data"), help="The base output location, whether local or cloud. Defaults to SE_OUTPUT_LOCATION if set, otherwise a folder called data", ) def export(subgraph_config_folder, database_string, output_location): for file_name in AnyPath(subgraph_config_folder).glob("*.yaml"): extract_from_config(file_name, database_string, output_location) if __name__ == "__main__": export()
from subgraph_extractor.cli import extract_from_config import click from cloudpathlib import AnyPath @click.command() @click.option( "--subgraph-config-folder", help="The folder containing the subgraph config files", default='config', ) @click.option( "--database-string", default="postgresql://graph-node:let-me-in@localhost:5432/graph-node", help="The database string for connections, defaults to a local graph-node", ) @click.option( "--output-location", default="data", help="The base output location, whether local or cloud", ) def export(subgraph_config_folder, database_string, output_location): for file_name in AnyPath(subgraph_config_folder).glob('*.yaml'): extract_from_config( file_name, database_string, output_location ) if __name__ == "__main__": export()
Make sure language code isset before trying to get it
<?php namespace ContentTranslator\Entity; abstract class Translate { protected $lang; protected $db; public function __construct() { global $wpdb; $this->db = $wpdb; if (isset(\ContentTranslator\Switcher::$currentLanguage->code)) { $this->lang = \ContentTranslator\Switcher::$currentLanguage->code; } } /** * Creates a language specific meta/options key * @param string $key The meta/option key * @return string Langual meta/option key */ protected function createLangualKey(string $key) : string { if ($this->isLangual($key)) { return $key; } return $key . TRANSLATE_DELIMITER . $this->lang; } /** * Check if key is a langual option * @param string $key Option key * @return boolean */ protected function isLangual($key) { return substr($key, -strlen(TRANSLATE_DELIMITER . $this->lang)) == TRANSLATE_DELIMITER . $this->lang ? true : false; } function install(string $language) {} function isInstalled(string $language) {} function uninstall(string $language) {} }
<?php namespace ContentTranslator\Entity; abstract class Translate { protected $lang; protected $db; public function __construct() { global $wpdb; $this->db = $wpdb; $this->lang = \ContentTranslator\Switcher::$currentLanguage->code; } /** * Creates a language specific meta/options key * @param string $key The meta/option key * @return string Langual meta/option key */ protected function createLangualKey(string $key) : string { if ($this->isLangual($key)) { return $key; } return $key . TRANSLATE_DELIMITER . $this->lang; } /** * Check if key is a langual option * @param string $key Option key * @return boolean */ protected function isLangual($key) { return substr($key, -strlen(TRANSLATE_DELIMITER . $this->lang)) == TRANSLATE_DELIMITER . $this->lang ? true : false; } function install(string $language) {} function isInstalled(string $language) {} function uninstall(string $language) {} }
Stop mounting quickfiles if no quickfiles
/** * Initialization code for the profile page. Currently, this just loads the necessary * modules and puts the profile module on the global context. * */ var $ = require('jquery'); var m = require('mithril'); require('../project.js'); // Needed for nodelists to work require('../components/logFeed.js'); // Needed for nodelists to work var profile = require('../profile.js'); // Social, Job, Education classes var publicNodes = require('../components/publicNodes.js'); var quickFiles = require('../components/quickFiles.js'); var ctx = window.contextVars; // Instantiate all the profile modules new profile.Social('#social', ctx.socialUrls, ['view'], false); new profile.Jobs('#jobs', ctx.jobsUrls, ['view'], false); new profile.Schools('#schools', ctx.schoolsUrls, ['view'], false); $(document).ready(function () { m.mount(document.getElementById('publicProjects'), m.component(publicNodes.PublicNodes, {user: ctx.user, nodeType: 'projects'})); m.mount(document.getElementById('publicComponents'), m.component(publicNodes.PublicNodes, {user: ctx.user, nodeType: 'components'})); if(ctx.user.has_quickfiles) { m.mount(document.getElementById('quickFiles'), m.component(quickFiles.QuickFiles, {user: ctx.user})); } });
/** * Initialization code for the profile page. Currently, this just loads the necessary * modules and puts the profile module on the global context. * */ var $ = require('jquery'); var m = require('mithril'); require('../project.js'); // Needed for nodelists to work require('../components/logFeed.js'); // Needed for nodelists to work var profile = require('../profile.js'); // Social, Job, Education classes var publicNodes = require('../components/publicNodes.js'); var quickFiles = require('../components/quickFiles.js'); var ctx = window.contextVars; // Instantiate all the profile modules new profile.Social('#social', ctx.socialUrls, ['view'], false); new profile.Jobs('#jobs', ctx.jobsUrls, ['view'], false); new profile.Schools('#schools', ctx.schoolsUrls, ['view'], false); $(document).ready(function () { m.mount(document.getElementById('publicProjects'), m.component(publicNodes.PublicNodes, {user: ctx.user, nodeType: 'projects'})); m.mount(document.getElementById('publicComponents'), m.component(publicNodes.PublicNodes, {user: ctx.user, nodeType: 'components'})); m.mount(document.getElementById('quickFiles'), m.component(quickFiles.QuickFiles, {user: ctx.user})); });
Remove underscore prefixes from private functions
<?php /** * This file has been made by pH7 (Pierre-Henry SORIA). */ namespace PFBC\Element; use PFBC\Validation\Token as ValidationToken; use PH7\Framework\Mvc\Model\DbConfig; use PH7\Framework\Security\CSRF\Token as SecurityToken; class Token extends Hidden { private $sName; public function __construct($sName) { if (!$this->isEnabled()) return; // If it's disabled, we stop the execution of the class $this->sName = $sName; parent::__construct('security_token', (new SecurityToken)->generate($this->sName)); } public function render() { if (!$this->isEnabled()) return; // If it's disabled, we stop the execution of the class $this->validation[] = new ValidationToken($this->sName); parent::render(); } /** * Check if the CSRF security token for forms is enabled. * * @return boolean Returns TRUE if the security token is enabled, FALSE otherwise. */ private function isEnabled() { // Check if the CSRF security token for forms is enabled return DbConfig::getSetting('securityToken'); } }
<?php /** * This file has been made by pH7 (Pierre-Henry SORIA). */ namespace PFBC\Element; use PFBC\Validation\Token as ValidationToken; use PH7\Framework\Mvc\Model\DbConfig; use PH7\Framework\Security\CSRF\Token as SecurityToken; class Token extends Hidden { private $sName; public function __construct($sName) { if (!$this->_isEnabled()) return; // If it's disabled, we stop the execution of the class $this->sName = $sName; parent::__construct('security_token', (new SecurityToken)->generate($this->sName)); } public function render() { if (!$this->_isEnabled()) return; // If it's disabled, we stop the execution of the class $this->validation[] = new ValidationToken($this->sName); parent::render(); } /** * Check if the CSRF security token for forms is enabled. * * @return boolean Returns TRUE if the security token is enabled, FALSE otherwise. */ private function _isEnabled() { // Check if the CSRF security token for forms is enabled return DbConfig::getSetting('securityToken'); } }
Make the port attribute lowercase ``` // truffle-config.js { // ... db: { port: 69420 } } ```
const command = { command: "serve", description: "Start Truffle's GraphQL UI playground", builder: {}, help: { usage: "truffle db serve", options: [] }, /* This command does starts an express derived server that invokes * `process.exit()` on SIGINT. As a result there is no need to invoke * truffle's own `process.exit()` which is triggered by invoking the `done` * callback. * * Todo: blacklist this command for REPLs */ run: async function(argv) { const Config = require("@truffle/config"); const { playgroundServer } = require("truffle-db"); const config = Config.detect(argv); const port = (config.db && config.db.port) || 4444; const { url } = await playgroundServer(config).listen({ port }); console.log(`🚀 Playground listening at ${url}`); console.log(`ℹ Press Ctrl-C to exit`); } }; module.exports = command;
const command = { command: "serve", description: "Start Truffle's GraphQL UI playground", builder: {}, help: { usage: "truffle db serve", options: [] }, /* This command does starts an express derived server that invokes * `process.exit()` on SIGINT. As a result there is no need to invoke * truffle's own `process.exit()` which is triggered by invoking the `done` * callback. * * Todo: blacklist this command for REPLs */ run: async function(argv) { const Config = require("@truffle/config"); const { playgroundServer } = require("truffle-db"); const config = Config.detect(argv); const port = (config.db && config.db.PORT) || 4444; const { url } = await playgroundServer(config).listen({ port }); console.log(`🚀 Playground listening at ${url}`); console.log(`ℹ Press Ctrl-C to exit`); } }; module.exports = command;
TACHYON-600: Add user model - address comments
/* * Licensed to the University of California, Berkeley under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package tachyon.security; import java.security.Principal; public class User implements Principal { private String mName; // TODO: add more attributes and methods for supporting Kerberos public User(String name) { mName = name; } @Override public String getName() { return mName; } @Override public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) { return false; } else { return mName.equals(((User) o).mName); } } @Override public int hashCode() { return mName.hashCode(); } @Override public String toString() { return mName; } }
/* * Licensed to the University of California, Berkeley under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package tachyon.security; import java.security.Principal; public class User implements Principal { private String mName; // TODO: add more attributes and methods for supporting Kerberos public User(String mName) { this.mName = mName; } @Override public String getName() { return mName; } @Override public boolean equals(Object o) { if (this == o) { return true; } else if (o == null || getClass() != o.getClass()) { return false; } else { return mName.equals(((User) o).mName); } } @Override public int hashCode() { return mName.hashCode(); } @Override public String toString() { return mName; } }
Add dev server status checking for testing safety
import {PROTOCOL, LOCATION, PORT} from '../../shared/constants' import http from 'http' import tcpPortUsed from 'tcp-port-used' const options = { host: '', path: '/data', port: `${PORT}`, method: 'POST', headers: { 'Content-Type': 'application/json' } } const callback = function(response) { let str = '' response.on('data', function (chunk) { str = chunk }) response.on('end', function () { console.log(`deposited ${str}`) }) } let sec = 0 setInterval(function() { tcpPortUsed.check(PORT, 'localhost') .then(function(inUse) { console.log(`Port ${PORT} is now ${inUse ? 'in use' : 'free'}`) if (inUse) { const req = http.request(options, callback) req.write(JSON.stringify( [{ 'dataId': 'speed', 'data': [sec] }] )) req.end() } }, function(err) { console.error('Error on check:', err.message) }) sec += 1 }, 3000)
import {PROTOCOL, LOCATION, PORT} from '../../shared/constants' import http from 'http' const options = { host: '', path: '/data', port: `${PORT}`, method: 'POST', headers: { 'Content-Type': 'application/json' } }; const callback = function(response) { let str = '' response.on('data', function (chunk) { str = chunk; }); response.on('end', function () { console.log(`deposited ${str}`) }); } let sec = 0 setInterval(function() { const req = http.request(options, callback) req.write( JSON.stringify( [ { "dataId": "speed", "data": [sec] } ] ) ); req.end() sec += 1 }, 3000)
Switch trace saga to use takeEvery
import debugModule from "debug"; const debug = debugModule("debugger:trace:sagas"); import { take, takeEvery, put, select } from "redux-saga/effects"; import * as actions from "./actions"; import trace from "./selectors"; export function *waitForTrace() { let {steps} = yield take(actions.SAVE_STEPS); let addresses = [ ...new Set( steps .filter( ({op}) => op == "CALL" || op == "DELEGATECALL" ) .map( ({stack}) => "0x" + stack[stack.length - 2].substring(24) ) ) ]; yield put(actions.receiveAddresses(addresses)); } export function* next() { let remaining = yield select(trace.stepsRemaining); debug("remaining: %o", remaining); let steps = yield select(trace.steps); debug("total steps: %o", steps.length); if (remaining > 0) { debug("putting TICK"); // updates state for current step yield put(actions.tick()); debug("put TICK"); remaining--; // local update, just for convenience } if (remaining) { debug("putting TOCK"); // updates step to next step in trace yield put(actions.tock()); debug("put TOCK"); } else { yield put(actions.endTrace()); } } export default function* saga() { // wait for trace to be defined yield *waitForTrace(); yield takeEvery(actions.NEXT, next); }
import debugModule from "debug"; const debug = debugModule("debugger:trace:sagas"); import { take, takeLatest, put, select } from "redux-saga/effects"; import * as actions from "./actions"; import trace from "./selectors"; export function *waitForTrace() { let {steps} = yield take(actions.SAVE_STEPS); let addresses = [ ...new Set( steps .filter( ({op}) => op == "CALL" || op == "DELEGATECALL" ) .map( ({stack}) => "0x" + stack[stack.length - 2].substring(24) ) ) ]; yield put(actions.receiveAddresses(addresses)); } export function* next() { let remaining = yield select(trace.stepsRemaining); debug("remaining: %o", remaining); let steps = yield select(trace.steps); debug("total steps: %o", steps.length); if (remaining > 0) { debug("putting TICK"); // updates state for current step yield put(actions.tick()); debug("put TICK"); remaining--; // local update, just for convenience } if (remaining) { debug("putting TOCK"); // updates step to next step in trace yield put(actions.tock()); debug("put TOCK"); } else { yield put(actions.endTrace()); } } export default function* saga() { // wait for trace to be defined yield *waitForTrace(); yield takeLatest(actions.NEXT, next); }
Fix issues with map seperators
package moz_test import ( "bytes" "io" "testing" "github.com/influx6/faux/tests" "github.com/influx6/moz" ) // TestFunctionGen validates the expected output of a giving function generator. func TestFunctionGen(t *testing.T) { expected := `func main(v int, m string) { fmt.Printf("Welcome to Lola Land"); }` src := moz.Function( moz.Name("main"), moz.Constructor( moz.VarType( moz.Name("v"), moz.Type("int"), ), moz.VarType( moz.Name("m"), moz.Type("string"), ), ), moz.Returns(), moz.Text(` fmt.Printf("Welcome to Lola Land");`, nil), ) var bu bytes.Buffer if _, err := src.WriteTo(&bu); err != nil && err != io.EOF { tests.Failed("Should have successfully written source output: %+q.", err) } tests.Passed("Should have successfully written source output.") if bu.String() != expected { tests.Info("Source: %+q", bu.String()) tests.Info("Expected: %+q", expected) tests.Failed("Should have successfully matched generated output with expected.") } tests.Passed("Should have successfully matched generated output with expected.") }
package moz_test import ( "bytes" "io" "testing" "github.com/influx6/faux/tests" "github.com/influx6/moz" ) // TestFunctionGen validates the expected output of a giving function generator. func TestFunctionGen(t *testing.T) { expected := `func main(v int, m string) { fmt.Printf("Welcome to Lola Land"); }` src := moz.Function( moz.Name("main"), moz.Constructor( moz.VarType( moz.Name("v"), moz.Type("int"), ), moz.VarType( moz.Name("m"), moz.Type("string"), ), ), moz.Returns(), moz.Text(` fmt.Printf("Welcome to Lola Land");`, nil), ) var bu bytes.Buffer if _, err := src.WriteTo(&bu); err != nil && err != io.EOF { tests.Failed("Should have successfully written source output: %+q.", err) } tests.Passed("Should have successfully written source output.") tests.Info("Source: %+q", bu.String()) if bu.String() != expected { tests.Info("Source: %+q", bu.String()) tests.Info("Expected: %+q", expected) tests.Failed("Should have successfully matched generated output with expected.") } tests.Passed("Should have successfully matched generated output with expected.") }
Change recursive type to Boolean
// Copyright 2019 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.controller.api.integration.configserver; import com.yahoo.vespa.flags.json.wire.WireFlagData; import com.yahoo.vespa.flags.json.wire.WireFlagDataList; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; /** * @author hakonhall */ @Path("") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public interface FlagsV1Api { @PUT @Path("/data/{flagId}") void putFlagData(@PathParam("flagId") String flagId, @QueryParam("force") Boolean force, WireFlagData flagData); @GET @Path("/data/{flagId}") WireFlagData getFlagData(@PathParam("flagId") String flagId, @QueryParam("force") Boolean force); @DELETE @Path("/data/{flagId}") void deleteFlagData(@PathParam("flagId") String flagId, @QueryParam("force") Boolean force); @GET @Path("/data") WireFlagDataList listFlagData(@QueryParam("recursive") Boolean recursive); }
// Copyright 2019 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.controller.api.integration.configserver; import com.yahoo.vespa.flags.json.wire.WireFlagData; import com.yahoo.vespa.flags.json.wire.WireFlagDataList; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; /** * @author hakonhall */ @Path("") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public interface FlagsV1Api { @PUT @Path("/data/{flagId}") void putFlagData(@PathParam("flagId") String flagId, @QueryParam("force") Boolean force, WireFlagData flagData); @GET @Path("/data/{flagId}") WireFlagData getFlagData(@PathParam("flagId") String flagId, @QueryParam("force") Boolean force); @DELETE @Path("/data/{flagId}") void deleteFlagData(@PathParam("flagId") String flagId, @QueryParam("force") Boolean force); @GET @Path("/data") WireFlagDataList listFlagData(@QueryParam("recursive") String recursive); }
Change sample query in the comment
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package sample; public class Main { // Example input for an interactive session. // val sqlContext = new org.apache.spark.sql.SQLContext(sc); val pf = sqlContext.read.parquet("wasb:///parquet/data*") // pf.registerTempTable("pftbl") // pf.count() // sqlContext.sql("SELECT para1, param2, param3 FROM pftbl").show(10) public static void main(String args[]) throws Exception { //InteractiveSample1 client = new InteractiveSample1(); BatchSample client = new BatchSample(); client.run(); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package sample; public class Main { // Example input for an interactive session. // val sqlContext = new org.apache.spark.sql.SQLContext(sc); val pf = sqlContext.read.parquet("wasb:///parquet/data*") // pf.registerTempTable("pftbl") // pf.count() // sqlContext.sql("SELECT para1, param2, param3 FROM pftbl").show(10) public static void main(String args[]) throws Exception { //InteractiveSample1 client = new InteractiveSample1(); BatchSample client = new BatchSample(); client.run(); } }
Fix to work with csarven's changes to util.js
jQuery(document).ready(function($){ $('notices_primary').infinitescroll({ debug: true, infiniteScroll : false, nextSelector : 'body#public li.nav_next a,'+ 'body#all li.nav_next a,'+ 'body#showstream li.nav_next a,'+ 'body#replies li.nav_next a,'+ 'body#showfavorites li.nav_next a,'+ 'body#showgroup li.nav_next a,'+ 'body#favorited li.nav_next a', loadingImg : $('address .url')[0].href+'plugins/InfiniteScroll/ajax-loader.gif', text : "<em>Loading the next set of posts...</em>", donetext : "<em>Congratulations, you\'ve reached the end of the Internet.</em>", navSelector : ".pagination", contentSelector : "#notices_primary ol.notices", itemSelector : "#notices_primary ol.notices li" },function(){ SN.Init.Notices(); }); });
jQuery(document).ready(function($){ $('notices_primary').infinitescroll({ debug: true, infiniteScroll : false, nextSelector : 'body#public li.nav_next a,'+ 'body#all li.nav_next a,'+ 'body#showstream li.nav_next a,'+ 'body#replies li.nav_next a,'+ 'body#showfavorites li.nav_next a,'+ 'body#showgroup li.nav_next a,'+ 'body#favorited li.nav_next a', loadingImg : $('address .url')[0].href+'plugins/InfiniteScroll/ajax-loader.gif', text : "<em>Loading the next set of posts...</em>", donetext : "<em>Congratulations, you\'ve reached the end of the Internet.</em>", navSelector : ".pagination", contentSelector : "#notices_primary ol.notices", itemSelector : "#notices_primary ol.notices li" },function(){ NoticeAttachments(); NoticeReply(); NoticeFavors(); }); });
Revert SiteMiddleware to setting request.site This way, SiteMiddleware continues to support existing user / third-party code that has not yet been migrated from request.site to Site.find_for_request
import warnings from django.utils.deprecation import MiddlewareMixin from wagtail.core.models import Site from wagtail.utils.deprecation import RemovedInWagtail211Warning class SiteMiddleware(MiddlewareMixin): def process_request(self, request): """ Set request.site to contain the Site object responsible for handling this request, according to hostname matching rules """ warnings.warn( 'Wagtail SiteMiddleware and the use of request.site is deprecated ' 'and will be removed in Wagtail 2.11. Update your middleware settings.', RemovedInWagtail211Warning, stacklevel=2 ) try: request.site = Site.find_for_request(request) except Site.DoesNotExist: request.site = None
import warnings from django.utils.deprecation import MiddlewareMixin from wagtail.core.models import Site from wagtail.utils.deprecation import RemovedInWagtail28Warning class SiteMiddleware(MiddlewareMixin): def process_request(self, request): """ Set request.site to contain the Site object responsible for handling this request, according to hostname matching rules """ warnings.warn( 'wagtail SiteMiddleware and the use of request.site is deprecated ' 'and will be removed in wagtail 2.8. Update your middleware settings.', RemovedInWagtail28Warning, stacklevel=2 ) try: request._wagtail_site = Site.find_for_request(request) except Site.DoesNotExist: request._wagtail_site = None
Add getRequest that PHPStorm will complete (ZF1 bad design)
<?php namespace Del\Common\ZF1\Controller; use Del\Common\ContainerService; use Exception; use Zend_Auth; use Zend_Controller_Action; use Zend_Layout; class AbstractController extends Zend_Controller_Action { protected $container; public function init() { $this->container = ContainerService::getInstance()->getContainer(); } /** * @param $key * @return mixed */ public function getContainerObject($key) { return $this->container[$key]; } /** * */ public function sendJSONResponse(array $array) { Zend_Layout::getMvcInstance()->disableLayout(); $this->_helper->viewRenderer->setNoRender(); $this->getResponse()->setHeader('Content-Type', 'application/json'); $this->_helper->json($array); } public function getIdentity() { if(Zend_Auth::getInstance()->hasIdentity()) { return Zend_Auth::getInstance()->getIdentity(); } throw new Exception('No Identity.'); } /** * @return Zend_Controller_Request_Http */ public function getRequest() { return parent::getRequest(); } }
<?php namespace Del\Common\ZF1\Controller; use Del\Common\ContainerService; use Exception; use Zend_Auth; use Zend_Controller_Action; use Zend_Layout; class AbstractController extends Zend_Controller_Action { protected $container; public function init() { $this->container = ContainerService::getInstance()->getContainer(); } /** * @param $key * @return mixed */ public function getContainerObject($key) { return $this->container[$key]; } /** * */ public function sendJSONResponse(array $array) { Zend_Layout::getMvcInstance()->disableLayout(); $this->_helper->viewRenderer->setNoRender(); $this->getResponse()->setHeader('Content-Type', 'application/json'); $this->_helper->json($array); } public function getIdentity() { if(Zend_Auth::getInstance()->hasIdentity()) { return Zend_Auth::getInstance()->getIdentity(); } throw new Exception('No Identity.'); } }
Add authorize middleware for routs requiring logged user
'use strict'; const controllers = require('../controllers/base.controller'); const csrf = require('csurf') ({ cookie: true }); const authorize = (req, res) => { if (!req.user) { res.redirect('/'); } } module.exports = (app) => { app .get('/', controllers.home.index) .get('/about', controllers.home.about) .get('/user/register', controllers.user.register) .post('/user/register', controllers.user.create) .get('/user/login', controllers.user.login) .post('/user/login', controllers.user.authenticate) .post('/user/logout', controllers.user.logout) .get('/user/profile', csrf, authorize, controllers.user.showProfile) .post('/user/profile', csrf, authorize, controllers.user.updateProfile) .get('/error', function(req, res) { res.render('partial/404', { message: "The page was not found", mainTitle: "Error 404", status: "404" }) }) .all('*', (req, res) => { res.redirect('/error'); }) }
'use strict'; const controllers = require('../controllers/base.controller'); const csrf = require('csurf') ({ cookie: true }); module.exports = (app) => { app .get('/', controllers.home.index) .get('/about', controllers.home.about) .get('/user/register', controllers.user.register) .post('/user/register', controllers.user.create) .get('/user/login', controllers.user.login) .post('/user/login', controllers.user.authenticate) .post('/user/logout', controllers.user.logout) .get('/user/profile', csrf, controllers.user.showProfile) .post('/user/profile', csrf, controllers.user.updateProfile) .get('/error', function(req, res) { res.render('partial/404', { message: "The page was not found", mainTitle: "Error 404", status: "404" }) }) .all('*', (req, res) => { res.redirect('/error'); }) }
Make centroid factory locations a little more plausible
import factory import factory.fuzzy from backend.images import models class ImageSeriesFactory(factory.django.DjangoModelFactory): class Meta: model = models.ImageSeries patient_id = factory.Sequence(lambda n: "TEST-SERIES-%04d" % n) series_instance_uid = factory.Sequence(lambda n: "1.3.6.1.4.1.14519.5.2.1.6279.6001.%030d" % n) uri = factory.LazyAttribute(lambda f: 'file:///tmp/%s/' % f.series_instance_uid) class ImageLocationFactory(factory.django.DjangoModelFactory): class Meta: model = models.ImageLocation series = factory.LazyAttribute(lambda f: f.factory_parent.case.series) x = factory.fuzzy.FuzzyInteger(0, 256) y = factory.fuzzy.FuzzyInteger(0, 256) z = factory.fuzzy.FuzzyInteger(0, 16)
import factory import factory.fuzzy from backend.images import models class ImageSeriesFactory(factory.django.DjangoModelFactory): class Meta: model = models.ImageSeries patient_id = factory.Sequence(lambda n: "TEST-SERIES-%04d" % n) series_instance_uid = factory.Sequence(lambda n: "1.3.6.1.4.1.14519.5.2.1.6279.6001.%030d" % n) uri = factory.LazyAttribute(lambda f: 'file:///tmp/%s/' % f.series_instance_uid) class ImageLocationFactory(factory.django.DjangoModelFactory): class Meta: model = models.ImageLocation series = factory.LazyAttribute(lambda f: f.factory_parent.case.series) x = factory.fuzzy.FuzzyInteger(0, 511) y = factory.fuzzy.FuzzyInteger(0, 511) z = factory.fuzzy.FuzzyInteger(0, 63)
[gulp] Add the watch task, which watches for sass changes and recompiles
var gulp = require('gulp'); var sass = require('gulp-sass'); var sourcemaps = require('gulp-sourcemaps'); var paths = { sass: { src: ['static/sass/**/*.scss'], dest: 'static/css' } }; gulp.task('sass', function() { return gulp.src(paths.sass.src) .pipe(sourcemaps.init()) .pipe(sass()) .pipe(sourcemaps.write( paths.sass.dest, {sourceRoot: '/static/sass'} )) .pipe(gulp.dest(paths.sass.dest)); }); gulp.task('watch', function() { gulp.watch(paths.sass.src, ['sass']); }); gulp.task('default', []);
var gulp = require('gulp'); var sass = require('gulp-sass'); var sourcemaps = require('gulp-sourcemaps'); var paths = { sass: { src: ['static/sass/**/*.scss'], dest: 'static/css' } }; gulp.task('sass', function() { return gulp.src(paths.sass.src) .pipe(sourcemaps.init()) .pipe(sass()) .pipe(sourcemaps.write( paths.sass.dest, {sourceRoot: '/static/sass'} )) .pipe(gulp.dest(paths.sass.dest)); }); gulp.task('default', []);
game/quests: Implement getObjective and tooltip objective
# -*- coding: utf-8 -*- """ Quests - questcache.wdb """ from .. import * class Quest(Model): def getTooltip(self): return QuestTooltip(self) class QuestTooltip(Tooltip): def tooltip(self): self.append("name", self.obj.getName(), color=YELLOW) self.appendEmptyLine() self.append("objective", self.obj.getObjective()) self.appendEmptyLine() ret = self.values self.values = [] return ret class QuestProxy(object): """ WDBC proxy for quests """ def __init__(self, cls): from pywow import wdbc self.__file = wdbc.get("questcache.wdb", build=-1) def get(self, id): return self.__file[id] def getCompleteSummary(self, row): return row.complete_summary def getDescription(self, row): return row.description.replace("$B", "\n") def getName(self, row): return row.name def getObjective(self, row): return row.objective def getSummary(self, row): return row.summary Quest.initProxy(QuestProxy)
# -*- coding: utf-8 -*- """ Quests - questcache.wdb """ from .. import * class Quest(Model): def getTooltip(self): return QuestTooltip(self) class QuestTooltip(Tooltip): def tooltip(self): self.append("name", self.obj.getName(), color=YELLOW) ret = self.values self.values = [] return ret class QuestProxy(object): """ WDBC proxy for quests """ def __init__(self, cls): from pywow import wdbc self.__file = wdbc.get("questcache.wdb", build=-1) def get(self, id): return self.__file[id] def getCompleteSummary(self, row): return row.complete_summary def getDescription(self, row): return row.description.replace("$B", "\n") def getName(self, row): return row.name def getSummary(self, row): return row.summary Quest.initProxy(QuestProxy)
Remove trailing slash in siteUrl This fixes issue where URLs had `//` in them because the post slugs start with `/`
const colors = require('../../src/styles/colors') module.exports = { homeTitle: 'Ben Ilegbodu', siteTitle: 'Ben Ilegbodu', shortSiteTitle: 'Ben Ilegbodu', siteDescription: 'Christ follower, husband & father of ✌. UI Architect & Speaker. ES6+, React & CSS3. Basketball, DIY & movies. Principal Frontend Engineer @ Eventbrite', siteUrl: 'http://www.benmvp.com', pathPrefix: '', siteImage: 'preview.jpg', siteLanguage: 'en', // author authorName: 'Ben Ilegbodu', authorTwitterAccount: 'benmvp', // info infoTitle: 'Ben Ilegbodu', infoTitleNote: 'UI Architect', // manifest.json manifestName: 'Ben Ilegbodu', manifestShortName: 'BenMVP', // max 12 characters manifestStartUrl: '/', manifestBackgroundColor: colors.bg, manifestThemeColor: colors.bg, manifestDisplay: 'standalone', // social authorSocialLinks: [ {name: 'twitter', url: 'https://twitter.com/benmvp', title: 'Follow Ben Ilegbodu on Twitter'}, {name: 'github', url: 'https://github.com/benmvp', title: "Ben Ilegbodu's projects"}, {name: 'linkedin', url: 'https://linkedin.com/in/benmvp', title: "Ben Ilegbodu's resume"}, ], // disqus disqusShortname: 'benmvp', }
const colors = require('../../src/styles/colors') module.exports = { homeTitle: 'Ben Ilegbodu', siteTitle: 'Ben Ilegbodu', shortSiteTitle: 'Ben Ilegbodu', siteDescription: 'Christ follower, husband & father of ✌. UI Architect & Speaker. ES6+, React & CSS3. Basketball, DIY & movies. Principal Frontend Engineer @ Eventbrite', siteUrl: 'http://www.benmvp.com/', pathPrefix: '', siteImage: 'preview.jpg', siteLanguage: 'en', // author authorName: 'Ben Ilegbodu', authorTwitterAccount: 'benmvp', // info infoTitle: 'Ben Ilegbodu', infoTitleNote: 'UI Architect', // manifest.json manifestName: 'Ben Ilegbodu', manifestShortName: 'BenMVP', // max 12 characters manifestStartUrl: '/', manifestBackgroundColor: colors.bg, manifestThemeColor: colors.bg, manifestDisplay: 'standalone', // social authorSocialLinks: [ {name: 'twitter', url: 'https://twitter.com/benmvp', title: 'Follow Ben Ilegbodu on Twitter'}, {name: 'github', url: 'https://github.com/benmvp', title: "Ben Ilegbodu's projects"}, {name: 'linkedin', url: 'https://linkedin.com/in/benmvp', title: "Ben Ilegbodu's resume"}, ], // disqus disqusShortname: 'benmvp', }
Add readme screenshot to screenshot config.
const puppeteer = require('puppeteer') const path = require('path') const HOST = process.env.TRAVIS == true ? 'http://localhost:8080/' : 'https://jsonnull.com/' const readme = { url: '', size: { width: 1920, height: 1080 }, options: { path: 'public/readme.jpeg', quality: 70 } } const twitter = { url: 'twitter.html', size: { width: 1500, height: 500 }, options: { path: 'public/twitterHeader.png' } } const screenshots = [readme, twitter] const main = async () => { const browser = await puppeteer.launch({ args: ['--no-sandbox', '--disable-setuid-sandbox'] }) const page = await browser.newPage() for (let i = 0; i < screenshots.length; i++) { let screenshot = screenshots[i] if (screenshot.size) { await page.setViewport(screenshot.size) } try { await page.goto(HOST + screenshot.url, { waitUntil: 'networkidle' }) await page.screenshot(screenshot.options) } catch (e) { console.error(e) } } await browser.close() } main()
const puppeteer = require('puppeteer') const path = require('path') const HOST = process.env.TRAVIS == true ? 'http://localhost:8080/' : 'https://jsonnull.com/' const readme = { url: '', size: { width: 1920, height: 1080 }, options: { path: 'public/readme.jpeg', quality: 70 } } const twitter = { url: 'twitter.html', size: { width: 1500, height: 500 }, options: { path: 'public/twitterHeader.png' } } const screenshots = [twitter] const main = async () => { const browser = await puppeteer.launch({ args: ['--no-sandbox', '--disable-setuid-sandbox'] }) const page = await browser.newPage() for (let i = 0; i < screenshots.length; i++) { let screenshot = screenshots[i] if (screenshot.size) { await page.setViewport(screenshot.size) } try { await page.goto(HOST + screenshot.url, { waitUntil: 'networkidle' }) await page.screenshot(screenshot.options) } catch (e) { console.error(e) } } await browser.close() } main()
Initialize scores and focus when start button is pressed
'use strict'; var Games_x01 = function () { console.log('x01: start'); var focusClass = 'focus'; var dartsUi = window.dartsUi; var scoreIndex = 1; var scoreElements = $('.scores td'); var totalScore = 301; var totalScoreElements = $('.scores-total-score td'); for (var i = 1; i < scoreElements.length; i++) { $(scoreElements[i]).removeClass(focusClass).text(0); } $(scoreElements[scoreIndex]).addClass(focusClass); dartsUi.onHit(function (cellId, point, ratio) { // console.log(cellId + ' : ' + point + ' x ' + ratio + ' = ' + point * ratio); $(scoreElements[scoreIndex]).text(point * ratio); $(scoreElements[scoreIndex]).removeClass(focusClass); scoreIndex++; $(scoreElements[scoreIndex]).addClass(focusClass); totalScore -= point * ratio; $(totalScoreElements).text(totalScore); if (totalScore <= 0) { console.log('Clear!'); } }); };
'use strict'; var Games_x01 = function () { console.log('x01: start'); var focusClass = 'focus'; var dartsUi = window.dartsUi; var scoreIndex = 1; var scoreElements = $('.scores td'); var totalScore = 301; var totalScoreElements = $('.scores-total-score td'); $(scoreElements[scoreIndex]).addClass(focusClass); dartsUi.onHit(function (cellId, point, ratio) { // console.log(cellId + ' : ' + point + ' x ' + ratio + ' = ' + point * ratio); $(scoreElements[scoreIndex]).text(point * ratio); $(scoreElements[scoreIndex]).removeClass(focusClass); scoreIndex++; $(scoreElements[scoreIndex]).addClass(focusClass); totalScore -= point * ratio; $(totalScoreElements).text(totalScore); if (totalScore <= 0) { console.log('Clear!'); } }); };
Support CLI on Python 2.6
#!/usr/bin/env python import os import sys from distutils.core import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() _install_requires = [ "parsimonious>=0.5,<0.6", ] if sys.version_info[:2] <= (2, 6): _install_requires.append("argparse==1.2.1") setup( name='mammoth', version='0.1.1', description='Convert Word documents to simple and clean HTML', long_description=read("README"), author='Michael Williamson', author_email='mike@zwobble.org', url='http://github.com/mwilliamson/python-mammoth', packages=['mammoth', 'mammoth.docx', 'mammoth.style_reader'], scripts=["scripts/mammoth"], keywords="docx word office clean html", install_requires=_install_requires, )
#!/usr/bin/env python import os from distutils.core import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='mammoth', version='0.1.1', description='Convert Word documents to simple and clean HTML', long_description=read("README"), author='Michael Williamson', author_email='mike@zwobble.org', url='http://github.com/mwilliamson/python-mammoth', packages=['mammoth', 'mammoth.docx', 'mammoth.style_reader'], scripts=["scripts/mammoth"], keywords="docx word office clean html", install_requires=[ "parsimonious>=0.5,<0.6", ] )
[ENH] Rename wizard page "Initialize Tiki" to "Featured Profiles". It describes better what it is and "invites" more profile pages git-svn-id: fe65cb8b726aa1bab0c239f321eb4f822d15ce08@48913 b456876b-0849-0410-b77d-98878d47e9d5
<?php // (c) Copyright 2002-2013 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id$ require_once('lib/wizard/wizard.php'); /** * Show the initial profiles choices */ class AdminWizardProfiles extends Wizard { function pageTitle () { return tra('Featured Profiles'); } function isEditable () { return false; } function onSetupPage ($homepageUrl) { global $smarty, $prefs; // Run the parent first parent::onSetupPage($homepageUrl); // Assign the page temaplte $wizardTemplate = 'wizard/admin_profiles.tpl'; $smarty->assign('wizardBody', $wizardTemplate); return true; } function onContinue ($homepageUrl) { // Run the parent first parent::onContinue($homepageUrl); } }
<?php // (c) Copyright 2002-2013 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id$ require_once('lib/wizard/wizard.php'); /** * Show the initial profiles choices */ class AdminWizardProfiles extends Wizard { function pageTitle () { return tra('Initialize Tiki'); } function isEditable () { return false; } function onSetupPage ($homepageUrl) { global $smarty, $prefs; // Run the parent first parent::onSetupPage($homepageUrl); // Assign the page temaplte $wizardTemplate = 'wizard/admin_profiles.tpl'; $smarty->assign('wizardBody', $wizardTemplate); return true; } function onContinue ($homepageUrl) { // Run the parent first parent::onContinue($homepageUrl); } }
Improve pragma handling for sqlite3
var Utils = require("../../utils") , sqlite3 = require('sqlite3').verbose() , Query = require("./query") module.exports = (function() { var ConnectorManager = function(sequelize) { this.sequelize = sequelize this.database = db = new sqlite3.Database(sequelize.options.storage || ':memory:', function(err) { if(!err && sequelize.options.foreignKeys !== false) { // Make it possible to define and use foreign key constraints unelss // explicitly disallowed. It's still opt-in per relation db.run('PRAGMA FOREIGN_KEYS=ON') } }) } Utils._.extend(ConnectorManager.prototype, require("../connector-manager").prototype) ConnectorManager.prototype.query = function(sql, callee, options) { return new Query(this.database, this.sequelize, callee, options).run(sql) } return ConnectorManager })()
var Utils = require("../../utils") , sqlite3 = require('sqlite3').verbose() , Query = require("./query") module.exports = (function() { var ConnectorManager = function(sequelize) { this.sequelize = sequelize this.database = new sqlite3.Database(sequelize.options.storage || ':memory:') this.opened = false } Utils._.extend(ConnectorManager.prototype, require("../connector-manager").prototype) ConnectorManager.prototype.query = function(sql, callee, options) { var self = this // Turn on foreign key checking (if the database has any) unless explicitly // disallowed globally. if(!this.opened && this.sequelize.options.foreignKeys !== false) { this.database.serialize(function() { self.database.run("PRAGMA FOREIGN_KEYS = ON") self.opened = true }) } return new Query(this.database, this.sequelize, callee, options).run(sql) } return ConnectorManager })()
Remove list filter based on event category
from django.utils.translation import ugettext_lazy as _ from django.contrib import admin from mezzanine.core.admin import StackedDynamicInlineAdmin, DisplayableAdmin from fullcalendar.models import * class EventCategoryAdmin(admin.ModelAdmin): list_display = ('name',) class OccurrenceInline(StackedDynamicInlineAdmin): model = Occurrence fields = ('start_time', 'end_time', 'description', 'location') class EventAdmin(DisplayableAdmin): list_display = ('title', 'status') search_fields = ('title', 'description', 'content') fieldsets = ( (None, { "fields": [ "title", "status", ("publish_date", "expiry_date"), "event_category", "content" ] }), (_("Meta data"), { "fields": [ "_meta_title", "slug", ("description", "gen_description"), "keywords", "in_sitemap" ], "classes": ("collapse-closed",) }), ) inlines = [OccurrenceInline] admin.site.register(Event, EventAdmin) admin.site.register(EventCategory, EventCategoryAdmin)
from django.utils.translation import ugettext_lazy as _ from django.contrib import admin from mezzanine.core.admin import StackedDynamicInlineAdmin, DisplayableAdmin from fullcalendar.models import * class EventCategoryAdmin(admin.ModelAdmin): list_display = ('name',) class OccurrenceInline(StackedDynamicInlineAdmin): model = Occurrence fields = ('start_time', 'end_time', 'description', 'location') class EventAdmin(DisplayableAdmin): list_display = ('title', 'status') list_filter = ('event_category',) search_fields = ('title', 'description', 'content') fieldsets = ( (None, { "fields": [ "title", "status", ("publish_date", "expiry_date"), "event_category", "content" ] }), (_("Meta data"), { "fields": [ "_meta_title", "slug", ("description", "gen_description"), "keywords", "in_sitemap" ], "classes": ("collapse-closed",) }), ) inlines = [OccurrenceInline] admin.site.register(Event, EventAdmin) admin.site.register(EventCategory, EventCategoryAdmin)
[prover] Disable warning messages in Z3
package edu.kit.iti.formal.pse.worthwhile.prover; import java.util.Arrays; import java.util.List; /** * Caller for the Z3 Prover by Microsoft Research. */ public class Z3Prover extends StdProver { /** * Construct a new prover caller with the default Z3 command line. * * The default Z3 command line is <code>z3 -in -smt2</code>. */ public Z3Prover() { /* we will assume that z3 is in the PATH */ this(Arrays.asList("z3", "-in", "-smt2", "-nw")); } /** * Construct a new {@link Z3Prover} with the given command line. * * @param command * the command line that is executed to run the Z3 prover binary */ public Z3Prover(final String command) { /* we will use SMTLib as the input format */ super(command, new SMTLIBStrategy()); } /** * Construct a new {@link Z3Prover} with the given command line. * * @param command * the command line that is executed to run the Z3 prover binary */ public Z3Prover(final List<String> command) { /* we will use SMTLib as the input format */ super(command, new SMTLIBStrategy()); } @Override public final ProverResult getResult(final String output) { return new Z3ProverResult(output); } }
package edu.kit.iti.formal.pse.worthwhile.prover; import java.util.Arrays; import java.util.List; /** * Caller for the Z3 Prover by Microsoft Research. */ public class Z3Prover extends StdProver { /** * Construct a new prover caller with the default Z3 command line. * * The default Z3 command line is <code>z3 -in -smt2</code>. */ public Z3Prover() { /* we will assume that z3 is in the PATH */ this(Arrays.asList("z3", "-in", "-smt2")); } /** * Construct a new {@link Z3Prover} with the given command line. * * @param command * the command line that is executed to run the Z3 prover binary */ public Z3Prover(final String command) { /* we will use SMTLib as the input format */ super(command, new SMTLIBStrategy()); } /** * Construct a new {@link Z3Prover} with the given command line. * * @param command * the command line that is executed to run the Z3 prover binary */ public Z3Prover(final List<String> command) { /* we will use SMTLib as the input format */ super(command, new SMTLIBStrategy()); } @Override public final ProverResult getResult(final String output) { return new Z3ProverResult(output); } }
Fix factory reference in presentable model
<?php namespace Nectary\Models; use Nectary\Data_Model; use Nectary\Factory; /** * A Viewable model is one that can present itself so that all of its * properties and calculated properties are useable within a template */ abstract class Presentable_Model extends Data_Model { /** * Present the model using the class provided * by presents(). Present knows how to build * factories. * * @return array */ public function present( $options = [] ) { $class_reference = $this->get_presenter_class_name(); if ( ! is_null( $class_reference ) ) { $instance = new $class_reference( $this, $options ); if ( $instance instanceof Factory ) { return $instance->build(); } else { return to_array( $instance ); } } else { return to_array( $this ); } } /** * Called to determine which class knows how to present the model. * Returning the string of a Factory class is prefered. * * @return String The name of the class that knows how to present the model */ abstract protected function get_presenter_class_name(); }
<?php namespace Nectary\Models; use Nectary\Data_Model; /** * A Viewable model is one that can present itself so that all of its * properties and calculated properties are useable within a template */ abstract class Presentable_Model extends Data_Model { /** * Present the model using the class provided * by presents(). Present knows how to build * factories. * * @return array */ public function present( $options = [] ) { $class_reference = $this->get_presenter_class_name(); if ( ! is_null( $class_reference ) ) { $instance = new $class_reference( $this, $options ); if ( $instance instanceof Factory ) { return $instance->build(); } else { return to_array( $instance ); } } else { return to_array( $this ); } } /** * Called to determine which class knows how to present the model. * Returning the string of a Factory class is prefered. * * @return String The name of the class that knows how to present the model */ abstract protected function get_presenter_class_name(); }
Refactor to latest bixby changes.
exports = module.exports = function express(id) { var map = { 'service': './service', 'authenticator': './authenticator', 'boot/httpserver': './boot/httpserver' }; var mid = map[id]; if (mid) { return require(mid); } }; exports.main = function() { function pre(IoC) { IoC.use('http', require('bixby-http')); IoC.use(exports); } function post(IoC) { var server = IoC.create('http/server'); var service = IoC.create('service'); var init = IoC.create('initializer'); init.phase(require('bootable').di.routes('app/routes'), service); // TODO: Create this phase via IoC init.phase(require('./init.d/listen')(server, service)); } require('bixby').main(pre, post); }
exports = module.exports = function express(id) { var map = { 'service': './service', 'authenticator': './authenticator', 'boot/httpserver': './boot/httpserver' }; var mid = map[id]; if (mid) { return require(mid); } }; exports.main = function() { console.log('bixby express main!'); // TODO: clean this up function pre(IoC) { console.log('PRE RUN!'); IoC.use('http', require('bixby-http')); IoC.use(exports); } // TODO: clean this up function post(IoC) { console.log('POST!'); var server = IoC.create('http/server'); var handler = IoC.create('service'); server.on('request', handler); server.listen(8080); } require('bixby').main(pre, post); }
BB-6622: Create PropertyAccess data provider - cs fix
<?php namespace Oro\Bundle\LayoutBundle\Tests\Unit\Layout\DataProvider; use Symfony\Component\PropertyAccess\PropertyAccessor; use Oro\Bundle\LayoutBundle\Layout\DataProvider\PropertyAccessDataProvider; class PropertyAccessDataProviderTest extends \PHPUnit_Framework_TestCase { public function testGetValue() { $object = new \stdClass(); $propertyPath = 'foo.bar["fee"]'; $result = 'result'; $propertyAccess = $this->createMock(PropertyAccessor::class); $propertyAccess->expects($this->once()) ->method('getValue') ->with($object, $propertyPath) ->willReturn($result); $provider = new PropertyAccessDataProvider($propertyAccess); $actual = $provider->getValue($object, $propertyPath); $this->assertEquals($result, $actual); } }
<?php namespace Oro\Bundle\LayoutBundle\Tests\Unit\Layout\DataProvider; use Oro\Bundle\LayoutBundle\Layout\DataProvider\PropertyAccessDataProvider; use Symfony\Component\PropertyAccess\PropertyAccessor; class PropertyAccessDataProviderTest extends \PHPUnit_Framework_TestCase { public function testGetValue() { $object = new \stdClass(); $propertyPath = 'foo.bar["fee"]'; $result = 'result'; $propertyAccess = $this->createMock(PropertyAccessor::class); $propertyAccess->expects($this->once()) ->method('getValue') ->with($object, $propertyPath) ->willReturn($result); $provider = new PropertyAccessDataProvider($propertyAccess); $actual = $provider->getValue($object, $propertyPath); $this->assertEquals($result, $actual); } }
Increment version number now that 0.1.5 release out.
import os from os.path import relpath, join from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() def find_package_data(data_root, package_root): files = [] for root, dirnames, filenames in os.walk(data_root): for fn in filenames: files.append(relpath(join(root, fn), package_root)) return files setup( name = "smarty", version = "0.1.6", author = "John Chodera, David Mobley, and others", author_email = "john.chodera@choderalab.org", description = ("Automated Bayesian atomtype sampling"), license = "MIT", keywords = "Bayesian atomtype sampling forcefield parameterization", url = "http://github.com/open-forcefield-group/smarty", packages=['smarty', 'smarty/tests', 'smarty/data'], long_description=read('README.md'), classifiers=[ "Development Status :: 3 - Alpha", "Topic :: Utilities", "License :: OSI Approved :: MIT", ], entry_points={'console_scripts': ['smarty = smarty.cli_smarty:main', 'smirky = smarty.cli_smirky:main']}, package_data={'smarty': find_package_data('smarty/data', 'smarty')}, )
import os from os.path import relpath, join from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() def find_package_data(data_root, package_root): files = [] for root, dirnames, filenames in os.walk(data_root): for fn in filenames: files.append(relpath(join(root, fn), package_root)) return files setup( name = "smarty", version = "0.1.5", author = "John Chodera, David Mobley, and others", author_email = "john.chodera@choderalab.org", description = ("Automated Bayesian atomtype sampling"), license = "MIT", keywords = "Bayesian atomtype sampling forcefield parameterization", url = "http://github.com/open-forcefield-group/smarty", packages=['smarty', 'smarty/tests', 'smarty/data'], long_description=read('README.md'), classifiers=[ "Development Status :: 3 - Alpha", "Topic :: Utilities", "License :: OSI Approved :: MIT", ], entry_points={'console_scripts': ['smarty = smarty.cli_smarty:main', 'smirky = smarty.cli_smirky:main']}, package_data={'smarty': find_package_data('smarty/data', 'smarty')}, )
Remove tr after approving/rejecting accounts
function remove(target) { var p = target.parentElement.parentElement; p.parentElement.removeChild(p); } var approves = document.querySelectorAll(".approve"); for (var i = 0; i < approves.length; i++) { approves[i].addEventListener("click", function(e) { e.preventDefault(); var id = e.target.dataset.user; var xhr = new XMLHttpRequest(); xhr.open("POST", "/api/approve/" + id); xhr.send(); remove(e.target); }); } var rejects = document.querySelectorAll(".reject"); for (var i = 0; i < rejects.length; i++) { rejects[i].addEventListener("click", function(e) { e.preventDefault(); var id = e.target.dataset.user; var xhr = new XMLHttpRequest(); xhr.open("POST", "/api/reject/" + id); xhr.send(); remove(e.target); }); }
var approves = document.querySelectorAll(".approve"); for (var i = 0; i < approves.length; i++) { approves[i].addEventListener("click", function(e) { e.preventDefault(); var id = e.target.dataset.user; var xhr = new XMLHttpRequest(); xhr.open("POST", "/api/approve/" + id); xhr.send(); }); } var rejects = document.querySelectorAll(".reject"); for (var i = 0; i < rejects.length; i++) { rejects[i].addEventListener("click", function(e) { e.preventDefault(); var id = e.target.dataset.user; var xhr = new XMLHttpRequest(); xhr.open("POST", "/api/reject/" + id); xhr.send(); }); }
Remove wrong migration of contracts.
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (C) 2015 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Coninckx David <david@coninckx.com> # # The licence is in the file __openerp__.py # ############################################################################## import sys def migrate(cr, version): reload(sys) sys.setdefaultencoding('UTF8') if not version: return delay_dict = {'annual': 12, 'biannual': 6, 'fourmonthly': 4, 'quarterly': 3, 'bimonthly': 2, 'monthly': 1} cr.execute( ''' SELECT id, advance_billing FROM recurring_contract_group ''' ) contract_groups = cr.fetchall() for contract_group in contract_groups: delay = delay_dict[contract_group[1]] or 1 cr.execute( ''' UPDATE recurring_contract_group SET advance_billing_months = {0} WHERE id = {1} '''.format(delay, contract_group[0]) )
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (C) 2015 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Coninckx David <david@coninckx.com> # # The licence is in the file __openerp__.py # ############################################################################## import sys def migrate(cr, version): reload(sys) sys.setdefaultencoding('UTF8') if not version: return delay_dict = {'annual': 12, 'biannual': 6, 'fourmonthly': 4, 'quarterly': 3, 'bimonthly': 2, 'monthly': 1} cr.execute( ''' SELECT id, advance_billing FROM recurring_contract_group ''' ) contract_groups = cr.fetchall() for contract_group in contract_groups: delay = delay_dict[contract_group[1]] or 1 cr.execute( ''' UPDATE recurring_contract_group SET recurring_value = {0}, advance_billing_months = {0} WHERE id = {1} '''.format(delay, contract_group[0]) )
Remove deleted posts from DOM when not showing deleted posts
{{-- Copyright (c) ppy Pty Ltd <contact@ppy.sh>. This file is part of osu!web. osu!web is distributed with the hope of attracting more community contributions to the core ecosystem of osu!. osu!web is free software: you can redistribute it and/or modify it under the terms of the Affero GNU General Public License version 3 as published by the Free Software Foundation. osu!web is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with osu!web. If not, see <http://www.gnu.org/licenses/>. --}} @extends('forum.topics.replace_delete_button', ['countDifference' => -1]) @section('moderatorAction') $deletedToggle = document.querySelector(".js-forum-topic-moderate--toggle-deleted"); if ($deletedToggle.dataset.showDeleted === "1") { $el.addClass("js-forum-post--hidden"); } else { $el.remove(); } @endsection
{{-- Copyright (c) ppy Pty Ltd <contact@ppy.sh>. This file is part of osu!web. osu!web is distributed with the hope of attracting more community contributions to the core ecosystem of osu!. osu!web is free software: you can redistribute it and/or modify it under the terms of the Affero GNU General Public License version 3 as published by the Free Software Foundation. osu!web is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with osu!web. If not, see <http://www.gnu.org/licenses/>. --}} @extends('forum.topics.replace_delete_button', ['countDifference' => -1]) @section('moderatorAction') $el.addClass("js-forum-post--hidden"); @endsection
Remove failing test (BC break in symfony 2.8)
<?php namespace Symnedi\Security\Tests\Core\Authorization; use InvalidArgumentException; use PHPUnit_Framework_TestCase; use Symfony\Component\Security\Core\Authorization\AccessDecisionManager; use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface; use Symnedi\Security\Core\Authorization\AccessDecisionManagerFactory; class AccessDecisionManagerFactoryTest extends PHPUnit_Framework_TestCase { /** * @var AccessDecisionManagerFactory */ private $accessDecisionManagerFactory; protected function setUp() { $this->accessDecisionManagerFactory = new AccessDecisionManagerFactory([]); } public function testCreateWithOneVoter() { $voterMock = $this->prophesize(VoterInterface::class); $this->accessDecisionManagerFactory->addVoter($voterMock->reveal()); $accessDecisionManager = $this->accessDecisionManagerFactory->create(); $this->assertInstanceOf(AccessDecisionManager::class, $accessDecisionManager); } }
<?php namespace Symnedi\Security\Tests\Core\Authorization; use InvalidArgumentException; use PHPUnit_Framework_TestCase; use Symfony\Component\Security\Core\Authorization\AccessDecisionManager; use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface; use Symnedi\Security\Core\Authorization\AccessDecisionManagerFactory; class AccessDecisionManagerFactoryTest extends PHPUnit_Framework_TestCase { /** * @var AccessDecisionManagerFactory */ private $accessDecisionManagerFactory; protected function setUp() { $this->accessDecisionManagerFactory = new AccessDecisionManagerFactory([]); } public function testAtLeastOneVoter() { $this->setExpectedException(InvalidArgumentException::class); $this->accessDecisionManagerFactory->create(); } public function testCreateWithOneVoter() { $voterMock = $this->prophesize(VoterInterface::class); $this->accessDecisionManagerFactory->addVoter($voterMock->reveal()); $accessDecisionManager = $this->accessDecisionManagerFactory->create(); $this->assertInstanceOf(AccessDecisionManager::class, $accessDecisionManager); } }
Update for compatibility with Vagrant 1.2 1.2 changed how the box UUID was written to the filesystem. Instead of JSON it's now written as a single file .vagrant/machines/default/virtualbox/id
<?php /** * Checks current directory for a running Vagrant virtual machine * * Author: John Kary <john@johnkary.net> */ $cwd = getcwd(); $uuid = getVagrantUuidInDir($cwd); if (false === $uuid) { // No vagrant file in this dir exit(1); } $runningVms = getRunningVms(); if (!isVmRunning($runningVms, $uuid)) { // VM not running exit(1); } // VM running exit(0); function getVagrantUuidInDir($dir) { $path = realpath($dir . '/.vagrant/machines/default/virtualbox/id'); if (false === $path) { // File with UUID doesn't exist return false; } return file_get_contents($path); } function getRunningVms() { exec('vboxmanage list runningvms', $output); return $output; } function isVmRunning($runningVms, $uuid) { return (bool) strstr(implode(' ', $runningVms), $uuid); }
<?php /** * Checks current directory for a running Vagrant virtual machine * * Author: John Kary <john@johnkary.net> */ $cwd = getcwd(); $filecontents = getVagrantFileRunningInDir($cwd); if (false === $filecontents) { // No vagrant file in this dir exit(1); } $uuid = getDirVagrantUuid($filecontents); $runningVms = getRunningVms(); if (!isVmRunning($runningVms, $uuid)) { // VM not running exit(1); } // VM running exit(0); function getVagrantFileRunningInDir($dir) { $path = realpath($dir . '/.vagrant'); if (false === $path) { // File with UUID doesn't exist return false; } return file_get_contents($path); } function getDirVagrantUuid($filecontents) { $vagrantJson = json_decode($filecontents); return $vagrantJson->active->default; } function getRunningVms() { exec('vboxmanage list runningvms', $output); return $output; } function isVmRunning($runningVms, $uuid) { return (bool) strstr(implode(' ', $runningVms), $uuid); }
Change tickets page with on site first
import React, { Component } from 'react'; import CustomTitle from '../Cards/CustomTitle'; import PresalesCard from '../Cards/Tickets/PresalesCard'; import OnSiteCard from '../Cards/Tickets/OnSiteCard'; const i18n_strings = { fr: { title: 'Tickets', desc: 'Sur place et Préventes', }, en: { title: 'Tickets', desc: 'On site and pre sales', }, nl: { title: 'Tickets', desc: 'Ter plaatse / Voorverkoop', }, } export default class TicketsPage extends React.Component { render() { var strings = i18n_strings[this.props.lang] || i18n_strings['fr']; return ( <div> <CustomTitle title={strings.title} desc={strings.desc} /> <OnSiteCard lang={this.props.lang} /> <p/> <PresalesCard lang={this.props.lang} /> </div> ); } }
import React, { Component } from 'react'; import CustomTitle from '../Cards/CustomTitle'; import PresalesCard from '../Cards/Tickets/PresalesCard'; import OnSiteCard from '../Cards/Tickets/OnSiteCard'; const i18n_strings = { fr: { title: 'Tickets', desc: 'Sur place et Préventes', }, en: { title: 'Tickets', desc: 'On site and pre sales', }, nl: { title: 'Tickets', desc: 'Ter plaatse / Voorverkoop', }, } export default class TicketsPage extends React.Component { render() { var strings = i18n_strings[this.props.lang] || i18n_strings['fr']; return ( <div> <CustomTitle title={strings.title} desc={strings.desc} /> <PresalesCard lang={this.props.lang} /> <OnSiteCard lang={this.props.lang} /> </div> ); } }
Fix integration test to run the BeforeClass method for all groups
package dk.statsbiblioteket.medieplatform.newspaper.editionRecords; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import dk.statsbiblioteket.medieplatform.autonomous.ConfigConstants; import dk.statsbiblioteket.medieplatform.autonomous.DomsItemFactory; import dk.statsbiblioteket.medieplatform.autonomous.Item; import dk.statsbiblioteket.medieplatform.autonomous.SolrJConnector; import java.io.FileInputStream; import java.util.List; import java.util.Properties; import static org.testng.Assert.*; public class NewspaperIndexIT { private String summaLocation; @BeforeClass(alwaysRun = true) public void setUp() throws Exception { String pathToProperties = System.getProperty("integration.test.newspaper.properties"); Properties props = new Properties(); props.load(new FileInputStream(pathToProperties)); summaLocation = props.getProperty(ConfigConstants.AUTONOMOUS_SBOI_URL); } @Test(groups = "externalTest") public void testGetNewspapers() throws Exception { NewspaperIndex newspaperIndex = new NewspaperIndex(new SolrJConnector(summaLocation).getSolrServer(), new DomsItemFactory()); List<Item> newspapers = newspaperIndex.getNewspapers("berlingsketidende", "1970-01-01"); assertTrue(newspapers.size() == 1); } }
package dk.statsbiblioteket.medieplatform.newspaper.editionRecords; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import dk.statsbiblioteket.medieplatform.autonomous.ConfigConstants; import dk.statsbiblioteket.medieplatform.autonomous.DomsItemFactory; import dk.statsbiblioteket.medieplatform.autonomous.Item; import dk.statsbiblioteket.medieplatform.autonomous.SolrJConnector; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.List; import java.util.Properties; import static org.testng.Assert.*; public class NewspaperIndexIT { private String summaLocation; @BeforeClass public void setUp() throws Exception { Properties props = new Properties(); try { props.load(new FileReader(new File(System.getProperty("integration.test.newspaper.properties")))); } catch (IOException e) { throw new RuntimeException(e); } summaLocation = props.getProperty(ConfigConstants.AUTONOMOUS_SBOI_URL); } @Test(groups = "externalTest") public void testGetNewspapers() throws Exception { NewspaperIndex newspaperIndex = new NewspaperIndex(new SolrJConnector(summaLocation).getSolrServer(), new DomsItemFactory()); List<Item> newspapers = newspaperIndex.getNewspapers("berlingsketidende", "1970-01-01"); assertTrue(newspapers.size() == 1); } }
Make the name of an organization required
from rest_framework import serializers from bluebottle.organizations.models import Organization from bluebottle.utils.serializers import URLField class OrganizationSerializer(serializers.ModelSerializer): class Meta: model = Organization fields = ('id', 'name', 'slug', 'address_line1', 'address_line2', 'city', 'state', 'country', 'postal_code', 'phone_number', 'website', 'email') class ManageOrganizationSerializer(serializers.ModelSerializer): slug = serializers.SlugField(required=False, allow_null=True) name = serializers.CharField(required=True) website = URLField(required=False, allow_blank=True) email = serializers.EmailField(required=False, allow_blank=True) class Meta: model = Organization fields = OrganizationSerializer.Meta.fields + ('partner_organizations', 'created', 'updated')
from rest_framework import serializers from bluebottle.organizations.models import Organization from bluebottle.utils.serializers import URLField class OrganizationSerializer(serializers.ModelSerializer): class Meta: model = Organization fields = ('id', 'name', 'slug', 'address_line1', 'address_line2', 'city', 'state', 'country', 'postal_code', 'phone_number', 'website', 'email') class ManageOrganizationSerializer(serializers.ModelSerializer): slug = serializers.SlugField(required=False, allow_null=True) name = serializers.CharField(required=True, allow_blank=True) website = URLField(required=False, allow_blank=True) email = serializers.EmailField(required=False, allow_blank=True) class Meta: model = Organization fields = OrganizationSerializer.Meta.fields + ('partner_organizations', 'created', 'updated')
Refactor "result" method: call fetch_all with MYSQLI_ASSOC
<?php /** * This file is part of the Crystal package. * * (c) Sergey Novikov (novikov.stranger@gmail.com) * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * Date: 16.12.2014 * Time: 16:26 */ namespace core\db_drivers\query_results; /** * Class MySQLResult * @package core\db_drivers\query_results */ class MySQLiResult extends QueryResult { /** * @return null|object */ public function row() { return ($this->result->num_rows > 0) ? $this->result->fetch_object() : false; } /** * @return array|null */ public function result() { return ($this->result->num_rows > 0) ? $this->result->fetch_all(MYSQLI_ASSOC) : []; } }
<?php /** * This file is part of the Crystal package. * * (c) Sergey Novikov (novikov.stranger@gmail.com) * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * Date: 16.12.2014 * Time: 16:26 */ namespace core\db_drivers\query_results; /** * Class MySQLResult * @package core\db_drivers\query_results */ class MySQLiResult extends QueryResult { /** * @return null|object */ public function row() { return ($this->result->num_rows > 0) ? $this->result->fetch_object() : false; } /** * @return array|null */ public function result() { return ($this->result->num_rows > 0) ? $this->result->fetch_all() : []; } }
Update count value to Number type.
var mongoose = require('mongoose'); require('./projectModel'); var AkamaiSchema = new mongoose.Schema({ Day : { type: String, index: true}, URL: String, Completed : Number, Initiated : Number, EDGE_VOLUME : Number, OK_EDGE_VOLUME : Number, ERROR_EDGE_VOLUME : Number, EDGE_HITS : Number, OK_EDGE_HITS : Number, ERROR_EDGE_HITS : Number, R_0XX : Number, R_2XX : Number, R_200 : Number, R_206 : Number, R_3XX : Number, R_302 : Number, R_304 : Number, R_4XX : Number, R_404 : Number, OFFLOADED_HITS : Number, ORIGIN_HITS : Number, ORIGIN_VOLUME : Number, MT : String, Project: String }); mongoose.model('AkamaiLog', AkamaiSchema);
var mongoose = require('mongoose'); require('./projectModel'); var AkamaiSchema = new mongoose.Schema({ Day : { type: String, index: true}, URL: String, Completed : Number, Initiated : String, EDGE_VOLUME : String, OK_EDGE_VOLUME : String, ERROR_EDGE_VOLUME : String, EDGE_HITS : String, OK_EDGE_HITS : String, ERROR_EDGE_HITS : String, R_0XX : String, R_2XX : String, R_200 : String, R_206 : String, R_3XX : String, R_302 : String, R_304 : String, R_4XX : String, R_404 : String, OFFLOADED_HITS : String, ORIGIN_HITS : String, ORIGIN_VOLUME : String, MT : String, Project: String }); mongoose.model('AkamaiLog', AkamaiSchema);
BAP-16729: Remove DecoratorApiType and refactor dependent types - remove deprecated 'cascade_validation' option
<?php namespace Oro\Bundle\ApiBundle\Form\Type; use Oro\Bundle\SoapBundle\Form\EventListener\PatchSubscriber; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; /** * This abstract form type may be used to be extended from to adapt any form type to be used as root form type * for REST and SOAP API. */ abstract class AbstractPatchableApiType extends AbstractType { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->addEventSubscriber(new PatchSubscriber()); } /** * {@inheritdoc} */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults( [ 'csrf_protection' => false ] ); } /** * {@inheritdoc} */ public function getName() { return $this->getBlockPrefix(); } }
<?php namespace Oro\Bundle\ApiBundle\Form\Type; use Oro\Bundle\SoapBundle\Form\EventListener\PatchSubscriber; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; /** * This abstract form type may be used to be extended from to adapt any form type to be used as root form type * for REST and SOAP API. */ abstract class AbstractPatchableApiType extends AbstractType { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->addEventSubscriber(new PatchSubscriber()); } /** * {@inheritdoc} */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults( [ 'cascade_validation' => true, 'csrf_protection' => false ] ); } /** * {@inheritdoc} */ public function getName() { return $this->getBlockPrefix(); } }
Fix docblock for return type Signed-off-by: Daniel Kesselberg <1d6e1cf70ec6f9ab28d3ea4b27a49a77654d370e@danielkesselberg.de>
<?php /** * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Morris Jobke <hey@morrisjobke.de> * @author Robin Appelman <robin@icewind.nl> * * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> * */ namespace OC\Files\Mount; /** * Defines the mount point to be (re)moved by the user */ interface MoveableMount { /** * Move the mount point to $target * * @param string $target the target mount point * @return bool */ public function moveMount($target); /** * Remove the mount points * * @return bool */ public function removeMount(); }
<?php /** * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Morris Jobke <hey@morrisjobke.de> * @author Robin Appelman <robin@icewind.nl> * * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> * */ namespace OC\Files\Mount; /** * Defines the mount point to be (re)moved by the user */ interface MoveableMount { /** * Move the mount point to $target * * @param string $target the target mount point * @return bool */ public function moveMount($target); /** * Remove the mount points * * @return mixed * @return bool */ public function removeMount(); }
Fix verbage around why we are disallowing removing a primary
# Copyright (c) 2015 Ansible, Inc. # All Rights Reserved from django.core.management.base import CommandError from awx.main.management.commands._base_instance import BaseCommandInstance from awx.main.models import Instance instance_str = BaseCommandInstance.instance_str class Command(BaseCommandInstance): """Internal tower command. Remove an existing instance from the HA instance table. This command is idempotent. This command will error out in the following conditions: * Attempting to remove a primary instance. """ def __init__(self): super(Command, self).__init__() self.include_option_hostname_uuid_find() def handle(self, *args, **options): super(Command, self).handle(*args, **options) # Is there an existing record for this machine? If so, retrieve that record and look for issues. try: # Get the instance. instance = Instance.objects.get(**self.get_unique_fields()) # Sanity check: Do not remove the primary instance. if instance.primary: raise CommandError('Can not remove primary instance %s. Another instance must be promoted to primary first.' % instance_str(instance)) # Remove the instance. instance.delete() print('Successfully removed instance %s.' % instance_str(instance)) except Instance.DoesNotExist: print('No matching instance found to remove.')
# Copyright (c) 2015 Ansible, Inc. # All Rights Reserved from django.core.management.base import CommandError from awx.main.management.commands._base_instance import BaseCommandInstance from awx.main.models import Instance instance_str = BaseCommandInstance.instance_str class Command(BaseCommandInstance): """Internal tower command. Remove an existing instance from the HA instance table. This command is idempotent. This command will error out in the following conditions: * Attempting to remove a primary instance. """ def __init__(self): super(Command, self).__init__() self.include_option_hostname_uuid_find() def handle(self, *args, **options): super(Command, self).handle(*args, **options) # Is there an existing record for this machine? If so, retrieve that record and look for issues. try: # Get the instance. instance = Instance.objects.get(**self.get_unique_fields()) # Sanity check: Do not remove the primary instance. if instance.primary: raise CommandError('I cowardly refuse to remove the primary instance %s.' % instance_str(instance)) # Remove the instance. instance.delete() print('Successfully removed instance %s.' % instance_str(instance)) except Instance.DoesNotExist: print('No matching instance found to remove.')
Add the deletion of the app users
from django.core.management.base import BaseCommand, CommandError from app.models import Author, Location, AutoComment, Comment, Idea, Vote, SocialNetworkAppUser class Command(BaseCommand): def handle(self, *args, **options): self.stdout.write('Starting to clean app tables...') try: Idea.objects.all().delete() self.stdout.write('Ideas were deleted') Comment.objects.all().delete() self.stdout.write('Comments were deleted') Vote.objects.all().delete() self.stdout.write('Votes were deleted') Location.objects.all().delete() self.stdout.write('Locations were deleted') Author.objects.all().delete() self.stdout.write('Authors were deleted') AutoComment.objects.all().delete() self.stdout.write('Automatic Comments were deleted') SocialNetworkAppUser.objects.all().delete() self.stdout.write('App users were deleted') except Exception as e: raise CommandError('The cleaning procedure couldn\'t finished. Error {}'.format(e)) self.stdout.write('The procedure has finished successfully...')
from django.core.management.base import BaseCommand, CommandError from app.models import Author, Location, AutoComment, Comment, Idea, Vote class Command(BaseCommand): def handle(self, *args, **options): self.stdout.write('Starting to clean app tables...') try: Idea.objects.all().delete() self.stdout.write('Ideas deleted') Comment.objects.all().delete() self.stdout.write('Comments deleted') Vote.objects.all().delete() self.stdout.write('Votes deleted') Location.objects.all().delete() self.stdout.write('Locations deleted') Author.objects.all().delete() self.stdout.write('Authors deleted') AutoComment.objects.all().delete() self.stdout.write('Automatic Comments deleted') except Exception as e: raise CommandError('The cleaning procedure couldn\'t finished. Error {}'.format(e)) self.stdout.write('The procedure has finished successfully...')
Use absolute paths for the templates
<?php return [ /* |-------------------------------------------------------------------------- | Where the templates for the generators are stored... |-------------------------------------------------------------------------- | */ 'model_template_path' => base_path() . 'vendor/way/generators/src/Way/Generators/templates/model.txt', 'scaffold_model_template_path' => base_path() . 'vendor/way/generators/src/Way/Generators/templates/scaffolding/model.txt', 'controller_template_path' => base_path() . 'vendor/way/generators/src/Way/Generators/templates/controller.txt', 'scaffold_controller_template_path' => base_path() . 'vendor/way/generators/src/Way/Generators/templates/scaffolding/controller.txt', 'migration_template_path' => base_path() . 'vendor/way/generators/src/Way/Generators/templates/migration.txt', 'seed_template_path' => base_path() . 'vendor/way/generators/src/Way/Generators/templates/seed.txt', 'view_template_path' => base_path() . 'vendor/way/generators/src/Way/Generators/templates/view.txt', /* |-------------------------------------------------------------------------- | Where the generated files will be saved... |-------------------------------------------------------------------------- | */ 'model_target_path' => app_path('models'), 'controller_target_path' => app_path('controllers'), 'migration_target_path' => app_path('database/migrations'), 'seed_target_path' => app_path('database/seeds'), 'view_target_path' => app_path('views') ];
<?php return [ /* |-------------------------------------------------------------------------- | Where the templates for the generators are stored... |-------------------------------------------------------------------------- | */ 'model_template_path' => 'vendor/way/generators/src/Way/Generators/templates/model.txt', 'scaffold_model_template_path' => 'vendor/way/generators/src/Way/Generators/templates/scaffolding/model.txt', 'controller_template_path' => 'vendor/way/generators/src/Way/Generators/templates/controller.txt', 'scaffold_controller_template_path' => 'vendor/way/generators/src/Way/Generators/templates/scaffolding/controller.txt', 'migration_template_path' => 'vendor/way/generators/src/Way/Generators/templates/migration.txt', 'seed_template_path' => 'vendor/way/generators/src/Way/Generators/templates/seed.txt', 'view_template_path' => 'vendor/way/generators/src/Way/Generators/templates/view.txt', /* |-------------------------------------------------------------------------- | Where the generated files will be saved... |-------------------------------------------------------------------------- | */ 'model_target_path' => app_path('models'), 'controller_target_path' => app_path('controllers'), 'migration_target_path' => app_path('database/migrations'), 'seed_target_path' => app_path('database/seeds'), 'view_target_path' => app_path('views') ];
Add a default value of None for reserved fields
import sys from .base import Field from ..fields import args class Reserved(Field): default = args.Override(default=None) def __init__(self, *args, **kwargs): super(Reserved, self).__init__(*args, **kwargs) # Hack to add the reserved field to the class without # having to explicitly give it a (likely useless) name frame = sys._getframe(2) locals = frame.f_locals locals[self.get_available_name(locals.keys())] = self def get_available_name(self, locals): i = 0 while True: name = '_reserved_%s' % i if name not in locals: return name i += 1 def set_name(self, name): if hasattr(self, 'name'): raise TypeError('Reserved fields must not be given an attribute name') super(Reserved, self).set_name(name) def encode(self, value): return b'\x00' * self.size def decode(self, value): return None
import sys from .base import Field class Reserved(Field): def __init__(self, *args, **kwargs): super(Reserved, self).__init__(*args, **kwargs) # Hack to add the reserved field to the class without # having to explicitly give it a (likely useless) name frame = sys._getframe(2) locals = frame.f_locals locals[self.get_available_name(locals.keys())] = self def get_available_name(self, locals): i = 0 while True: name = '_reserved_%s' % i if name not in locals: return name i += 1 def set_name(self, name): if hasattr(self, 'name'): raise TypeError('Reserved fields must not be given an attribute name') super(Reserved, self).set_name(name) def encode(self, value): return b'\x00' * self.size def decode(self, value): return None