text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Disable W0232, no `__init__` method.
|
# -*- coding: utf-8 -*-
'''
salt.utils.yamldumper
~~~~~~~~~~~~~~~~~~~~~
'''
# pylint: disable=W0232
# class has no __init__ method
from __future__ import absolute_import
try:
from yaml import CDumper as Dumper
from yaml import CSafeDumper as SafeDumper
except ImportError:
from yaml import Dumper
from yaml import SafeDumper
from salt.utils.odict import OrderedDict
class OrderedDumper(Dumper):
'''
A YAML dumper that represents python OrderedDict as simple YAML map.
'''
class SafeOrderedDumper(SafeDumper):
'''
A YAML safe dumper that represents python OrderedDict as simple YAML map.
'''
def represent_ordereddict(dumper, data):
return dumper.represent_dict(data.items())
OrderedDumper.add_representer(OrderedDict, represent_ordereddict)
SafeOrderedDumper.add_representer(OrderedDict, represent_ordereddict)
|
# -*- coding: utf-8 -*-
'''
salt.utils.yamldumper
~~~~~~~~~~~~~~~~~~~~~
'''
from __future__ import absolute_import
try:
from yaml import CDumper as Dumper
from yaml import CSafeDumper as SafeDumper
except ImportError:
from yaml import Dumper
from yaml import SafeDumper
from salt.utils.odict import OrderedDict
class OrderedDumper(Dumper):
'''
A YAML dumper that represents python OrderedDict as simple YAML map.
'''
class SafeOrderedDumper(SafeDumper):
'''
A YAML safe dumper that represents python OrderedDict as simple YAML map.
'''
def represent_ordereddict(dumper, data):
return dumper.represent_dict(data.items())
OrderedDumper.add_representer(OrderedDict, represent_ordereddict)
SafeOrderedDumper.add_representer(OrderedDict, represent_ordereddict)
|
Insert encrypt button placeholder in open chat tabs
|
// ==UserScript==
// @name OTR for Facebook
// @include http://*.facebook.com
// @include https://*.facebook.com
// @require lib/jquery.js
// @require lib/dep/bigint.js
// @require lib/dep/crypto.js
// @require lib/dep/eventemitter.js
// @require lib/dep/salsa20.js
// @require lib/otr.js
// ==/UserScript==
console.log("OTR for Facebook loaded.");
console.log(kango);
// execute callback when the page is ready:
$(document).ready(function() {
console.log("doc ready.");
console.log($('.headerTinymanName').text());
var elemChatTabs = $('#ChatTabsPagelet .fbDockChatTabFlyout');
console.log(elemChatTabs.size());
$(elemChatTabs).on('focus', 'textarea', function(e){
console.log('textarea has focus.');
});
$(elemChatTabs).each(function(index) {
console.log(this);
$(this)
.find(".titlebarButtonWrapper")
.prepend('<a tabindex="0" data-hover="tooltip" aria-label="Encrypt" class="encrypticon button" role="button"></a>');
});
});
// Get last saved color number from storage
kango.invokeAsync('kango.storage.getItem', 'myKey', function(key) {
console.log('stored value for myKey is ' + myKey);
});
|
// ==UserScript==
// @name OTR for Facebook
// @include http://*.facebook.com
// @include https://*.facebook.com
// @require lib/jquery.js
// @require lib/dep/bigint.js
// @require lib/dep/crypto.js
// @require lib/dep/eventemitter.js
// @require lib/dep/salsa20.js
// @require lib/otr.js
// ==/UserScript==
console.log("OTR for Facebook loaded.");
console.log(kango);
// execute callback when the page is ready:
$('#ChatTabsPagelet').ready(function() {
console.log("doc ready.");
console.log($('.headerTinymanName').text());
var elemChatTabs = $('#ChatTabsPagelet .fbDockChatTabFlyout');
console.log(elemChatTabs.size());
$(elemChatTabs).on('focus', 'textarea', function(e){
console.log('textarea has focus.');
});
});
// Get last saved color number from storage
kango.invokeAsync('kango.storage.getItem', 'myKey', function(key) {
console.log('stored value for myKey is ' + myKey);
});
|
Add empty onUnload to pass test
|
const simplePreferences = require("sdk/simple-prefs");
const ui = require("./lib/ui");
const preferences = simplePreferences.prefs;
exports.main = function(options) {
console.log("Starting up with reason ", options.loadReason);
// Use a panel because there is no multiline string in simple-prefs
// show and fill on button click in preference
simplePreferences.on("editButton", function() {
ui.panel.show();
});
ui.panel.on("show", function() {
ui.panel.port.emit("show", preferences.items);
});
// save content and hide on save button click
ui.panel.port.on("save", function(text) {
ui.panel.hide();
preferences.items = text;
});
simplePreferences.on("items", function() {
ui.populateSubMenu();
});
ui.populateSubMenu();
};
exports.onUnload = function(reason) {
console.log("Closing down with reason ", reason);
};
|
const simplePreferences = require("sdk/simple-prefs");
const ui = require("./lib/ui");
const preferences = simplePreferences.prefs;
exports.main = function(options) {
console.log("Starting up with reason ", options.loadReason);
// Use a panel because there is no multiline string in simple-prefs
// show and fill on button click in preference
simplePreferences.on("editButton", function() {
ui.panel.show();
});
ui.panel.on("show", function() {
ui.panel.port.emit("show", preferences.items);
});
// save content and hide on save button click
ui.panel.port.on("save", function(text) {
ui.panel.hide();
preferences.items = text;
});
simplePreferences.on("items", function() {
ui.populateSubMenu();
});
ui.populateSubMenu();
};
|
Add doc blocks to service provider.
|
<?php
namespace DigitLab\AdaptiveView;
use DigitLab\AdaptiveView\Browser\AgentBrowserAdapter;
use DigitLab\AdaptiveView\Browser\Browser;
use Illuminate\Support\ServiceProvider;
class AdaptiveViewServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->registerBrowser();
$this->registerViewFinder();
}
/**
* Register the browser implementation.
*
* @return void
*/
public function registerBrowser()
{
$browser = $this->app['config']['view.browser'];
if (!$browser) {
$browser = AgentBrowserAdapter::class;
}
$this->app->bind(Browser::class, $browser);
}
/**
* Register the view finder implementation.
*
* @return void
*/
public function registerViewFinder()
{
$this->app->bind('view.finder', function ($app) {
$browser = $app->make(Browser::class);
$paths = $app['config']['view.paths'];
return new AdaptiveFileViewFinder($browser, $app['files'], $paths);
});
}
}
|
<?php
namespace DigitLab\AdaptiveView;
use DigitLab\AdaptiveView\Browser\AgentBrowserAdapter;
use DigitLab\AdaptiveView\Browser\Browser;
use Illuminate\Support\ServiceProvider;
class AdaptiveViewServiceProvider extends ServiceProvider
{
public function register()
{
$this->registerBrowser();
$this->registerViewFinder();
}
public function registerBrowser()
{
$browser = $this->app['config']['view.browser'];
if (!$browser) {
$browser = AgentBrowserAdapter::class;
}
$this->app->bind(Browser::class, $browser);
}
public function registerViewFinder()
{
$this->app->bind('view.finder', function ($app) {
$browser = $app->make(Browser::class);
$paths = $app['config']['view.paths'];
return new AdaptiveFileViewFinder($browser, $app['files'], $paths);
});
}
}
|
Comment out game render hooks
|
package reborncore.mixin.client;
import net.minecraft.client.render.GameRenderer;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import reborncore.RebornCoreClient;
import reborncore.client.ClientChunkManager;
@Mixin(GameRenderer.class)
public class MixinGameRenderer {
//TODO 1.15 nope
// @Inject(method = "renderCenter", at = @At(value = "INVOKE", target = "net/minecraft/util/profiler/Profiler.swap(Ljava/lang/String;)V", ordinal = 15))
// private void renderCenter(float float_1, long long_1, CallbackInfo info) {
// RebornCoreClient.multiblockRenderEvent.onWorldRenderLast(float_1);
//
// }
//
// @Inject(method = "renderCenter", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/render/debug/DebugRenderer;render(J)V", ordinal = 0))
// private void renderCenter_2(float float_1, long long_1, CallbackInfo info) {
// ClientChunkManager.render();
// }
}
|
package reborncore.mixin.client;
import net.minecraft.client.render.GameRenderer;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import reborncore.RebornCoreClient;
import reborncore.client.ClientChunkManager;
@Mixin(GameRenderer.class)
public class MixinGameRenderer {
@Inject(method = "renderCenter", at = @At(value = "INVOKE", target = "net/minecraft/util/profiler/Profiler.swap(Ljava/lang/String;)V", ordinal = 15))
private void renderCenter(float float_1, long long_1, CallbackInfo info) {
RebornCoreClient.multiblockRenderEvent.onWorldRenderLast(float_1);
}
@Inject(method = "renderCenter", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/render/debug/DebugRenderer;render(J)V", ordinal = 0))
private void renderCenter_2(float float_1, long long_1, CallbackInfo info) {
ClientChunkManager.render();
}
}
|
Make naming consistent with MDN
|
// Third party
import localforage from 'localForage';
import { applyMiddleware, compose, createStore } from 'redux';
import { autoRehydrate, persistStore, purgeStoredState } from 'redux-persist';
import thunk from 'redux-thunk';
// import freeze from 'redux-freeze';
import undoable, { ActionCreators } from 'redux-undo';
import appReducer from 'app-reducer';
const CONFIG = {
storage: localforage,
debounce: 75,
keyPrefix: 'matrixDecompositionMethods.'
};
export default class States {
constructor () {
this.store = createStore(
undoable(appReducer),
undefined,
compose(
autoRehydrate(),
applyMiddleware(thunk),
// applyMiddleware(freeze)
)
);
persistStore(this.store, CONFIG, (err, state) => {
// Rehydration is done
this.isRehydrated = Object.keys(true).length > 0;
});
}
undo () {
this.store.dispatch(ActionCreators.undo());
}
redo () {
this.store.dispatch(ActionCreators.redo());
}
reset () {
return purgeStoredState(CONFIG);
}
}
|
// Third party
import localForage from 'localForage';
import { applyMiddleware, compose, createStore } from 'redux';
import { autoRehydrate, persistStore, purgeStoredState } from 'redux-persist';
import thunk from 'redux-thunk';
// import freeze from 'redux-freeze';
import undoable, { ActionCreators } from 'redux-undo';
import appReducer from 'app-reducer';
const CONFIG = {
storage: localForage,
debounce: 75,
keyPrefix: 'matrixDecompositionMethods.'
};
export default class States {
constructor () {
this.store = createStore(
undoable(appReducer),
undefined,
compose(
autoRehydrate(),
applyMiddleware(thunk),
// applyMiddleware(freeze)
)
);
persistStore(this.store, CONFIG, (err, state) => {
// Rehydration is done
this.isRehydrated = Object.keys(true).length > 0;
});
}
undo () {
this.store.dispatch(ActionCreators.undo());
}
redo () {
this.store.dispatch(ActionCreators.redo());
}
reset () {
return purgeStoredState(CONFIG);
}
}
|
Fix type: emptyProcedute -> emptyProcedure
|
<?php
namespace Retrinko\CottonTail\Message\Payloads;
use Retrinko\CottonTail\Exceptions\PayloadException;
class RpcRequestPayload extends DefaultPayload
{
const KEY_PARAMS = 'params';
const KEY_PROCEDURE = 'procedure';
/**
* @var array
*/
protected $requiredFields = [self::KEY_PROCEDURE, self::KEY_PARAMS];
/**
* @param string $procedure
* @param array $params
*
* @return RpcRequestPayload
* @throws PayloadException
*/
public static function create($procedure, $params = [])
{
if (empty($procedure))
{
throw PayloadException::emptyProcedure();
}
$data = [self::KEY_PROCEDURE => $procedure,
self::KEY_PARAMS => $params];
return new self($data);
}
/**
* @return array
*/
public function getParams()
{
return $this->data[self::KEY_PARAMS];
}
/**
* @return string
*/
public function getProcedure()
{
return $this->data[self::KEY_PROCEDURE];
}
}
|
<?php
namespace Retrinko\CottonTail\Message\Payloads;
use Retrinko\CottonTail\Exceptions\PayloadException;
class RpcRequestPayload extends DefaultPayload
{
const KEY_PARAMS = 'params';
const KEY_PROCEDURE = 'procedure';
/**
* @var array
*/
protected $requiredFields = [self::KEY_PROCEDURE, self::KEY_PARAMS];
/**
* @param string $procedure
* @param array $params
*
* @return RpcRequestPayload
* @throws PayloadException
*/
public static function create($procedure, $params = [])
{
if (empty($procedure))
{
throw PayloadException::emptyProcedute();
}
$data = [self::KEY_PROCEDURE => $procedure,
self::KEY_PARAMS => $params];
return new self($data);
}
/**
* @return array
*/
public function getParams()
{
return $this->data[self::KEY_PARAMS];
}
/**
* @return string
*/
public function getProcedure()
{
return $this->data[self::KEY_PROCEDURE];
}
}
|
Remove @NonNull from a nullable parameter
Slot data can be null: https://wiki.vg/Slot_Data
|
package com.github.steveice10.mc.protocol.packet.ingame.server.window;
import com.github.steveice10.mc.protocol.data.game.entity.metadata.ItemStack;
import com.github.steveice10.packetlib.io.NetInput;
import com.github.steveice10.packetlib.io.NetOutput;
import com.github.steveice10.packetlib.packet.Packet;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.Setter;
import java.io.IOException;
@Data
@Setter(AccessLevel.NONE)
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@AllArgsConstructor
public class ServerSetSlotPacket implements Packet {
private int windowId;
private int slot;
private ItemStack item;
@Override
public void read(NetInput in) throws IOException {
this.windowId = in.readUnsignedByte();
this.slot = in.readShort();
this.item = ItemStack.read(in);
}
@Override
public void write(NetOutput out) throws IOException {
out.writeByte(this.windowId);
out.writeShort(this.slot);
ItemStack.write(out, this.item);
}
@Override
public boolean isPriority() {
return false;
}
}
|
package com.github.steveice10.mc.protocol.packet.ingame.server.window;
import com.github.steveice10.mc.protocol.data.game.entity.metadata.ItemStack;
import com.github.steveice10.packetlib.io.NetInput;
import com.github.steveice10.packetlib.io.NetOutput;
import com.github.steveice10.packetlib.packet.Packet;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.Setter;
import java.io.IOException;
@Data
@Setter(AccessLevel.NONE)
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@AllArgsConstructor
public class ServerSetSlotPacket implements Packet {
private int windowId;
private int slot;
private @NonNull ItemStack item;
@Override
public void read(NetInput in) throws IOException {
this.windowId = in.readUnsignedByte();
this.slot = in.readShort();
this.item = ItemStack.read(in);
}
@Override
public void write(NetOutput out) throws IOException {
out.writeByte(this.windowId);
out.writeShort(this.slot);
ItemStack.write(out, this.item);
}
@Override
public boolean isPriority() {
return false;
}
}
|
Compress images at the proxy
|
<?php
$strFile = rawurldecode(@$_GET['url']);
$strFile_array = explode('.' , $strFile);
$strFileExt = end($strFile_array);
if($strFileExt == 'jpg' or $strFileExt == 'jpeg') {
header('Content-Type: image/jpeg');
} elseif($strFileExt == 'png') {
header('Content-Type: image/png');
} elseif($strFileExt == 'gif') {
header('Content-Type: image/gif');
} else {
die('not supported');
}
if($strFile != ''){
$cache_expire = 60*60*24*365;
header("Pragma: public");
header("Cache-Control: maxage=". $cache_expire);
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $cache_expire).' GMT');
$im = new Imagick($strFile);
$im->thumbnailImage(250,250);
echo $im;
}
exit;
?>
|
<?php
$strFile = rawurldecode(@$_GET['url']);
$strFile_array = explode('.' , $strFile);
$strFileExt = end($strFile_array);
if($strFileExt == 'jpg' or $strFileExt == 'jpeg') {
header('Content-Type: image/jpeg');
} elseif($strFileExt == 'png') {
header('Content-Type: image/png');
} elseif($strFileExt == 'gif') {
header('Content-Type: image/gif');
} else {
die('not supported');
}
if($strFile != ''){
$cache_expire = 60*60*24*365;
header("Pragma: public");
header("Cache-Control: maxage=". $cache_expire);
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $cache_expire).' GMT');
echo file_get_contents($strFile);
}
exit;
?>
|
Fix for empty lines in data sets
|
from typing import List
import csv
import os
import random
DICT_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "dicts")
def dictionary_sample(name: str, sample: int = 1) -> List[str]:
# TODO: Cache counting, and use file.seek to speed file reading.
fname = os.path.join(DICT_DIR, f"{name}.csv")
if not os.path.exists(fname):
raise ValueError(f"{name} dictionary does not exists.")
with open(fname, "rt") as csvfile:
csvreader = csv.DictReader(
csvfile, fieldnames=["NAME"], delimiter=",", quotechar='"'
)
names = [row["NAME"] for row in csvreader if row["NAME"].strip() != ""]
return random.sample(names, sample)
def generate_codenames(
prefix: str = "adjectives",
suffix: str = "mobi_notable_scientists_and_hackers",
num: int = 1,
) -> List[str]:
prefixes = dictionary_sample(prefix, num)
suffixes = dictionary_sample(suffix, num)
return [f"{prefix} {suffix}" for prefix, suffix in zip(prefixes, suffixes)]
|
from typing import List
import csv
import os
import random
DICT_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "dicts")
def dictionary_sample(name: str, sample: int = 1) -> List[str]:
# TODO: Cache counting, and use file.seek to speed file reading.
fname = os.path.join(DICT_DIR, f"{name}.csv")
if not os.path.exists(fname):
raise ValueError(f"{name} dictionary does not exists.")
with open(fname, "rt") as csvfile:
csvreader = csv.DictReader(
csvfile, fieldnames=["NAME"], delimiter=",", quotechar='"'
)
names = [row["NAME"] for row in csvreader]
return random.sample(names, sample)
def generate_codenames(
prefix: str = "adjectives",
suffix: str = "mobi_notable_scientists_and_hackers",
num: int = 1,
) -> List[str]:
prefixes = dictionary_sample(prefix, num)
suffixes = dictionary_sample(suffix, num)
return [f"{prefix} {suffix}" for prefix, suffix in zip(prefixes, suffixes)]
|
Remove semicolon to match lint guidelines
|
const isTouch = (('ontouchstart' in window) || (navigator.msMaxTouchPoints > 0))
const event = isTouch ? 'touchstart' : 'click'
const directive = {
instances: []
}
directive.onEvent = function (event) {
directive.instances.forEach(({ el, fn }) => {
if (event.target !== el && !el.contains(event.target)) {
fn && fn(event)
}
})
}
directive.bind = function (el) {
directive.instances.push({ el, fn: null })
if (directive.instances.length === 1) {
document.addEventListener(event, directive.onEvent)
}
}
directive.update = function (el, binding) {
if (typeof binding.value !== 'function') {
throw new Error('Argument must be a function')
}
const instance = directive.instances.find(i => i.el === el)
instance.fn = binding.value
}
directive.unbind = function (el) {
const instanceIndex = directive.instances.findIndex(i => i.el === el)
directive.instances.splice(instanceIndex, 1)
if (directive.instances.length === 0) {
document.removeEventListener(event, directive.onEvent)
}
}
export default directive
|
const isTouch = (('ontouchstart' in window) || (navigator.msMaxTouchPoints > 0));
const event = isTouch ? 'touchstart' : 'click'
const directive = {
instances: []
}
directive.onEvent = function (event) {
directive.instances.forEach(({ el, fn }) => {
if (event.target !== el && !el.contains(event.target)) {
fn && fn(event)
}
})
}
directive.bind = function (el) {
directive.instances.push({ el, fn: null })
if (directive.instances.length === 1) {
document.addEventListener(event, directive.onEvent)
}
}
directive.update = function (el, binding) {
if (typeof binding.value !== 'function') {
throw new Error('Argument must be a function')
}
const instance = directive.instances.find(i => i.el === el)
instance.fn = binding.value
}
directive.unbind = function (el) {
const instanceIndex = directive.instances.findIndex(i => i.el === el)
directive.instances.splice(instanceIndex, 1)
if (directive.instances.length === 0) {
document.removeEventListener(event, directive.onEvent)
}
}
export default directive
|
Update: Add relevant notes and documentation to addInfoToCSVReport.py
|
#!/usr/bin/env python3
from csv import reader
from sys import stdin
from xmlrpc.client import ServerProxy
from ssl import create_default_context, Purpose
# Script to add user account notes to account_configurations.csv
host="https://localhost:9192/rpc/api/xmlrpc" # If not localhost then this address will need to be whitelisted in PaperCut
auth="token" # Value defined in advanced config property "auth.webservices.auth-token". Should be random
proxy = ServerProxy(host, verbose=False,
context = create_default_context(Purpose.CLIENT_AUTH))#Create new ServerProxy Instance
# #TODO open and manipulate CSV
csv_reader = reader(stdin, delimiter=',') #Read in standard data
line_count = 0
for row in csv_reader:
if line_count == 1: #Header row
row.insert(4,"Notes data")
elif line_count > 2:
row.insert(4,proxy.api.getSharedAccountProperty(auth, row[0] + "\\" + row[2], "notes")) #Add Note data for shared account(Parent or child)
print(", ".join(row))
line_count += 1
|
#!/usr/bin/env python3
from csv import reader
from sys import stdin
from xmlrpc.client import ServerProxy
from ssl import create_default_context, Purpose
# #TODO Add a note about which report this example works with.
host="https://localhost:9192/rpc/api/xmlrpc" # If not localhost then this address will need to be whitelisted in PaperCut
auth="token" # Value defined in advanced config property "auth.webservices.auth-token". Should be random
proxy = ServerProxy(host, verbose=False,
context = create_default_context(Purpose.CLIENT_AUTH))
csv_reader = reader(stdin, delimiter=',')
line_count = 0
for row in csv_reader:
if line_count == 2:
row.insert(4,"Notes data")
elif line_count > 2:
row.insert(4,proxy.api.getSharedAccountProperty(auth, row[0] + "\\" + row[2], "notes"))
print(", ".join(row))
line_count += 1
|
Add isRunning method to Job
|
var util = require('util');
var _ = require('underscore');
var EventEmitter = require('events').EventEmitter;
var PulsarJob = require('../node_modules/pulsar-rest-api/lib/pulsar/job');
/**
* @param {String} app
* @param {String} env
* @param {String} task
* @param {Object.<String, String>} [taskVariables]
* @constructor
*/
function Job(app, env, task, taskVariables) {
this.app = app;
this.env = env;
this.task = task;
this.taskVariables = taskVariables;
this.data = {};
EventEmitter.call(this);
}
util.inherits(Job, EventEmitter);
/**
* @param {Object} jobData
* @returns {Object} new merged Job's data
*/
Job.prototype.setData = function(jobData) {
return _.extend(this.data, jobData);
};
Job.prototype.isRunning = function() {
return this.data.status == PulsarJob.STATUS.RUNNING;
};
Job.prototype.toString = function() {
var result = util.format('%s "%s" to "%s"', this.task, this.app, this.env);
if (this.data.id) {
result += ' id: ' + this.data.id;
}
return result;
};
module.exports = Job;
|
var util = require('util');
var _ = require('underscore');
var EventEmitter = require('events').EventEmitter;
/**
* @param {String} app
* @param {String} env
* @param {String} task
* @param {Object.<String, String>} [taskVariables]
* @constructor
*/
function Job(app, env, task, taskVariables) {
this.app = app;
this.env = env;
this.task = task;
this.taskVariables = taskVariables;
this.data = {};
EventEmitter.call(this);
}
util.inherits(Job, EventEmitter);
/**
* @param {Object} jobData
* @returns {Object} new merged Job's data
*/
Job.prototype.setData = function(jobData) {
return _.extend(this.data, jobData);
};
Job.prototype.toString = function() {
var result = util.format('%s "%s" to "%s"', this.task, this.app, this.env);
if (this.data.id) {
result += ' id: ' + this.data.id;
}
return result;
};
module.exports = Job;
|
Allow fetching notifications by user
|
<?php
class Notification extends Eloquent {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'radio_notifications';
/**
* Should deleted_at be used
*
* @var bool
*/
protected $softDelete = true;
// allow mass-assignment
protected $fillable = ["notification", "privileges"];
public static function generate($notification, $level) {
return static::create([
"privileges" => $level,
"notification" => $notification,
]);
}
public static function dev($notification) {
return static::generate($notification, User::DEV);
}
public static function pending($notification) {
return static::generate($notification, User::PENDING);
}
public static function admin($notification) {
return static::generate($notification, User::ADMIN);
}
public static function news($notification) {
return static::generate($notification, User::NEWS);
}
public static function dj($notification) {
return static::generate($notification, User::DJ);
}
public static function fetch(User $user) {
return static::where("privileges", "<", (int) $user->privileges + 1)->orderBy("created_at", "desc")->get();
}
public function toArray() {
$array = parent::toArray();
$array["notification"] = Markdown::render($array["notification"]);
return $array;
}
}
|
<?php
class Notification extends Eloquent {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'radio_notifications';
/**
* Should deleted_at be used
*
* @var bool
*/
protected $softDeletes = true;
// allow mass-assignment
protected $fillable = ["notification", "privileges"];
public static function generate($notification, $level) {
return static::create([
"privileges" => $level,
"notification" => $notification,
]);
}
public static function dev($notification) {
return static::generate($notification, User::DEV);
}
public static function pending($notification) {
return static::generate($notification, User::PENDING);
}
public static function admin($notification) {
return static::generate($notification, User::ADMIN);
}
public static function news($notification) {
return static::generate($notification, User::NEWS);
}
public static function dj($notification) {
return static::generate($notification, User::DJ);
}
public function toArray() {
$array = parent::toArray();
$array["notification"] = Markdown::render($array["notification"]);
return $array;
}
}
|
Fix Jest call in the release script
Just running jest binary will no longer work
|
#!/usr/bin/env node
'use strict';
const chalk = require('chalk');
const {exec} = require('child-process-promise');
const {logPromise} = require('../utils');
const runYarnTask = async (cwd, task, errorMessage) => {
try {
await exec(`yarn ${task}`, {cwd});
} catch (error) {
throw Error(
chalk`
${errorMessage}
{white ${error.stdout}}
`
);
}
};
module.exports = async ({cwd}) => {
await logPromise(runYarnTask(cwd, 'lint', 'Lint failed'), 'Running ESLint');
await logPromise(
runYarnTask(cwd, 'flow', 'Flow failed'),
'Running Flow checks'
);
await logPromise(
runYarnTask(cwd, 'test', 'Jest failed'),
'Running Jest tests',
true
);
};
|
#!/usr/bin/env node
'use strict';
const chalk = require('chalk');
const {exec} = require('child-process-promise');
const {logPromise} = require('../utils');
const runYarnTask = async (cwd, task, errorMessage) => {
try {
await exec(`yarn ${task}`, {cwd});
} catch (error) {
throw Error(
chalk`
${errorMessage}
{white ${error.stdout}}
`
);
}
};
module.exports = async ({cwd}) => {
await logPromise(runYarnTask(cwd, 'lint', 'Lint failed'), 'Running ESLint');
await logPromise(
runYarnTask(cwd, 'flow', 'Flow failed'),
'Running Flow checks'
);
await logPromise(
runYarnTask(cwd, 'jest', 'Jest failed'),
'Running Jest tests',
true
);
};
|
Add missing return statement to model user
|
const mongo = require('../db')
const utils = require('../utils')
const crypto = require('crypto')
/**
* User :: {
* id: String,
* username: String,
* password: String,
* createdAt: String
* }
*/
/** String -> String -> User */
function createUser(username, password) {
return {
"id": utils.UUID(),
"username": username,
"password": crypto.createHmac('sha256', password).update(password).digest('base64'),
"createdAt": Date.now()
}
}
/** String -> Promise(Boolean, Error) */
function userExist(username) {
return mongo.connect()
.then(db => db.collection('users').findOne({ username })
.then(mongo.close(db)))
.then(user => user != null)
}
/** User -> Promise(User, Error) */
function saveUser(user) {
return mongo.connect()
.then(db => db.collection('users').insertOne(user)
.then(mongo.close(db)))
.then(() => user)
}
/** String -> String -> Promise({id, username, token : String}, Error) */
exports.register = function register(username, password) {
return userExist(username)
.then(exist => exist ?
Promise.reject("The user already exist") :
Promise.resolve(createUser(username, password)))
.then(saveUser)
}
|
const mongo = require('../db')
const utils = require('../utils')
const crypto = require('crypto')
/**
* User :: {
* id: String,
* username: String,
* password: String,
* createdAt: String
* }
*/
/** String -> String -> User */
function createUser(username, password) {
return {
"id": utils.UUID(),
"username": username,
"password": crypto.createHmac('sha256', password).update(password).digest('base64'),
"createdAt": Date.now()
}
}
/** String -> Promise(Boolean, Error) */
function userExist(username) {
return mongo.connect()
.then(db => db.collection('users').findOne({ username })
.then(mongo.close(db)))
.then(user => user != null)
}
/** User -> Promise(User, Error) */
function saveUser(user) {
return mongo.connect()
.then(db => db.collection('users').insertOne(user)
.then(mongo.close(db)))
.then(() => user)
}
/** String -> String -> Promise({id, username, token : String}, Error) */
exports.register = function register(username, password) {
userExist(username)
.then(exist => exist ?
Promise.reject("The user already exist") :
Promise.resolve(createUser(username, password)))
.then(saveUser)
}
|
Fix implicit flow athorization denied redirect
|
<?php
namespace Laravel\Passport\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Contracts\Routing\ResponseFactory;
class DenyAuthorizationController
{
use RetrievesAuthRequestFromSession;
/**
* The response factory implementation.
*
* @var ResponseFactory
*/
protected $response;
/**
* Create a new controller instance.
*
* @param ResponseFactory $response
* @return void
*/
public function __construct(ResponseFactory $response)
{
$this->response = $response;
}
/**
* Deny the authorization request.
*
* @param Request $request
* @return Response
*/
public function deny(Request $request)
{
$authRequest = $this->getAuthRequestFromSession($request);
$authRequest->getClient()->getRedirectUri();
$separator = $authRequest->getGrantTypeId() === 'implicit' ? '#' : '?';
return $this->response->redirectTo(
$redirect.$separator.'error=access_denied&state='.$request->input('state')
);
}
}
|
<?php
namespace Laravel\Passport\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Contracts\Routing\ResponseFactory;
class DenyAuthorizationController
{
use RetrievesAuthRequestFromSession;
/**
* The response factory implementation.
*
* @var ResponseFactory
*/
protected $response;
/**
* Create a new controller instance.
*
* @param ResponseFactory $response
* @return void
*/
public function __construct(ResponseFactory $response)
{
$this->response = $response;
}
/**
* Deny the authorization request.
*
* @param Request $request
* @return Response
*/
public function deny(Request $request)
{
$redirect = $this->getAuthRequestFromSession($request)
->getClient()->getRedirectUri();
return $this->response->redirectTo(
$redirect.'?error=access_denied&state='.$request->input('state')
);
}
}
|
Fix migration for older mysql versions that do not support default values on blob/text columns
|
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddMessageIdToSentEmailsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('sent_emails', function(Blueprint $table) {
$table->string('message_id')->nullable();
$table->text('meta');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('sent_emails', function(Blueprint $table) {
$table->dropColumn('message_id');
$table->dropColumn('meta');
});
}
}
|
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddMessageIdToSentEmailsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('sent_emails', function(Blueprint $table) {
$table->string('message_id')->nullable();
$table->text('meta')->default('[]');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('sent_emails', function(Blueprint $table) {
$table->dropColumn('message_id');
$table->dropColumn('meta');
});
}
}
|
Migrate away from deprecated behavior annotation
PiperOrigin-RevId: 271439031
|
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.material.testapp.custom;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatTextView;
import android.util.AttributeSet;
import android.widget.TextView;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
/**
* Custom extension of AppCompat's text view for testing a runtime-specified behavior.
*/
public class CustomTextView extends AppCompatTextView
implements CoordinatorLayout.AttachedBehavior {
public CustomTextView(Context context) {
super(context);
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
@NonNull
public CoordinatorLayout.Behavior<TextView> getBehavior() {
return new TestFloatingBehavior();
}
}
|
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.material.testapp.custom;
import android.content.Context;
import androidx.appcompat.widget.AppCompatTextView;
import android.util.AttributeSet;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
@CoordinatorLayout.DefaultBehavior(TestFloatingBehavior.class)
public class CustomTextView extends AppCompatTextView {
public CustomTextView(Context context) {
super(context);
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
}
|
Disable wavefront for tests that include scdf-core but don't apply the DefaultEnvironmentPostProcessor
|
/*
* Copyright 2017-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.dataflow.composedtaskrunner.configuration;
import org.springframework.boot.actuate.autoconfigure.metrics.export.wavefront.WavefrontMetricsExportAutoConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cloud.dataflow.rest.client.TaskOperations;
import org.springframework.cloud.dataflow.rest.client.config.DataFlowClientAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.TestPropertySource;
import static org.mockito.Mockito.mock;
/**
* @author Glenn Renfro
*/
@Configuration
@EnableAutoConfiguration(exclude = { DataFlowClientAutoConfiguration.class, WavefrontMetricsExportAutoConfiguration.class })
public class DataFlowTestConfiguration {
@Bean
public TaskOperations taskOperations() {
return mock(TaskOperations.class);
}
}
|
/*
* Copyright 2017-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.dataflow.composedtaskrunner.configuration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cloud.dataflow.rest.client.TaskOperations;
import org.springframework.cloud.dataflow.rest.client.config.DataFlowClientAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import static org.mockito.Mockito.mock;
/**
* @author Glenn Renfro
*/
@Configuration
@EnableAutoConfiguration(exclude = DataFlowClientAutoConfiguration.class)
public class DataFlowTestConfiguration {
@Bean
public TaskOperations taskOperations() {
return mock(TaskOperations.class);
}
}
|
Add description to hook generator
|
import { Base } from 'yeoman-generator';
import generatorArguments from './arguments';
import generatorOptions from './options';
import generatorSteps from './steps';
export default class HookGenerator extends Base {
constructor(...args) {
super(...args);
Object.keys(generatorArguments).forEach(key => this.argument(key, generatorArguments[key]));
Object.keys(generatorOptions).forEach(key => this.option(key, generatorOptions[key]));
this.description = 'Scaffold a custom hook in api/hooks';
}
get configuring() {
return generatorSteps.configuring;
}
get conflicts() {
return generatorSteps.conflicts;
}
get default() {
return generatorSteps.default;
}
get end() {
return generatorSteps.end;
}
get initializing() {
return generatorSteps.initializing
}
get install() {
return generatorSteps.install;
}
get prompting() {
return generatorSteps.prompting
}
get writing() {
return generatorSteps.writing;
}
}
|
import { Base } from 'yeoman-generator';
import generatorArguments from './arguments';
import generatorOptions from './options';
import generatorSteps from './steps';
export default class HookGenerator extends Base {
constructor(...args) {
super(...args);
Object.keys(generatorArguments).forEach(key => this.argument(key, generatorArguments[key]));
Object.keys(generatorOptions).forEach(key => this.option(key, generatorOptions[key]));
}
get configuring() {
return generatorSteps.configuring;
}
get conflicts() {
return generatorSteps.conflicts;
}
get default() {
return generatorSteps.default;
}
get end() {
return generatorSteps.end;
}
get initializing() {
return generatorSteps.initializing
}
get install() {
return generatorSteps.install;
}
get prompting() {
return generatorSteps.prompting
}
get writing() {
return generatorSteps.writing;
}
}
|
Use ArrayCache for integration tests
|
<?php
namespace Radebatz\ACache\Tests\Decorators\Psr;
use Cache\IntegrationTests\CachePoolTest;
use Radebatz\ACache\ArrayCache;
use Radebatz\ACache\Decorators\Psr\CacheItemPool;
if (version_compare(phpversion(), '5.4.0', 'ge') && class_exists('\Cache\IntegrationTests\CachePoolTest')) {
/**
* Additional Psr integration tests.
*/
class IntegrationTest extends CachePoolTest
{
/*
* {@inheritdoc}
*/
public function createCachePool()
{
return new CacheItemPool(new ArrayCache(array(), true));
}
}
} else {
/**
* Dummy Psr integration tests.
*/
class IntegrationTest extends \PHPUnit_Framework_TestCase
{
public function testDummy()
{
$this->assertTrue(true);
}
}
}
|
<?php
namespace Radebatz\ACache\Tests\Decorators\Psr;
use Cache\IntegrationTests\CachePoolTest;
use Radebatz\ACache\ApcCache;
use Radebatz\ACache\ArrayCache;
use Radebatz\ACache\Decorators\Psr\CacheItemPool;
if (version_compare(phpversion(), '5.4.0', 'ge') && class_exists('\Cache\IntegrationTests\CachePoolTest')) {
/**
* Additional Psr integration tests.
*/
class IntegrationTest extends CachePoolTest
{
/*
* {@inheritdoc}
*/
public function createCachePool()
{
return new CacheItemPool(new ApcCache());
return new CacheItemPool(new ArrayCache());
}
}
} else {
/**
* Dummy Psr integration tests.
*/
class IntegrationTest extends \PHPUnit_Framework_TestCase
{
public function testDummy()
{
$this->assertTrue(true);
}
}
}
|
Convert css class of PasswordInput widget
|
from django import template
register = template.Library()
class_converter = {
"textinput":"textinput textInput",
"fileinput":"fileinput fileUpload",
"passwordinput":"textinput textInput",
>>>>>>> f85af74... Convert css class of PasswordInput widget:uni_form/templatetags/uni_form_field.py
}
@register.filter
def is_checkbox(field):
return field.field.widget.__class__.__name__.lower() == "checkboxinput"
@register.filter
def with_class(field):
class_name = field.field.widget.__class__.__name__.lower()
class_name = class_converter.get(class_name, class_name)
if "class" in field.field.widget.attrs:
css_class = field.field.widget.attrs['class']
if field.field.widget.attrs['class'].find(class_name) == -1:
css_class += " %s" % (class_name,)
else:
css_class = class_name
return field.as_widget(attrs={'class': css_class})
|
from django import template
register = template.Library()
class_converter = {
"textinput":"textinput textInput",
"fileinput":"fileinput fileUpload",
"passwordinput":"passwordinput textInput"
}
@register.filter
def is_checkbox(field):
return field.field.widget.__class__.__name__.lower() == "checkboxinput"
@register.filter
def with_class(field):
class_name = field.field.widget.__class__.__name__.lower()
class_name = class_converter.get(class_name, class_name)
if "class" in field.field.widget.attrs:
css_class = field.field.widget.attrs['class']
if field.field.widget.attrs['class'].find(class_name) == -1:
css_class += " %s" % (class_name,)
else:
css_class = class_name
return field.as_widget(attrs={'class': css_class})
|
Fix double running of shell commands.
|
<?php
namespace App;
use Illuminate\Config\Repository;
use Symfony\Component\Process\Process;
class Shell
{
protected $rootPath;
protected $projectPath;
protected $hideOutput;
public function __construct(Repository $config)
{
$this->rootPath = $config->get('lambo.store.root_path');
$this->projectPath = $config->get('lambo.store.project_path');
$this->hideOutput = $config->get('lambo.store.quiet-shell');
}
public function execInRoot($command)
{
return $this->exec("cd {$this->rootPath} && $command");
}
public function execInProject($command)
{
return $this->exec("cd {$this->projectPath} && $command");
}
protected function exec($command)
{
$process = app()->make(Process::class, [
'command' => $command,
]);
$process->setTimeout(null);
$process->disableOutput();
$hideOutput = $this->hideOutput;
// @todo resolve this
$process->run(function ($type, $buffer) use ($hideOutput) {
if (! $hideOutput) {
echo $buffer;
}
});
}
}
|
<?php
namespace App;
use Illuminate\Config\Repository;
use Symfony\Component\Process\Process;
class Shell
{
protected $rootPath;
protected $projectPath;
protected $hideOutput;
public function __construct(Repository $config)
{
$this->rootPath = $config->get('lambo.store.root_path');
$this->projectPath = $config->get('lambo.store.project_path');
$this->hideOutput = $config->get('lambo.store.quiet-shell');
}
public function execInRoot($command)
{
return $this->exec("cd {$this->rootPath} && $command");
}
public function execInProject($command)
{
return $this->exec("cd {$this->projectPath} && $command");
}
protected function exec($command)
{
$process = app()->make(Process::class, [
'command' => $command,
]);
$process->setTimeout(null);
$process->disableOutput();
$process->run();
$hideOutput = $this->hideOutput;
// @todo resolve this
$process->run(function ($type, $buffer) use ($hideOutput) {
if (! $hideOutput) {
echo $buffer;
}
});
}
}
|
MMLC-137: Set an explicit log level on live.
|
/**
* Production environment settings
*
* This file can include shared settings for a production environment,
* such as API keys or remote database passwords. If you're using
* a version control solution for your Sails app, this file will
* be committed to your repository unless you add it to your .gitignore
* file. If your repository will be publicly viewable, don't add
* any private information to this file!
*
*/
module.exports = {
/***************************************************************************
* Set the default database connection for models in the production *
* environment (see config/connections.js and config/models.js ) *
***************************************************************************/
models: {
connection: 'productionMongodbServer'
},
/***************************************************************************
* Set the port *
***************************************************************************/
port: 80,
/***************************************************************************
* Set the log level *
***************************************************************************/
log: {
level: "warn"
}
};
|
/**
* Production environment settings
*
* This file can include shared settings for a production environment,
* such as API keys or remote database passwords. If you're using
* a version control solution for your Sails app, this file will
* be committed to your repository unless you add it to your .gitignore
* file. If your repository will be publicly viewable, don't add
* any private information to this file!
*
*/
module.exports = {
/***************************************************************************
* Set the default database connection for models in the production *
* environment (see config/connections.js and config/models.js ) *
***************************************************************************/
models: {
connection: 'productionMongodbServer'
},
/***************************************************************************
* Set the port in the production environment to 80 *
***************************************************************************/
port: 80,
/***************************************************************************
* Set the log level in production environment to "silent" *
***************************************************************************/
// log: {
// level: "silent"
// }
};
|
Remove no longer needed Ember import
|
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr('string'),
annotation: DS.attr('string'),
createdAt: DS.attr('date'),
updatedAt: DS.attr('date'),
courses: DS.hasMany('course', {async: true}),
objectives: DS.hasMany('objectives', {async: true}),
sessions: DS.hasMany('session', {async: true}),
concepts: DS.hasMany('mesh-concept', {async: true}),
qualifiers: DS.hasMany('mesh-qualifier', {async: true}),
trees: DS.hasMany('mesh-tree', {async: true}),
sessionLearningMaterials: DS.hasMany('session-learning-material', {async: true}),
courseLearningMaterials: DS.hasMany('course-learning-material', {async: true}),
previousIndexing: DS.belongsTo('mesh-previous-indexing', {async: true}),
});
|
import Ember from 'ember';
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr('string'),
annotation: DS.attr('string'),
createdAt: DS.attr('date'),
updatedAt: DS.attr('date'),
courses: DS.hasMany('course', {async: true}),
objectives: DS.hasMany('objectives', {async: true}),
sessions: DS.hasMany('session', {async: true}),
concepts: DS.hasMany('mesh-concept', {async: true}),
qualifiers: DS.hasMany('mesh-qualifier', {async: true}),
trees: DS.hasMany('mesh-tree', {async: true}),
sessionLearningMaterials: DS.hasMany('session-learning-material', {async: true}),
courseLearningMaterials: DS.hasMany('course-learning-material', {async: true}),
previousIndexing: DS.belongsTo('mesh-previous-indexing', {async: true}),
});
|
Add postfix for subprocess metric
|
import asyncio
from . import Agent
from asyncio.subprocess import PIPE
class SubprocessAgent(Agent):
@property
def script(self):
return self._data["script"]
def is_valid(self):
return "script" in self._data
async def process(self, event_fn):
logger = self.get_logger()
proc = await asyncio.create_subprocess_shell(self.script)
exitcode = await proc.wait()
state = "ok" if exitcode == 0 else "failure"
event_fn(service=self.prefix + "shell",
state=state,
metric_f=1.0,
description="Exit code: {0}".format(exitcode)
)
|
import asyncio
from . import Agent
from asyncio.subprocess import PIPE
class SubprocessAgent(Agent):
@property
def script(self):
return self._data["script"]
def is_valid(self):
return "script" in self._data
async def process(self, event_fn):
logger = self.get_logger()
proc = await asyncio.create_subprocess_shell(self.script)
exitcode = await proc.wait()
state = "ok" if exitcode == 0 else "failure"
event_fn(service=self.prefix,
state=state,
metric_f=1.0,
description="Exit code: {0}".format(exitcode)
)
|
Add default message to URI validator
|
/*
* Copyright 2020 Global Biodiversity Information Facility (GBIF)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gbif.api.util;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
/**
* Validates that the URI field is absolute, beginning with either http or https.
* To use, apply to the URI fields intended for validation.
* The field must be:
* <ul>
* <li>A URI object</li>
* </ul>
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD})
@Constraint(validatedBy = URIValidator.class)
public @interface HttpURI {
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String message() default "Invalid URI";
}
|
/*
* Copyright 2020 Global Biodiversity Information Facility (GBIF)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gbif.api.util;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
/**
* Validates that the URI field is absolute, beginning with either http or https.
* To use, apply to the URI fields intended for validation.
* The field must be:
* <ul>
* <li>A URI object</li>
* </ul>
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD})
@Constraint(validatedBy = URIValidator.class)
public @interface HttpURI {
public abstract Class<?>[] groups() default {};
public abstract Class<? extends Payload>[] payload() default { };
public abstract String message() default "";
}
|
Remove all use of python-future package due to a bug which prevents the IPython notebook interrupt the program
|
# try:
# from future.builtins import *
# except ImportError:
# pass
try:
input = raw_input
range = xrange
except NameError:
pass
try:
string_types = basestring
except NameError:
string_types = str
# This handles pprint always returns string witout ' prefix
# important when running doctest in both python 2 og python 2
import pprint as _pprint
class MyPrettyPrinter(_pprint.PrettyPrinter):
def format(self, object, context, maxlevels, level):
try:
if isinstance(object, unicode):
rep = u"'" + object + u"'"
return ( rep.encode('utf8'), True, False)
except NameError:
pass
return _pprint.PrettyPrinter.format(self, object, context, maxlevels, level)
def py3k_pprint(s):
printer = MyPrettyPrinter(width = 110)
printer.pprint(s)
|
try:
from future_builtins import *
except ImportError:
pass
try:
input = raw_input
range = xrange
except NameError:
pass
try:
string_types = basestring
except NameError:
string_types = str
# This handles pprint always returns string witout ' prefix
# important when running doctest in both python 2 og python 2
import pprint as _pprint
class MyPrettyPrinter(_pprint.PrettyPrinter):
def format(self, object, context, maxlevels, level):
try:
if isinstance(object, unicode):
rep = u"'" + object + u"'"
return ( rep.encode('utf8'), True, False)
except NameError:
pass
return _pprint.PrettyPrinter.format(self, object, context, maxlevels, level)
def py3k_pprint(s):
printer = MyPrettyPrinter(width = 110)
printer.pprint(s)
|
Test the doc comments in the expressions module.
|
'''Search all our doc comments for "Example" blocks and try executing them.'''
import re
import sourcer.expressions
def run_examples(package):
pattern = re.compile(r'''
(\s*) # initial indent
Example # magic keyword
([^\n]*) # optional description
\:\: # magic marker
# Each line of the example is indented
# by four additional spaces:
(\n((\1\ \ \ \ .*)?\n)+)
''',
re.IGNORECASE | re.VERBOSE
)
for k, v in package.__dict__.iteritems():
if k.startswith('__') and k.endswith('__'):
continue
doc = getattr(v, '__doc__') or ''
for m in pattern.finditer(doc):
indent = '\n ' + m.group(1)
body = m.group(3)
example = body.replace(indent, '\n')
print ' Running', k, 'example', m.group(2).strip()
exec example in {}
if __name__ == '__main__':
run_examples(sourcer.expressions)
|
'''Search all our doc comments for "Example" blocks and try executing them.'''
import re
import sourcer
def run_examples(package):
pattern = re.compile(r'''
(\s*) # initial indent
Example # magic keyword
([^\n]*) # optional description
\:\: # magic marker
# Each line of the example is indented
# by four additional spaces:
(\n((\1\ \ \ \ .*)?\n)+)
''',
re.IGNORECASE | re.VERBOSE
)
for k, v in package.__dict__.iteritems():
if k.startswith('__') and k.endswith('__'):
continue
doc = getattr(v, '__doc__') or ''
for m in pattern.finditer(doc):
indent = '\n ' + m.group(1)
body = m.group(3)
example = body.replace(indent, '\n')
print ' Running', k, 'example', m.group(2).strip()
exec example in {}
if __name__ == '__main__':
run_examples(sourcer)
|
FIX failure to pass location
|
import React from 'react';
import { Preview } from '@storybook/components';
import memoize from 'memoizerific';
import { Consumer } from '../core/context';
const createPreviewActions = memoize(1)(api => ({
toggleFullscreen: () => api.toggleFullscreen(),
}));
const createProps = (api, layout, location, path, storyId, viewMode) => ({
api,
getElements: api.getElements,
actions: createPreviewActions(api),
options: layout,
location,
path,
storyId,
viewMode,
});
const PreviewConnected = React.memo(props => (
<Consumer>
{({ state, api }) => (
<Preview
{...props}
{...createProps(
api,
state.layout,
state.location,
state.path,
state.storyId,
state.viewMode
)}
/>
)}
</Consumer>
));
PreviewConnected.displayName = 'PreviewConnected';
export default PreviewConnected;
|
import React from 'react';
import { Preview } from '@storybook/components';
import memoize from 'memoizerific';
import { Consumer } from '../core/context';
const createPreviewActions = memoize(1)(api => ({
toggleFullscreen: () => api.toggleFullscreen(),
}));
const createProps = (api, layout, location, path, storyId, viewMode) => ({
api,
getElements: api.getElements,
actions: createPreviewActions(api),
options: layout,
path,
storyId,
viewMode,
});
const PreviewConnected = React.memo(props => (
<Consumer>
{({ state, api }) => (
<Preview
{...props}
{...createProps(
api,
state.layout,
state.location,
state.path,
state.storyId,
state.viewMode
)}
/>
)}
</Consumer>
));
PreviewConnected.displayName = 'PreviewConnected';
export default PreviewConnected;
|
Allow address to be null
|
import uuid
from django.db import models
from django.contrib.auth.models import User
from opencivicdata.models.people_orgs import Person
class Preferences(models.Model):
user = models.OneToOneField(User, related_name='preferences')
address = models.CharField(max_length=100, blank=True, null=True)
lat = models.FloatField(null=True, blank=True)
lon = models.FloatField(null=True, blank=True)
apikey = models.UUIDField(default=uuid.uuid4)
class PersonFollow(models.Model):
user = models.ForeignKey(User, related_name='person_follows')
person = models.ForeignKey(Person, related_name='follows')
class TopicFollow(models.Model):
user = models.ForeignKey(User, related_name='topic_follows')
topic = models.CharField(max_length=100)
class LocationFollow(models.Model):
user = models.ForeignKey(User, related_name='location_follows')
location = models.CharField(max_length=100)
|
import uuid
from django.db import models
from django.contrib.auth.models import User
from opencivicdata.models.people_orgs import Person
from django.contrib.auth.models import User
class Preferences(models.Model):
user = models.OneToOneField(User, related_name='preferences')
address = models.CharField(max_length=100, blank=True)
lat = models.FloatField(null=True, blank=True)
lon = models.FloatField(null=True, blank=True)
apikey = models.UUIDField(default=uuid.uuid4)
class PersonFollow(models.Model):
user = models.ForeignKey(User, related_name='person_follows')
person = models.ForeignKey(Person, related_name='follows')
class TopicFollow(models.Model):
user = models.ForeignKey(User, related_name='topic_follows')
topic = models.CharField(max_length=100)
class LocationFollow(models.Model):
user = models.ForeignKey(User, related_name='location_follows')
location = models.CharField(max_length=100)
|
Fix eslint issue when running unit tests
|
import Vue from 'vue'{{#if_eq lintConfig "airbnb"}};{{/if_eq}}
Vue.config.productionTip = false{{#if_eq lintConfig "airbnb"}};{{/if_eq}}
// Polyfill fn.bind() for PhantomJS
/* eslint-disable no-extend-native */
Function.prototype.bind = require('function-bind'){{#if_eq lintConfig "airbnb"}};{{/if_eq}}
// require all test files (files that ends with .spec.js)
const testsContext = require.context('./specs', true, /\.spec$/){{#if_eq lintConfig "airbnb"}};{{/if_eq}}
testsContext.keys().forEach(testsContext){{#if_eq lintConfig "airbnb"}};{{/if_eq}}
// require all src files except main.js for coverage.
// you can also change this to match only the subset of files that
// you want coverage for.
const srcContext = require.context('../../src', true, /^\.\/(?!main(\.js)?$)/){{#if_eq lintConfig "airbnb"}};{{/if_eq}}
srcContext.keys().forEach(srcContext){{#if_eq lintConfig "airbnb"}};{{/if_eq}}
|
import Vue from 'vue'{{#if_eq lintConfig "airbnb"}};{{/if_eq}}
Vue.config.productionTip = false{{#if_eq lintConfig "airbnb"}};{{/if_eq}}
// Polyfill fn.bind() for PhantomJS
/* eslint-disable no-extend-native */
Function.prototype.bind = require('function-bind'){{#if_eq lintConfig "airbnb"}};{{/if_eq}}
// require all test files (files that ends with .spec.js)
const testsContext = require.context('./specs', true, /\.spec$/){{#if_eq lintConfig "airbnb"}};{{/if_eq}}
testsContext.keys().forEach(testsContext){{#if_eq lintConfig "airbnb"}};{{/if_eq}}
// require all src files except main.js for coverage.
// you can also change this to match only the subset of files that
// you want coverage for.
const srcContext = require.context('../../src', true, /^\.\/(?!main(\.js)?$)/){{#if_eq lintConfig "airbnb"}};{{/if_eq}}
srcContext.keys().forEach(srcContext){{#if_eq lintConfig "airbnb"}};{{/if_eq}}
|
Save `downloadIcon` test output to `out`
|
const downloadIcon = require('./../lib/modules/download/downloadIcon');
const fs = require('fs');
const path = require('path');
const ICON_URL = 'https://web.whatsapp.com/favicon.ico';
const ICON_PATH = path.join(__dirname, '..','out', 'test_icon.ico');
describe('Download Icons', function() {
this.timeout(10000);
it('Can download Icons', function(done) {
downloadIcon(ICON_URL)
.then(icon => {
if (!icon) {
throw 'Icon not found';
}
fs.writeFileSync(ICON_PATH, icon.data);
done();
})
.catch(done);
})
});
|
const downloadIcon = require('./../lib/modules/download/downloadIcon');
const fs = require('fs');
const ICON_URL = 'https://web.whatsapp.com/favicon.ico';
describe('Download Icons', function() {
this.timeout(10000);
it('Can download Icons', function(done) {
downloadIcon(ICON_URL)
.then(icon => {
if (!icon) {
throw 'Icon not found';
}
fs.writeFileSync(__dirname + 'testicon.ico', icon.data);
done();
})
.catch(done);
})
});
|
Add query path capabilities to /itemsource
|
<?php
namespace Friendica\Module;
use Friendica\Core\L10n;
use Friendica\Core\Renderer;
use Friendica\Model;
/**
* @author Hypolite Petovan <mrpetovan@gmail.com>
*/
class Itemsource extends \Friendica\BaseModule
{
public static function content()
{
if (!is_site_admin()) {
return;
}
$a = self::getApp();
if (!empty($a->argv[1])) {
$guid = $a->argv[1];
}
$guid = defaults($_REQUEST['guid'], $guid);
$source = '';
$item_uri = '';
if (!empty($guid)) {
$item = Model\Item::selectFirst([], ['guid' => $guid]);
$conversation = Model\Conversation::getByItemUri($item['uri']);
$item_uri = $item['uri'];
$source = $conversation['source'];
}
$tpl = Renderer::getMarkupTemplate('debug/itemsource.tpl');
$o = Renderer::replaceMacros($tpl, [
'$guid' => ['guid', L10n::t('Item Guid'), defaults($_REQUEST, 'guid', ''), ''],
'$source' => $source,
'$item_uri' => $item_uri
]);
return $o;
}
}
|
<?php
namespace Friendica\Module;
use Friendica\Core\L10n;
use Friendica\Core\Renderer;
use Friendica\Model;
/**
* @author Hypolite Petovan <mrpetovan@gmail.com>
*/
class Itemsource extends \Friendica\BaseModule
{
public static function content()
{
if (!is_site_admin()) {
return;
}
$source = '';
$item_uri = '';
if (!empty($_REQUEST['guid'])) {
$item = Model\Item::selectFirst([], ['guid' => $_REQUEST['guid']]);
$conversation = Model\Conversation::getByItemUri($item['uri']);
$item_uri = $item['uri'];
$source = $conversation['source'];
}
$tpl = Renderer::getMarkupTemplate('debug/itemsource.tpl');
$o = Renderer::replaceMacros($tpl, [
'$guid' => ['guid', L10n::t('Item Guid'), defaults($_REQUEST, 'guid', ''), ''],
'$source' => $source,
'$item_uri' => $item_uri
]);
return $o;
}
}
|
Fix a small syntax error
|
redactParagraph = Redact.addModule(
'paragraph',
(
typeof Template != 'undefined'
? Template.redactParagraph
: ''
),
{
label: 'Paragraph',
icon: '/redactParagraph.svg',
defaults: {
_html: 'Lorem Ipsum'
}
}
)
if(Meteor.isClient) {
Template.redactParagraph.events({
'keydown .redactParagraph': function (e) {
if(
e.keyCode == 8
&& (
e.currentTarget.innerHTML.length < 1
|| e.currentTarget.innerHTML === '<br>'
)
) {
redactParagraph.removeElement(
Template.currentData().collection,
Template.parentData(1)._id,
'_draft',
Template.currentData()._id
)
}
}
})
}
|
redactParagraph = Redact.addModule(
'paragraph',
(
typeof Template != 'undefined'
? Template.redactParagraph
: ''
),
{
label: 'Paragraph',
icon: '/redactParagraph.svg',
defaults: {
_html: 'Lorem Ipsum'
}
}
)
if(Meteor.isClient) {
Template.redactParagraph.events({
'keydown .redactParagraph': function (e) {
if(
e.keyCode == 8
&& (
e.currentTarget.innerHTML.length < 1
|| e.currentTarget.innerHTML === '<br>'
)
) {
redactParagraph.removeElement(
Template.currentData().collection
Template.parentData(1)._id,
'_draft',
Template.currentData()._id
)
}
}
})
}
|
Allow to reverse LVFVerb migration
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
from os.path import join
from django.db import models, migrations
from django.conf import settings
from loadmapping.models import LVFVerb
def import_verbs(apps, schema_editor):
LVFVerb = apps.get_model('loadmapping', 'LVFVerb')
LVFVerb.objects.all().delete()
with open(join(settings.SITE_ROOT, 'loadmapping/fixtures/lvfverb.json')) as fixture:
for entry in json.loads(fixture.read()):
assert entry['model'] == 'loadmapping.lvfverb'
fields = entry['fields']
LVFVerb(
lemma=fields['lemma'],
sense=fields['sense'],
lvf_class=fields['lvf_class'],
construction=fields['construction']).save()
def delete_verbs(apps, schema_editor):
LVFVerb = apps.get_model('loadmapping', 'LVFVerb')
LVFVerb.objects.all().delete()
class Migration(migrations.Migration):
dependencies = [
('loadmapping', '0001_initial'),
]
operations = [
migrations.RunPython(import_verbs, delete_verbs)
]
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
from os.path import join
from django.db import models, migrations
from django.conf import settings
from loadmapping.models import LVFVerb
def import_verbs(apps, schema_editor):
LVFVerb = apps.get_model('loadmapping', 'LVFVerb')
with open(join(settings.SITE_ROOT, 'loadmapping/fixtures/lvfverb.json')) as fixture:
for entry in json.loads(fixture.read()):
assert entry['model'] == 'loadmapping.lvfverb'
fields = entry['fields']
LVFVerb(
lemma=fields['lemma'],
sense=fields['sense'],
lvf_class=fields['lvf_class'],
construction=fields['construction']).save()
class Migration(migrations.Migration):
dependencies = [
('loadmapping', '0001_initial'),
]
operations = [
migrations.RunPython(import_verbs)
]
|
Add installation/guiprefs XML node w/o splash child
|
package com.izforge.izpack.compiler.packager.impl;
import static org.junit.Assert.fail;
import java.io.IOException;
import org.dom4j.dom.DOMElement;
import org.junit.Test;
import com.izforge.izpack.api.adaptator.IXMLElement;
import com.izforge.izpack.api.adaptator.impl.XMLElementImpl;
import com.izforge.izpack.compiler.resource.ResourceFinder;
public class PackagerTest {
@Test
public void testWritePacks() throws IOException {
final ResourceFinder resourceFinder = new ResourceFinder(null, null,
null, null) {
@Override
public IXMLElement getXMLTree() throws IOException {
final DOMElement rootNode = new DOMElement("installation");
final DOMElement guiPrefsNode = new DOMElement("guiprefs");
rootNode.add(guiPrefsNode);
return new XMLElementImpl(rootNode);
}
};
final Packager packager = new Packager(null, null, null, null, null,
null, null, null, null, null, null, resourceFinder);
packager.writeManifest();
fail("Not yet implemented");
}
}
|
package com.izforge.izpack.compiler.packager.impl;
import static org.junit.Assert.fail;
import java.io.IOException;
import org.junit.Test;
import com.izforge.izpack.api.adaptator.IXMLElement;
import com.izforge.izpack.compiler.resource.ResourceFinder;
public class PackagerTest {
@Test
public void testWritePacks() throws IOException {
final ResourceFinder resourceFinder = new ResourceFinder(null, null,
null, null) {
@Override
public IXMLElement getXMLTree() throws IOException {
return super.getXMLTree();
}
};
final Packager packager = new Packager(null, null, null, null, null,
null, null, null, null, null, null, resourceFinder);
packager.writeManifest();
fail("Not yet implemented");
}
}
|
Make long description not point to Travis since can't guarantee tag
|
from __future__ import absolute_import
from setuptools import setup
long_description="""http://github.com/nanonyme/simplepreprocessor"""
setup(
name = "simplecpreprocessor",
author = "Seppo Yli-Olli",
author_email = "seppo.yli-olli@iki.fi",
description = "Simple C preprocessor for usage eg before CFFI",
keywords = "python c preprocessor",
license = "BSD",
url = "https://github.com/nanonyme/simplecpreprocessor",
py_modules=["simplecpreprocessor"],
long_description=long_description,
use_scm_version=True,
setup_requires=["setuptools_scm"],
classifiers=[
"Development Status :: 4 - Beta",
"Topic :: Utilities",
"License :: OSI Approved :: BSD License",
],
)
|
from __future__ import absolute_import
from setuptools import setup
long_description="""TravisCI results
.. image:: https://travis-ci.org/nanonyme/simplecpreprocessor.svg
"""
setup(
name = "simplecpreprocessor",
author = "Seppo Yli-Olli",
author_email = "seppo.yli-olli@iki.fi",
description = "Simple C preprocessor for usage eg before CFFI",
keywords = "python c preprocessor",
license = "BSD",
url = "https://github.com/nanonyme/simplecpreprocessor",
py_modules=["simplecpreprocessor"],
long_description=long_description,
use_scm_version=True,
setup_requires=["setuptools_scm"],
classifiers=[
"Development Status :: 4 - Beta",
"Topic :: Utilities",
"License :: OSI Approved :: BSD License",
],
)
|
Revert change 00342e052b17 to fix sshlibrary on standalone jar.
Update issue 1311
Status: Done
Revert change 00342e052b17 to fix sshlibrary on standalone jar.
|
/* Copyright 2008-2012 Nokia Siemens Networks Oyj
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.robotframework;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
/**
*
* Helper class to create an Jython object and coerce it so that it can be used
* from Java.
*
*/
public class RunnerFactory {
private PyObject runnerClass;
public RunnerFactory() {
runnerClass = importRunnerClass();
}
private PyObject importRunnerClass() {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("import robot; from robot.jarrunner import JarRunner");
return interpreter.get("JarRunner");
}
/**
* Creates and returns an instance of the robot.JarRunner (implemented in
* Python), which can be used to execute tests.
*/
public RobotRunner createRunner() {
PyObject runnerObject = runnerClass.__call__();
return (RobotRunner) runnerObject.__tojava__(RobotRunner.class);
}
}
|
/* Copyright 2008-2012 Nokia Siemens Networks Oyj
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.robotframework;
import org.python.core.PyObject;
import org.python.core.PySystemState;
import org.python.util.PythonInterpreter;
/**
*
* Helper class to create an Jython object and coerce it so that it can be used
* from Java.
*
*/
public class RunnerFactory {
private PyObject runnerClass;
public RunnerFactory() {
runnerClass = importRunnerClass();
}
private PyObject importRunnerClass() {
PythonInterpreter interpreter = new PythonInterpreter(null, new PySystemState());
interpreter.exec("import robot; from robot.jarrunner import JarRunner");
return interpreter.get("JarRunner");
}
/**
* Creates and returns an instance of the robot.JarRunner (implemented in
* Python), which can be used to execute tests.
*/
public RobotRunner createRunner() {
PyObject runnerObject = runnerClass.__call__();
return (RobotRunner) runnerObject.__tojava__(RobotRunner.class);
}
}
|
Raise a more specific exception when the source root cannot be found.
|
# Copyright 2017 The Chromium Authors.
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd.
import os
class NoSourceRootError(Exception):
"""Exception raise when the CodeSearch library can't determine the location
of the local Chromium checkout."""
pass
def GetPackageRelativePath(filename):
"""GetPackageRelativePath returns the path to |filename| relative to the root
of the package as determined by GetSourceRoot()."""
return os.path.relpath(filename, GetSourceRoot(filename)).replace('\\', '/')
def GetSourceRoot(filename):
"""Try to determine the root of the package which contains |filename|.
The current heuristic attempts to determine the root of the Chromium source
tree by searching up the directory hierarchy until we find a directory
containing src/.gn.
"""
# If filename is not absolute, then we are going to assume that it is
# relative to the current directory.
if not os.path.isabs(filename):
filename = os.path.abspath(filename)
if not os.path.exists(filename):
raise NoSourceRootError('File not found: {}'.format(filename))
source_root = os.path.dirname(filename)
while True:
gnfile = os.path.join(source_root, 'src', '.gn')
if os.path.exists(gnfile):
return source_root
new_package_root = os.path.dirname(source_root)
if new_package_root == source_root:
raise NoSourceRootError("Can't determine package root")
source_root = new_package_root
|
# Copyright 2017 The Chromium Authors.
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd.
import os
def GetPackageRelativePath(filename):
"""GetPackageRelativePath returns the path to |filename| relative to the root
of the package as determined by GetSourceRoot()."""
return os.path.relpath(filename, GetSourceRoot(filename)).replace('\\', '/')
def GetSourceRoot(filename):
"""Try to determine the root of the package which contains |filename|.
The current heuristic attempts to determine the root of the Chromium source
tree by searching up the directory hierarchy until we find a directory
containing src/.gn.
"""
# If filename is not absolute, then we are going to assume that it is
# relative to the current directory.
if not os.path.isabs(filename):
filename = os.path.abspath(filename)
if not os.path.exists(filename):
raise IOError('File not found: {}'.format(filename))
source_root = os.path.dirname(filename)
while True:
gnfile = os.path.join(source_root, 'src', '.gn')
if os.path.exists(gnfile):
return source_root
new_package_root = os.path.dirname(source_root)
if new_package_root == source_root:
raise Exception("Can't determine package root")
source_root = new_package_root
|
Drop databases setup field, not needed since database name can be added to connection string.
|
/*jshint esnext: true */
var mongodb = require('mongodb');
/**
* Health check a mongodb resource.
*
* @param {Object} setup: http check setup with fields:
* - uri: a resource URI
* - connectTimeout: MongoDB connect timeout in milliseconds
* @param {Function} cb: standard cb(err, result) callback
*/
function check(setup, cb) {
const CONNECT_TIMEOUT = 2000;
var result = { uri: setup.uri },
opts = {
server: {
socketOptions: {
connectTimeoutMS: setup.connectTimeout || CONNECT_TIMEOUT
}
}
};
mongodb.MongoClient.connect(setup.uri , opts, function(err, conn) {
if (err) {
result.status = 'FAIL';
result.desc = err.message;
} else {
conn.close();
result.status = 'OK';
}
cb(null, result);
});
}
exports.check = check;
|
/*jshint esnext: true */
var mongodb = require('mongodb');
/**
* Health check a mongodb resource.
*
* @param {Object} setup: http check setup with fields:
* - uri: a resource URI
* - connectTimeout: MongoDB connect timeout in milliseconds
* - TODO databases: an array of database names that should exist, OK when all databases exist
* @param {Function} cb: standard cb(err, result) callback
*/
function check(setup, cb) {
const CONNECT_TIMEOUT = 2000;
var result = { uri: setup.uri },
opts = {
server: {
socketOptions: {
connectTimeoutMS: setup.connectTimeout || CONNECT_TIMEOUT
}
}
};
mongodb.MongoClient.connect(setup.uri , opts, function(err, conn) {
if (err) {
result.status = 'FAIL';
result.desc = err.message;
} else {
conn.close();
result.status = 'OK';
}
cb(null, result);
});
}
exports.check = check;
|
lxd-agent: Load certs from current dir
Signed-off-by: Stéphane Graber <089afc6d81f66f1168a9849e15660feae286e024@ubuntu.com>
|
package main
import (
"crypto/x509"
"flag"
"log"
"github.com/lxc/lxd/lxd/vsock"
"github.com/lxc/lxd/shared"
"github.com/pkg/errors"
)
func main() {
var debug bool
var cert *x509.Certificate
flag.BoolVar(&debug, "debug", false, "Enable debug mode")
flag.Parse()
l, err := vsock.Listen(8443)
if err != nil {
log.Fatalln(errors.Wrap(err, "Failed to listen on vsock"))
}
cert, err = shared.ReadCert("server.crt")
if err != nil {
log.Fatalln(errors.Wrap(err, "Failed to read client certificate"))
}
tlsConfig, err := serverTLSConfig()
if err != nil {
log.Fatalln(errors.Wrap(err, "Failed to get TLS config"))
}
httpServer := restServer(tlsConfig, cert, debug)
log.Println(httpServer.ServeTLS(networkTLSListener(l, tlsConfig), "agent.crt", "agent.key"))
}
|
package main
import (
"crypto/x509"
"flag"
"log"
"path/filepath"
"github.com/lxc/lxd/lxd/vsock"
"github.com/lxc/lxd/shared"
"github.com/pkg/errors"
)
var tlsClientCertFile = filepath.Join("/", "media", "lxd_config", "server.crt")
var tlsServerCertFile = filepath.Join("/", "media", "lxd_config", "agent.crt")
var tlsServerKeyFile = filepath.Join("/", "media", "lxd_config", "agent.key")
func main() {
var debug bool
var cert *x509.Certificate
flag.BoolVar(&debug, "debug", false, "Enable debug mode")
flag.Parse()
l, err := vsock.Listen(8443)
if err != nil {
log.Fatalln(errors.Wrap(err, "Failed to listen on vsock"))
}
cert, err = shared.ReadCert(tlsClientCertFile)
if err != nil {
log.Fatalln(errors.Wrap(err, "Failed to read client certificate"))
}
tlsConfig, err := serverTLSConfig()
if err != nil {
log.Fatalln(errors.Wrap(err, "Failed to get TLS config"))
}
httpServer := restServer(tlsConfig, cert, debug)
log.Println(httpServer.ServeTLS(networkTLSListener(l, tlsConfig), tlsServerCertFile, tlsServerKeyFile))
}
|
Increase version number for pypi
|
from setuptools import setup
setup(
name='autograd',
version='1.5',
description='Efficiently computes derivatives of numpy code.',
author='Dougal Maclaurin and David Duvenaud and Matthew Johnson',
author_email="maclaurin@physics.harvard.edu, duvenaud@cs.toronto.edu, mattjj@csail.mit.edu",
packages=['autograd', 'autograd.numpy', 'autograd.scipy', 'autograd.scipy.stats', 'autograd.misc'],
install_requires=['numpy>=1.12', 'future>=0.15.2'],
keywords=['Automatic differentiation', 'backpropagation', 'gradients',
'machine learning', 'optimization', 'neural networks',
'Python', 'Numpy', 'Scipy'],
url='https://github.com/HIPS/autograd',
license='MIT',
classifiers=['Development Status :: 4 - Beta',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.5'],
)
|
from setuptools import setup
setup(
name='autograd',
version='1.4',
description='Efficiently computes derivatives of numpy code.',
author='Dougal Maclaurin and David Duvenaud and Matthew Johnson',
author_email="maclaurin@physics.harvard.edu, duvenaud@cs.toronto.edu, mattjj@csail.mit.edu",
packages=['autograd', 'autograd.numpy', 'autograd.scipy', 'autograd.scipy.stats', 'autograd.misc'],
install_requires=['numpy>=1.12', 'future>=0.15.2'],
keywords=['Automatic differentiation', 'backpropagation', 'gradients',
'machine learning', 'optimization', 'neural networks',
'Python', 'Numpy', 'Scipy'],
url='https://github.com/HIPS/autograd',
license='MIT',
classifiers=['Development Status :: 4 - Beta',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.5'],
)
|
Fix getCapacityHandler: write response status code and add nosniff header
|
package handlers
import (
"encoding/json"
"net/http"
"github.com/sirupsen/logrus"
"github.com/ivan1993spb/snake-server/connections"
)
const URLRouteGetCapacity = "/capacity"
const MethodGetCapacity = http.MethodGet
type responseGetCapacityHandler struct {
Capacity float32 `json:"capacity"`
}
type getCapacityHandler struct {
logger logrus.FieldLogger
groupManager *connections.ConnectionGroupManager
}
type ErrGetCapacityHandler string
func (e ErrGetCapacityHandler) Error() string {
return "get capacity handler error: " + string(e)
}
func NewGetCapacityHandler(logger logrus.FieldLogger, groupManager *connections.ConnectionGroupManager) http.Handler {
return &getCapacityHandler{
logger: logger,
groupManager: groupManager,
}
}
func (h *getCapacityHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
err := json.NewEncoder(w).Encode(responseGetCapacityHandler{
Capacity: h.groupManager.Capacity(),
})
if err != nil {
h.logger.Error(ErrGetGameHandler(err.Error()))
}
}
|
package handlers
import (
"encoding/json"
"net/http"
"github.com/sirupsen/logrus"
"github.com/ivan1993spb/snake-server/connections"
)
const URLRouteGetCapacity = "/capacity"
const MethodGetCapacity = http.MethodGet
type responseGetCapacityHandler struct {
Capacity float32 `json:"capacity"`
}
type getCapacityHandler struct {
logger logrus.FieldLogger
groupManager *connections.ConnectionGroupManager
}
type ErrGetCapacityHandler string
func (e ErrGetCapacityHandler) Error() string {
return "get capacity handler error: " + string(e)
}
func NewGetCapacityHandler(logger logrus.FieldLogger, groupManager *connections.ConnectionGroupManager) http.Handler {
return &getCapacityHandler{
logger: logger,
groupManager: groupManager,
}
}
func (h *getCapacityHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
err := json.NewEncoder(w).Encode(responseGetCapacityHandler{
Capacity: h.groupManager.Capacity(),
})
if err != nil {
h.logger.Error(ErrGetGameHandler(err.Error()))
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
}
|
Build ebooks as part of CI tasks
|
const gulp = require('gulp');
const del = require('del');
const gulpGitbook = require('gulp-gitbook');
const shell = require('gulp-shell');
const gulpLoadPlugins = require('gulp-load-plugins');
const $ = gulpLoadPlugins();
// Publishes the site to GitHub Pages
gulp.task('publish', () => {
console.log('Publishing to GH Pages');
return gulp.src('./_book/**/*')
.pipe($.ghPages({
origin: 'origin',
branch: 'gh-pages'
}));
});
gulp.task('clean', () => {
console.log('Clean build directory');
return del(['./_book/**/*', '!./_book/.keep']);
});
gulp.task('build', function (cb) {
console.log('Building HTML version')
gulpGitbook('.', cb);
});
// FIXME: smh, you should actually learn how to use gulp
gulp.task('build-ebooks', () => {
console.log('Building PDF, ePUB, and MOBI versions')
shell.task([
'gitbook pdf docs _book/hybox-models.pdf',
'gitbook epub docs _book/hybox-models.epub',
'gitbook mobi docs _book/hybox-models.mobi',
]);
});
gulp.task('default', ['clean', 'build', 'publish']);
gulp.task('travis', ['clean', 'build', 'build-ebooks']);
|
const gulp = require('gulp');
const del = require('del');
const gulpGitbook = require('gulp-gitbook');
const shell = require('gulp-shell');
const gulpLoadPlugins = require('gulp-load-plugins');
const $ = gulpLoadPlugins();
// Publishes the site to GitHub Pages
gulp.task('publish', () => {
console.log('Publishing to GH Pages');
return gulp.src('./_book/**/*')
.pipe($.ghPages({
origin: 'origin',
branch: 'gh-pages'
}));
});
gulp.task('clean', () => {
console.log('Clean build directory');
return del(['./_book/**/*', '!./_book/.keep']);
});
gulp.task('build', function (cb) {
console.log('Building HTML version')
gulpGitbook('.', cb);
});
// FIXME: smh, you should actually learn how to use gulp
gulp.task('build-ebooks', () => {
console.log('Building PDF, ePUB, and MOBI versions')
shell.task([
'gitbook pdf docs _book/hybox-models.pdf',
'gitbook epub docs _book/hybox-models.epub',
'gitbook mobi docs _book/hybox-models.mobi',
]);
});
gulp.task('default', ['clean', 'build', 'publish']);
gulp.task('travis', ['clean', 'build']);
|
Set main frame default location.
|
package com.github.aureliano.edocs.app.gui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import com.github.aureliano.edocs.app.gui.menu.MenuBar;
public class AppFrame extends JFrame {
private static final long serialVersionUID = 7618501026967569839L;
private TabbedPane tabbedPane;
public AppFrame() {
this.buildGui();
}
private void buildGui() {
super.setTitle("e-Docs");
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new BorderLayout());
panel.setOpaque(true);
panel.add(new VerticalToolBar(), BorderLayout.WEST);
this.tabbedPane = new TabbedPane();
panel.add(this.tabbedPane, BorderLayout.CENTER);
super.setContentPane(panel);
super.setJMenuBar(new MenuBar());
}
public void showFrame() {
super.pack();
super.setSize(new Dimension(500, 500));
super.setLocationRelativeTo(null);
super.setVisible(true);
}
}
|
package com.github.aureliano.edocs.app.gui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import com.github.aureliano.edocs.app.gui.menu.MenuBar;
public class AppFrame extends JFrame {
private static final long serialVersionUID = 7618501026967569839L;
private TabbedPane tabbedPane;
public AppFrame() {
this.buildGui();
}
private void buildGui() {
super.setTitle("e-Docs");
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new BorderLayout());
panel.setOpaque(true);
panel.add(new VerticalToolBar(), BorderLayout.WEST);
this.tabbedPane = new TabbedPane();
panel.add(this.tabbedPane, BorderLayout.CENTER);
super.setContentPane(panel);
super.setJMenuBar(new MenuBar());
}
public void showFrame() {
super.pack();
super.setVisible(true);
super.setSize(new Dimension(500, 500));
}
}
|
Work on Log Normal. Not ready yet.
|
from __future__ import division
import sys
import numpy as np
from random import randrange, choice
import matplotlib.pyplot as plt
from matplotlib import patches, path
import scipy.stats
'''This script codes the LogNormal Models'''
# To code the LogNormal...each division is 75:25
# Still working on this...numbers are not properly summing to N yet
# Getting proper number of divisions but whole thing is yet to come together
def SimLogNorm(N, S, sample_size):
for i in range(sample_size):
sample = []
RAC = []
while len(RAC) < S:
sp1 = N * .75
RAC.append(sp1)
sp2 = N * .25
RAC.append(sp2)
sp3 = choice(RAC) * .75
RAC.append(sp3)
sp4 = sp3 * 1/3
RAC.append(sp4)
#print RAC
sample.append(RAC)
print sample
samples = SimLogNorm(8, 4, 5)
|
from __future__ import division
import sys
import numpy as np
from random import randrange, choice
import matplotlib.pyplot as plt
from matplotlib import patches, path
import scipy.stats
'''This script codes the LogNormal Models'''
# To code the LogNormal...each division is 75:25
# Still working on this...numbers are not properly summing to N yet
# Getting proper number of divisions but whole thing is yet to come together
def SimLogNorm(N, S, sample_size):
for i in range(sample_size):
sample = []
RAC = [N*.75,N*.25]
while len(RAC) < S:
x = choice(RAC)
new1 = x * .75
new2 = x * .25
RAC.append(x)
RAC.append(new1)
RAC.append(new2)
print RAC
sample.append(RAC)
sample = SimLogNorm(20, 5, 10)
print sample
|
Remove unnecessary import [rev: minor]
|
/*
* Copyright 2014-2015 Hewlett-Packard Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
define([
'find/app/find-pages',
'find/app/page/find-settings-page',
'i18n!find/nls/bundle'
], function(FindPages, SettingsPage) {
return FindPages.extend({
initializePages: function() {
this.pages = [
{
constructor: SettingsPage
, pageName: 'settings'
, classes: 'hide-from-non-useradmin'
}
];
}
});
});
|
/*
* Copyright 2014-2015 Hewlett-Packard Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
define([
'find/app/find-pages',
'find/app/page/find-search',
'find/app/page/find-settings-page',
'i18n!find/nls/bundle'
], function(FindPages, FindSearch, SettingsPage) {
return FindPages.extend({
initializePages: function() {
this.pages = [
{
constructor: SettingsPage
, pageName: 'settings'
, classes: 'hide-from-non-useradmin'
}
];
}
});
});
|
Add test with non-Array data
|
// This is the key from storage.js.
const runsKey = 'playbyplay_runs_A*O%y21#Q1WSh^f09YO!';
describe('after storing non-JSON data', () => {
beforeEach(() => {
localStorage[runsKey] = 'Not JSON!';
});
it('should return an error on load', () =>
expect(playbyplay.load()).to.be.rejectedWith(Error,
`SyntaxError: Unable to parse JSON string`)
);
describe('and saving a first run', () => {
beforeEach(() => playbyplay.save('first'));
it('should load the first run', () =>
expect(playbyplay.load()).to.eventually.deep.equal(['first'])
);
});
after(playbyplay.clear);
});
describe('after storing non-Array data', () => {
beforeEach(() => {
localStorage[runsKey] = '"Not an Array"';
});
it('should return an error on load', () =>
expect(playbyplay.load()).to.be.rejectedWith(Error, `Error: Loaded runs are not an Array`)
);
describe('and saving a first run', () => {
beforeEach(() => playbyplay.save('first'));
it('should load the first run', () =>
expect(playbyplay.load()).to.eventually.deep.equal(['first'])
);
});
after(playbyplay.clear);
});
|
describe('after storing garbage data', () => {
// This is the key from storage.js.
const runsKey = 'playbyplay_runs_A*O%y21#Q1WSh^f09YO!';
beforeEach(() => {
localStorage[runsKey] = 'Not JSON!';
});
it('should return an error on load', () =>
expect(playbyplay.load()).to.be.rejectedWith(Error,
`SyntaxError: Unable to parse JSON string`)
);
describe('and saving a first run', () => {
beforeEach(() => playbyplay.save('first'));
it('should load the first run', () =>
expect(playbyplay.load()).to.eventually.deep.equal(['first'])
);
});
after(playbyplay.clear);
});
|
Add custom config for notifier catcher
|
/* @flow */
import EmailSmtpProvider from './email/smtp'
// Types
import type {ChannelType} from '../index'
import type {EmailRequestType} from '../models/notification-request'
export default class NotificationCatcherProvider {
id: string
provider: EmailSmtpProvider
static getConfig (channels: ChannelType[]) {
return channels.reduce((config, channel: any) => ({
...config,
[channel]: {
providers: [{type: 'notificationcatcher'}],
multiProviderStrategy: 'no-fallback'
}
}), {})
}
constructor (channel: ChannelType) {
this.id = `${channel}-notificationcatcher-provider`
const options = process.env.NOTIFME_CATCHER_OPTIONS || {
port: 1025,
ignoreTLS: true
}
this.provider = new EmailSmtpProvider(options)
}
async sendToCatcher (request: EmailRequestType): Promise<string> {
return this.provider.send(request)
}
}
|
/* @flow */
import EmailSmtpProvider from './email/smtp'
// Types
import type {ChannelType} from '../index'
import type {EmailRequestType} from '../models/notification-request'
export default class NotificationCatcherProvider {
id: string
provider: EmailSmtpProvider
static getConfig (channels: ChannelType[]) {
return channels.reduce((config, channel: any) => ({
...config,
[channel]: {
providers: [{type: 'notificationcatcher'}],
multiProviderStrategy: 'no-fallback'
}
}), {})
}
constructor (channel: ChannelType) {
this.id = `${channel}-notificationcatcher-provider`
this.provider = new EmailSmtpProvider({
port: 1025,
ignoreTLS: true
})
}
async sendToCatcher (request: EmailRequestType): Promise<string> {
return this.provider.send(request)
}
}
|
Fix bug in print statement
|
"""Test garner.dates."""
from __future__ import absolute_import
from .check import Check
from proselint.checks.garner import dates
class TestCheck(Check):
"""Test class for garner.dates."""
__test__ = True
def test_50s_hyphenation(self):
"""Find uneeded hyphen in 50's."""
text = """The 50's were swell."""
errors = dates.check_decade_apostrophes_short(text)
assert len(errors) == 1
def test_50_Cent_hyphenation(self):
"""Don't flag 50's when it refers to 50 Cent's manager."""
text = """
Dr. Dre suggested to 50's manager that he look into signing
Eminem to the G-Unit record label.
"""
errors = dates.check_decade_apostrophes_short(text)
assert len(errors) == 0
def test_dash_and_from(self):
"""Test garner.check_dash_and_from."""
text = """From 1999-2002, Sally served as chair of the committee."""
errors = dates.check_dash_and_from(text)
print(errors)
assert len(errors) == 1
|
"""Test garner.dates."""
from __future__ import absolute_import
from .check import Check
from proselint.checks.garner import dates
class TestCheck(Check):
"""Test class for garner.dates."""
__test__ = True
def test_50s_hyphenation(self):
"""Find uneeded hyphen in 50's."""
text = """The 50's were swell."""
errors = dates.check_decade_apostrophes_short(text)
assert len(errors) == 1
def test_50_Cent_hyphenation(self):
"""Don't flag 50's when it refers to 50 Cent's manager."""
text = """
Dr. Dre suggested to 50's manager that he look into signing
Eminem to the G-Unit record label.
"""
errors = dates.check_decade_apostrophes_short(text)
assert len(errors) == 0
def test_dash_and_from(self):
"""Test garner.check_dash_and_from."""
text = """From 1999-2002, Sally served as chair of the committee."""
errors = dates.check_dash_and_from(text)
print errors
assert len(errors) == 1
|
Fix bad usage of Bacon
|
'use strict';
const _ = require('lodash');
const cleverClient = require('clever-client');
const Logger = require('../logger.js');
const { conf, loadOAuthConf } = require('./configuration.js');
function initApi () {
return loadOAuthConf().map((tokens) => {
const apiSettings = _.assign({}, conf, {
API_HOST: conf.API_HOST,
API_CONSUMER_KEY: conf.OAUTH_CONSUMER_KEY,
API_CONSUMER_SECRET: conf.OAUTH_CONSUMER_SECRET,
API_OAUTH_TOKEN: tokens.token,
API_OAUTH_TOKEN_SECRET: tokens.secret,
logger: Logger,
});
const api = cleverClient(apiSettings);
// Waiting for clever-client to be fully node compliant
api.session.getAuthorization = (httpMethod, url, params) => {
return api.session.getHMACAuthorization(httpMethod, url, params, {
user_oauth_token: tokens.token,
user_oauth_token_secret: tokens.secret,
});
};
return api;
});
};
module.exports = initApi;
|
'use strict';
const _ = require('lodash');
const cleverClient = require('clever-client');
const Logger = require('../logger.js');
const { conf, loadOAuthConf } = require('./configuration.js');
function initApi () {
return loadOAuthConf().flatMapLatest((tokens) => {
const apiSettings = _.assign({}, conf, {
API_HOST: conf.API_HOST,
API_CONSUMER_KEY: conf.OAUTH_CONSUMER_KEY,
API_CONSUMER_SECRET: conf.OAUTH_CONSUMER_SECRET,
API_OAUTH_TOKEN: tokens.token,
API_OAUTH_TOKEN_SECRET: tokens.secret,
logger: Logger,
});
const api = cleverClient(apiSettings);
// Waiting for clever-client to be fully node compliant
api.session.getAuthorization = (httpMethod, url, params) => {
return api.session.getHMACAuthorization(httpMethod, url, params, {
user_oauth_token: tokens.token,
user_oauth_token_secret: tokens.secret,
});
};
return api;
});
};
module.exports = initApi;
|
Make x axis label samples for now, though eventually should have a date option
|
#!/usr/bin/python
import argparse
import matplotlib.pyplot as plt
from pylab import *
from osta.osta import *
############
### MAIN ###
############
parser = argparse.ArgumentParser(formatter_class = argparse.RawTextHelpFormatter)
parser.add_argument(
'--select',
help = "Select the full name of a stat to graph (e.g. \"scene.Keynote 1.RootAgents\")")
parser.add_argument(
'--out',
help = "Path to output the graph rather the interactively display. Filename extension determines graphics type (e.g. \"graph.jpg\")",
default = argparse.SUPPRESS)
parser.add_argument(
'statsLogPath',
help = "Path to the stats log file.",
metavar = "stats-log-path")
opts = parser.parse_args()
osta = Osta()
osta.parse(opts.statsLogPath)
stat = osta.getStat(opts.select)
if not stat == None:
plt.plot(stat['abs']['values'])
plt.title(stat['fullName'])
plt.xlabel("samples")
plt.ylabel(stat['name'])
if 'out' in opts:
savefig(opts.out)
else:
plt.show()
else:
print "No such stat as %s" % (opts.select)
|
#!/usr/bin/python
import argparse
import matplotlib.pyplot as plt
from pylab import *
from osta.osta import *
############
### MAIN ###
############
parser = argparse.ArgumentParser(formatter_class = argparse.RawTextHelpFormatter)
parser.add_argument(
'--select',
help = "Select the full name of a stat to graph (e.g. \"scene.Keynote 1.RootAgents\")")
parser.add_argument(
'--out',
help = "Path to output the graph rather the interactively display. Filename extension determines graphics type (e.g. \"graph.jpg\")",
default = argparse.SUPPRESS)
parser.add_argument(
'statsLogPath',
help = "Path to the stats log file.",
metavar = "stats-log-path")
opts = parser.parse_args()
osta = Osta()
osta.parse(opts.statsLogPath)
stat = osta.getStat(opts.select)
if not stat == None:
plt.plot(stat['abs']['values'])
plt.title(stat['fullName'])
plt.ylabel(stat['name'])
if 'out' in opts:
savefig(opts.out)
else:
plt.show()
else:
print "No such stat as %s" % (opts.select)
|
Update Slybot packages and drop support for Python < 2.7
|
from slybot import __version__
from setuptools import setup, find_packages
install_requires = ['Scrapy', 'scrapely', 'loginform', 'lxml', 'jsonschema']
tests_requires = install_requires
setup(name='slybot',
version=__version__,
license='BSD',
description='Slybot crawler',
author='Scrapy project',
author_email='info@scrapy.org',
url='http://github.com/scrapy/slybot',
packages=find_packages(exclude=('tests', 'tests.*')),
platforms=['Any'],
scripts=['bin/slybot', 'bin/portiacrawl'],
install_requires=install_requires,
tests_requires=tests_requires,
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7'
])
|
from slybot import __version__
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
install_requires = ['Scrapy', 'scrapely', 'loginform', 'lxml', 'jsonschema']
tests_requires = install_requires
setup(name='slybot',
version=__version__,
license='BSD',
description='Slybot crawler',
author='Scrapy project',
author_email='info@scrapy.org',
url='http://github.com/scrapy/slybot',
packages=['slybot', 'slybot.fieldtypes', 'slybot.tests', 'slybot.linkextractor'],
platforms=['Any'],
scripts=['bin/slybot', 'bin/portiacrawl'],
install_requires=install_requires,
tests_requires=tests_requires,
classifiers=['Development Status :: 4 - Beta',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python'])
|
Update permission to show course detail for teachers
|
'use strict';
module.exports = function(app) {
var users = require('../../app/controllers/users.server.controller');
var courses = require('../../app/controllers/courses.server.controller');
var authorized = ['manager', 'admin'];
// Courses Routes
app.route('/courses')
.get(users.requiresLogin, users.hasAuthorization(authorized), courses.list)
.post(users.requiresLogin, users.hasAuthorization(authorized), courses.create);
app.route('/list/myCourses')
.get(users.requiresLogin, users.hasAuthorization(['teacher']), courses.listMyCourses);
app.route('/courses/:courseId')
.post(users.requiresLogin, users.hasAuthorization(authorized), courses.create)
.get(users.requiresLogin, users.hasAuthorization(['manager', 'admin', 'teacher']), courses.read)
.put(users.requiresLogin, users.hasAuthorization(authorized), courses.update)
.delete(users.requiresLogin, users.hasAuthorization(authorized), courses.delete);
// Finish by binding the Course middleware
app.param('courseId', courses.courseByID);
};
|
'use strict';
module.exports = function(app) {
var users = require('../../app/controllers/users.server.controller');
var courses = require('../../app/controllers/courses.server.controller');
var authorized = ['manager', 'admin'];
// Courses Routes
app.route('/courses')
.get(users.requiresLogin, users.hasAuthorization(authorized), courses.list)
.post(users.requiresLogin, users.hasAuthorization(authorized), courses.create);
app.route('/list/myCourses')
.get(users.requiresLogin, users.hasAuthorization(['teacher']), courses.listMyCourses);
app.route('/courses/:courseId')
.post(users.requiresLogin, users.hasAuthorization(authorized), courses.create)
.get(users.requiresLogin, users.hasAuthorization(authorized), courses.read)
.put(users.requiresLogin, users.hasAuthorization(authorized), courses.update)
.delete(users.requiresLogin, users.hasAuthorization(authorized), courses.delete);
// Finish by binding the Course middleware
app.param('courseId', courses.courseByID);
};
|
Add Bernoulli iterator to namespace
|
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-read-only-property' );
// MAIN //
/**
* Top-level namespace.
*
* @namespace ns
*/
var ns = {};
/**
* @name arcsine
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/random/iterators/arcsine}
*/
setReadOnly( ns, 'arcsine', require( '@stdlib/random/iterators/arcsine' ) );
/**
* @name bernoulli
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/random/iterators/bernoulli}
*/
setReadOnly( ns, 'bernoulli', require( '@stdlib/random/iterators/bernoulli' ) );
// EXPORTS //
module.exports = ns;
|
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-read-only-property' );
// MAIN //
/**
* Top-level namespace.
*
* @namespace ns
*/
var ns = {};
/**
* @name arcsine
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/random/iterators/arcsine}
*/
setReadOnly( ns, 'arcsine', require( '@stdlib/random/iterators/arcsine' ) );
// EXPORTS //
module.exports = ns;
|
Add the consumer name to the extra values
|
"""
Logging Related Things
"""
import logging
class CorrelationFilter(logging.Formatter):
"""Filter records that have a correlation_id"""
def __init__(self, exists=None):
super(CorrelationFilter, self).__init__()
self.exists = exists
def filter(self, record):
if self.exists:
return hasattr(record, 'correlation_id')
return not hasattr(record, 'correlation_id')
class CorrelationAdapter(logging.LoggerAdapter):
"""A LoggerAdapter that appends the a correlation ID to the message
record properties.
"""
def __init__(self, logger, consumer):
self.logger = logger
self.consumer = consumer
def process(self, msg, kwargs):
"""Process the logging message and keyword arguments passed in to
a logging call to insert contextual information.
:param str msg: The message to process
:param dict kwargs: The kwargs to append
:rtype: (str, dict)
"""
kwargs['extra'] = {'correlation_id': self.consumer.correlation_id,
'consumer': self.consumer.name}
return msg, kwargs
|
"""
Logging Related Things
"""
import logging
class CorrelationFilter(logging.Formatter):
"""Filter records that have a correlation_id"""
def __init__(self, exists=None):
super(CorrelationFilter, self).__init__()
self.exists = exists
def filter(self, record):
if self.exists:
return hasattr(record, 'correlation_id')
return not hasattr(record, 'correlation_id')
class CorrelationAdapter(logging.LoggerAdapter):
"""A LoggerAdapter that appends the a correlation ID to the message
record properties.
"""
def __init__(self, logger, consumer):
self.logger = logger
self.consumer = consumer
def process(self, msg, kwargs):
"""Process the logging message and keyword arguments passed in to
a logging call to insert contextual information.
:param str msg: The message to process
:param dict kwargs: The kwargs to append
:rtype: (str, dict)
"""
kwargs['extra'] = {'correlation_id': self.consumer.correlation_id}
return msg, kwargs
|
Add verbose flag to processor parameters
|
/*
* Copyright 2015 Michael Rozumyanskiy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.michaelrocks.lightsaber.processor;
import com.beust.jcommander.Parameter;
public class LightsaberParameters {
@Parameter(names = "--jar", description = "Jar file to process")
public String jar;
@Parameter(names = "--classes", description = "Classes directory to process")
public String classes;
@Parameter(names = { "-v", "--verbose" }, description = "Use verbose output")
public boolean verbose = false;
@Parameter(names = "--stacktrace", description = "Print stack traces")
public boolean printStacktrace = false;
}
|
/*
* Copyright 2015 Michael Rozumyanskiy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.michaelrocks.lightsaber.processor;
import com.beust.jcommander.Parameter;
public class LightsaberParameters {
@Parameter(names = "--jar", description = "Jar file to process")
public String jar;
@Parameter(names = "--classes", description = "Classes directory to process")
public String classes;
@Parameter(names = "--stacktrace", description = "Print stack traces")
public boolean printStacktrace = false;
}
|
BUG: Fix forgotten import in example
|
"""Non linear regression with Support Vector Regression (SVR)
using RBF kernel
"""
###############################################################################
# Generate sample data
import numpy as np
X = np.sort(5*np.random.rand(40, 1), axis=0)
y = np.sin(X).ravel()
###############################################################################
# Add noise to targets
y[::5] += 3*(0.5 - np.random.rand(8))
###############################################################################
# Fit regression model
from scikits.learn.svm import SVR
svr_rbf = SVR(kernel='rbf', C=1e4, gamma=0.1)
svr_lin = SVR(kernel='linear', C=1e4)
svr_poly = SVR(kernel='poly', C=1e4, degree=2)
y_rbf = svr_rbf.fit(X, y).predict(X)
y_lin = svr_lin.fit(X, y).predict(X)
y_poly = svr_poly.fit(X, y).predict(X)
###############################################################################
# look at the results
import pylab as pl
pl.scatter(X, y, c='k', label='data')
pl.hold('on')
pl.plot(X, y_rbf, c='g', label='RBF model')
pl.plot(X, y_lin, c='r', label='Linear model')
pl.plot(X, y_poly, c='b', label='Polynomial model')
pl.xlabel('data')
pl.ylabel('target')
pl.title('Support Vector Regression')
pl.legend()
pl.show()
|
"""Non linear regression with Support Vector Regression (SVR)
using RBF kernel
"""
###############################################################################
# Generate sample data
import numpy as np
X = np.sort(5*np.random.rand(40, 1), axis=0)
y = np.sin(X).ravel()
###############################################################################
# Add noise to targets
y[::5] += 3*(0.5 - np.random.rand(8))
###############################################################################
# Fit regression model
from scikits.learn.svm import SVR
svr_rbf = SVR(kernel='rbf', C=1e4, gamma=0.1)
svr_lin = SVR(kernel='linear', C=1e4)
svr_poly = SVR(kernel='poly', C=1e4, degree=2)
y_rbf = svr_rbf.fit(X, y).predict(X)
y_lin = svr_lin.fit(X, y).predict(X)
y_poly = svr_poly.fit(X, y).predict(X)
###############################################################################
# look at the results
pl.scatter(X, y, c='k', label='data')
pl.hold('on')
pl.plot(X, y_rbf, c='g', label='RBF model')
pl.plot(X, y_lin, c='r', label='Linear model')
pl.plot(X, y_poly, c='b', label='Polynomial model')
pl.xlabel('data')
pl.ylabel('target')
pl.title('Support Vector Regression')
pl.legend()
pl.show()
|
JSONFieldDescriptor: Use DjangoJSONEncoder, it knows how to handle dates and decimals
|
from django.core.serializers.json import DjangoJSONEncoder
from django.utils import simplejson
class JSONFieldDescriptor(object):
def __init__(self, field):
self.field = field
def __get__(self, obj, objtype):
cache_field = '_cached_jsonfield_%s' % self.field
if not hasattr(obj, cache_field):
try:
setattr(obj, cache_field, simplejson.loads(getattr(obj, self.field)))
except (TypeError, ValueError):
setattr(obj, cache_field, {})
return getattr(obj, cache_field)
def __set__(self, obj, value):
setattr(obj, '_cached_jsonfield_%s' % self.field, value)
setattr(obj, self.field, simplejson.dumps(value, cls=DjangoJSONEncoder))
|
from django.utils import simplejson
class JSONFieldDescriptor(object):
def __init__(self, field):
self.field = field
def __get__(self, obj, objtype):
cache_field = '_cached_jsonfield_%s' % self.field
if not hasattr(obj, cache_field):
try:
setattr(obj, cache_field, simplejson.loads(getattr(obj, self.field)))
except (TypeError, ValueError):
setattr(obj, cache_field, {})
return getattr(obj, cache_field)
def __set__(self, obj, value):
setattr(obj, '_cached_jsonfield_%s' % self.field, value)
setattr(obj, self.field, simplejson.dumps(value))
|
Fix datacenter listing for r34lz
Signed-off-by: Adam Stokes <49c255c1d074742f60d19fdba5e2aa5a34add567@users.noreply.github.com>
|
from conjureup import controllers
from conjureup.app_config import app
class BaseVSphereSetupController:
def __init__(self):
# Assign current datacenter
app.provider.login()
for dc in app.provider.get_datacenters():
if dc == app.provider.region:
self.datacenter = dc
def finish(self, data):
app.provider.model_defaults = {
'primary-network': data['primary-network'],
'external-network': data['external-network'],
'datastore': data['datastore']
}
return controllers.use('controllerpicker').render()
|
from conjureup import controllers
from conjureup.app_config import app
class BaseVSphereSetupController:
def __init__(self):
# Assign current datacenter
app.provider.login()
for dc in app.provider.get_datacenters():
if dc.name == app.provider.region:
self.datacenter = dc
def finish(self, data):
app.provider.model_defaults = {
'primary-network': data['primary-network'],
'external-network': data['external-network'],
'datastore': data['datastore']
}
return controllers.use('controllerpicker').render()
|
Change NUMBER field format: None -> count
|
REDIS_HOST = '127.0.0.1'
REDIS_PORT = 6379
REDIS_DB = 0
MONGO_HOST = '127.0.0.1'
MONGO_PORT = 27017
MONGO_DB_NAME = 'appstats'
APP_IDS = [dict(key='prom.ua', name='Prom.ua'),
dict(key='tiu.ru', name='Tiu.ru'),
dict(key='deal.by', name='Deal.by')]
FIELDS = [
dict(key='NUMBER', name='NUMBER', format='count', visible=True),
dict(key='cpu_time', name='CPU', format='time', visible=True),
]
TIME_FIELDS = [
dict(key='real_time', name='TOTAL', format='time', visible=True),
dict(key='memc:duration', name='MEMC', format='time', visible=True),
dict(key='redis:duration', name='REDIS', format='time', visible=True),
dict(key='solr:duration', name='SOLR', format='time', visible=True),
dict(key='sql:duration', name='SQL', format='time', visible=True),
]
|
REDIS_HOST = '127.0.0.1'
REDIS_PORT = 6379
REDIS_DB = 0
MONGO_HOST = '127.0.0.1'
MONGO_PORT = 27017
MONGO_DB_NAME = 'appstats'
APP_IDS = [dict(key='prom.ua', name='Prom.ua'),
dict(key='tiu.ru', name='Tiu.ru'),
dict(key='deal.by', name='Deal.by')]
FIELDS = [
dict(key='NUMBER', name='NUMBER', format=None, visible=True),
dict(key='cpu_time', name='CPU', format='time', visible=True),
]
TIME_FIELDS = [
dict(key='real_time', name='TOTAL', format='time', visible=True),
dict(key='memc:duration', name='MEMC', format='time', visible=True),
dict(key='redis:duration', name='REDIS', format='time', visible=True),
dict(key='solr:duration', name='SOLR', format='time', visible=True),
dict(key='sql:duration', name='SQL', format='time', visible=True),
]
|
Fix references not available after pulling up two instances of roamer
|
#!/usr/bin/env python
"""
argh
"""
import os
from roamer.python_edit import file_editor
from roamer.directory import Directory
from roamer.edit_directory import EditDirectory
from roamer.engine import Engine
from roamer.record import Record
from roamer.constant import TRASH_DIR
def main():
"""
argh
"""
if not os.path.exists(TRASH_DIR):
os.makedirs(TRASH_DIR)
cwd = os.getcwd()
raw_entries = os.listdir(cwd)
directory = Directory(cwd, raw_entries)
Record().add_dir(directory)
output = file_editor(directory.text())
edit_directory = EditDirectory(cwd, output)
engine = Engine(directory, edit_directory)
print engine.print_commands()
engine.run_commands()
Record().add_dir(Directory(cwd, os.listdir(cwd)))
if __name__ == "__main__":
main()
|
#!/usr/bin/env python
"""
argh
"""
import os
from roamer.python_edit import file_editor
from roamer.directory import Directory
from roamer.edit_directory import EditDirectory
from roamer.engine import Engine
from roamer.record import Record
from roamer.constant import TRASH_DIR
def main():
"""
argh
"""
if not os.path.exists(TRASH_DIR):
os.makedirs(TRASH_DIR)
cwd = os.getcwd()
raw_entries = os.listdir(cwd)
directory = Directory(cwd, raw_entries)
output = file_editor(directory.text())
edit_directory = EditDirectory(cwd, output)
engine = Engine(directory, edit_directory)
print engine.print_commands()
engine.run_commands()
Record().add_dir(Directory(cwd, os.listdir(cwd)))
if __name__ == "__main__":
main()
|
Use polling block notifier if using MetaMask
|
"use strict";
var Notifier = require("./notifier.js");
var PollingBlockNotifier = require("./polling-block-notifier.js");
var SubscribingBlockNotifier = require("./subscribing-block-notifier.js");
var isMetaMask = require("../utils/is-meta-mask");
function BlockNotifier(transport, pollingIntervalMilliseconds) {
var blockNotifier;
Notifier.call(this);
if (isMetaMask()) { // MetaMask doesn't throw an error on eth_subscribe, but doesn't actually send block notifications, so we need to poll instead...
blockNotifier = new PollingBlockNotifier(transport, pollingIntervalMilliseconds);
} else {
blockNotifier = new SubscribingBlockNotifier(transport, function () {
blockNotifier.destroy();
blockNotifier = new PollingBlockNotifier(transport, pollingIntervalMilliseconds);
blockNotifier.subscribe(this.notifySubscribers);
}.bind(this));
}
blockNotifier.subscribe(this.notifySubscribers);
this.destroy = function () {
this.unsubscribeAll();
blockNotifier.destroy();
}.bind(this);
}
BlockNotifier.prototype = Object.create(Notifier.prototype);
BlockNotifier.prototype.constructor = BlockNotifier;
module.exports = BlockNotifier;
|
"use strict";
var Notifier = require("./notifier.js");
var PollingBlockNotifier = require("./polling-block-notifier.js");
var SubscribingBlockNotifier = require("./subscribing-block-notifier.js");
function BlockNotifier(transport, pollingIntervalMilliseconds) {
var blockNotifier;
Notifier.call(this);
blockNotifier = new SubscribingBlockNotifier(transport, function () {
blockNotifier.destroy();
blockNotifier = new PollingBlockNotifier(transport, pollingIntervalMilliseconds);
blockNotifier.subscribe(this.notifySubscribers);
}.bind(this));
blockNotifier.subscribe(this.notifySubscribers);
this.destroy = function () {
this.unsubscribeAll();
blockNotifier.destroy();
}.bind(this);
}
BlockNotifier.prototype = Object.create(Notifier.prototype);
BlockNotifier.prototype.constructor = BlockNotifier;
module.exports = BlockNotifier;
|
Update for English Intent Classifier Bug Fix 2
|
import { PAGE_ACCESS_TOKEN } from './token';
const apiai = require('apiai');
const FBMessenger = require('fb-messenger');
const messenger = new FBMessenger(PAGE_ACCESS_TOKEN);
const app = apiai('73f11a6d692146bdb9708b4e434e7ec9');
export default function engineEnglish(data) {
const senderID = data.sender.id;
const request = app.textRequest(data.message.text, {
sessionId: senderID,
});
function isDefined(obj) {
if (typeof obj === 'undefined') {
return false;
}
if (!obj) {
return false;
}
return obj != null;
}
request.on('response', (response) => {
if (isDefined(response.result) && isDefined(response.result.fulfillment)) {
messenger.sendTextMessage(senderID, response.result.fulfillment.speech);
}
});
request.on('error', (error) => {
console.log(error);
});
request.end();
}
|
import { PAGE_ACCESS_TOKEN } from './token';
const apiai = require('apiai');
const FBMessenger = require('fb-messenger');
const messenger = new FBMessenger(PAGE_ACCESS_TOKEN);
const app = apiai('73f11a6d692146bdb9708b4e434e7ec9');
export default function engineEnglish(data) {
const senderID = data.sender.id;
const request = app.textRequest(data.message.text, {
sessionId: senderID,
});
isDefined(obj) {
if (typeof obj == 'undefined') {
return false;
}
if (!obj) {
return false;
}
return obj != null;
}
request.on('response', (response) => {
if (this.isDefined(response.result) && this.isDefined(response.result.fulfillment)) {
messenger.sendTextMessage(senderID, response.result.fulfillment.speech);
}
});
request.on('error', (error) => {
console.log(error);
});
request.end();
}
|
Change julian date to be a property.
|
import datetime
import numpy as np
class Epoch(datetime.datetime):
@property
def jd(self):
jd = (367.0 * self.year
- np.floor( (7 * (self.year + np.floor( (self.month + 9) / 12.0) ) ) * 0.25 )
+ np.floor( 275 * self.month / 9.0 )
+ self.day + 1721013.5
+ ( (self.second/60.0 + self.minute ) / 60.0 + self.hour ) / 24.0)
return jd
@property
def jd2000(self):
return self.jd - 2451544.5
@property
def jd1950(self):
return self.jd - 2433282.5
@property
def mjd(self):
return self.jd - 2400000.5
class State:
def __init__(self, x, y, z, vx, vy, vz, epoch=Epoch(2000,1,1,0,0,0)):
self.r = np.array([x, y, z])
self.v = np.array([vx, vy, vz])
self.t = epoch
|
import datetime
import numpy as np
class Epoch(datetime.datetime):
def get_jd(self, epoch=2000):
jd = (367.0 * self.year
- np.floor( (7 * (self.year + np.floor( (self.month + 9) / 12.0) ) ) * 0.25 )
+ np.floor( 275 * self.month / 9.0 )
+ self.day + 1721013.5
+ ( (self.second/60.0 + self.minute ) / 60.0 + self.hour ) / 24.0)
if epoch == 2000:
return jd - 2451544.5
elif epoch == 1950:
return jd - 2433282.5
elif epoch == "mjd":
return jd - 2400000.5
elif epoch == 0:
return jd
class State:
def __init__(self, x, y, z, vx, vy, vz, epoch=Epoch(2000,1,1,0,0,0)):
self.r = np.array([x, y, z])
self.v = np.array([vx, vy, vz])
self.t = epoch
|
Change state and method style in Tooltip
|
import styles from './Tooltip.css';
import React, { Component } from 'react';
import cx from 'classnames';
export default class Tooltip extends Component {
state = {
showToolTip: false
}
onMouseEnter = () => {
this.setState({
showToolTip: true
});
}
onMouseLeave = () => {
this.setState({
showToolTip: false
});
}
render() {
const { content, children, className, list, style } = this.props;
const tooltipClass = this.state.showToolTip ? styles.baseTooltipHover : styles.tooltip;
const tooltip = list ? styles.listTooltip : styles.showTooltip;
return (
<div
className={className}
style={style}
>
<div className={cx(tooltipClass, tooltip)}>
{content}
</div>
<div
onMouseEnter={this.onMouseEnter.bind(this)}
onMouseLeave={this.onMouseLeave.bind(this)}
>
{children}
</div>
</div>
);
}
}
|
import styles from './Tooltip.css';
import React, { Component } from 'react';
import cx from 'classnames';
export default class Tooltip extends Component {
constructor(props) {
super(props);
this.state = { showToolTip: false };
this.onMouseEnter = this.onMouseEnter.bind(this);
this.onMouseLeave = this.onMouseLeave.bind(this);
}
onMouseEnter() {
this.setState({
showToolTip: true
});
}
onMouseLeave() {
this.setState({
showToolTip: false
});
}
render() {
const { content, children, className, list, style } = this.props;
const tooltipClass = this.state.showToolTip ? styles.baseTooltipHover : styles.tooltip;
const tooltip = list ? styles.listTooltip : styles.showTooltip;
return (
<div
className={className}
style={style}
>
<div className={cx(tooltipClass, tooltip)}>
{content}
</div>
<div onMouseEnter={this.onMouseEnter} onMouseLeave={this.onMouseLeave}>
{children}
</div>
</div>
);
}
}
|
Change indentation to 2 spaces
|
from constants import *
class Buffer:
"""Stores data, buffers it and sends it to the Framer"""
def __init__(self):
self.buffer = []
self.callback = None
def attach(self, callback):
self.callback = callback
def addData(self, data):
# we can't add all the data, there's not enough space
if len(self.buffer) + len(data) > BUFFER_SIZE:
# compute remaining space
buffer_space_rem = BUFFER_SIZE - len(self.buffer)
self.buffer.append(data[:buffer_space_rem])
data = data[buffer_space_rem:]
# flush the buffer
self.flushBuffer()
# repeat till we have no data
self.addData(data)
else:
self.buffer.append(data)
def flushBuffer(self):
self.callback(self.buffer)
self.buffer = []
|
from constants import *
class Buffer:
"""Stores data, buffers it and sends it to the Framer"""
def __init__(self):
self.buffer = []
self.callback = None
def attach(self, callback):
self.callback = callback
def addData(self, data):
# we can't add all the data, there's not enough space
if len(self.buffer) + len(data) > BUFFER_SIZE:
# compute remaining space
buffer_space_rem = BUFFER_SIZE - len(self.buffer)
self.buffer.append(data[:buffer_space_rem])
data = data[buffer_space_rem:]
# flush the buffer
self.flushBuffer()
# repeat till we have no data
self.addData(data)
else:
self.buffer.append(data)
def flushBuffer(self):
self.callback(self.buffer)
self.buffer = []
|
Add package to AuthorizationException so implementors of this don't need to import that.
|
/**
* @license
* Copyright 2018 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.INTERFACE({
package: 'foam.nanos.auth',
name: 'Authorizable',
documentation: `
A model should implement this interface if it is authorizable, meaning some
users are allowed to operate on (create, read, update, or delete) that
object but others are not.
`,
methods: [
{
name: 'authorizeOnCreate',
args: [
{ name: 'x', type: 'Context' }
],
javaThrows: ['foam.nanos.auth.AuthorizationException']
},
{
name: 'authorizeOnRead',
args: [
{ name: 'x', type: 'Context' }
],
javaThrows: ['foam.nanos.auth.AuthorizationException']
},
{
name: 'authorizeOnUpdate',
args: [
{ name: 'x', type: 'Context' },
{ name: 'oldObj', type: 'foam.core.FObject' }
],
javaThrows: ['foam.nanos.auth.AuthorizationException']
},
{
name: 'authorizeOnDelete',
args: [
{ name: 'x', type: 'Context' }
],
javaThrows: ['foam.nanos.auth.AuthorizationException']
}
]
});
|
/**
* @license
* Copyright 2018 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.INTERFACE({
package: 'foam.nanos.auth',
name: 'Authorizable',
documentation: `
A model should implement this interface if it is authorizable, meaning some
users are allowed to operate on (create, read, update, or delete) that
object but others are not.
`,
methods: [
{
name: 'authorizeOnCreate',
args: [
{ name: 'x', type: 'Context' }
],
javaThrows: ['AuthorizationException'],
},
{
name: 'authorizeOnRead',
args: [
{ name: 'x', type: 'Context' }
],
javaThrows: ['AuthorizationException'],
},
{
name: 'authorizeOnUpdate',
args: [
{ name: 'x', type: 'Context' },
{ name: 'oldObj', type: 'foam.core.FObject' }
],
javaThrows: ['AuthorizationException'],
},
{
name: 'authorizeOnDelete',
args: [
{ name: 'x', type: 'Context' }
],
javaThrows: ['AuthorizationException'],
}
]
});
|
Include updating of scoped tag permissions
Addresses https://github.com/flarum/core/issues/2924
The rename `viewDiscussions` migration introduced for Flarum 1.0 does not take tag scoped permissions into account
https://github.com/flarum/core/blob/e92c267cdec46266b633f71c2f41040731cdaf39/migrations/2021_05_10_000000_rename_permissions.php#L17
This adds a new migration to additionally rename `tagX.viewDiscussions` to `tagX.viewForum`
Tested locally on an upgrade from core `beta.16` to `1.0.3`
|
<?php
/*
* This file is part of Flarum.
*
* For detailed copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/
use Illuminate\Database\Schema\Builder;
return [
'up' => function (Builder $schema) {
$db = $schema->getConnection();
$db->table('group_permission')
->where('permission', 'LIKE', '%viewDiscussions')
->update(['permission' => $db->raw("REPLACE(permission, 'viewDiscussions', 'viewForum')")]);
$db->table('group_permission')
->where('permission', 'LIKE', 'viewUserList')
->update(['permission' => $db->raw("REPLACE(permission, 'viewUserList', 'searchUsers')")]);
},
'down' => function (Builder $schema) {
$db = $schema->getConnection();
$db->table('group_permission')
->where('permission', 'LIKE', '%viewForum')
->update(['permission' => $db->raw("REPLACE(permission, 'viewForum', 'viewDiscussions')")]);
$db->table('group_permission')
->where('permission', 'LIKE', 'searchUsers')
->update(['permission' => $db->raw("REPLACE(permission, 'searchUsers', 'viewUserList')")]);
}
];
|
<?php
/*
* This file is part of Flarum.
*
* For detailed copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/
use Illuminate\Database\Schema\Builder;
return [
'up' => function (Builder $schema) {
$db = $schema->getConnection();
$db->table('group_permission')
->where('permission', 'LIKE', 'viewDiscussions')
->update(['permission' => $db->raw("REPLACE(permission, 'viewDiscussions', 'viewForum')")]);
$db->table('group_permission')
->where('permission', 'LIKE', 'viewUserList')
->update(['permission' => $db->raw("REPLACE(permission, 'viewUserList', 'searchUsers')")]);
},
'down' => function (Builder $schema) {
$db = $schema->getConnection();
$db->table('group_permission')
->where('permission', 'LIKE', 'viewForum')
->update(['permission' => $db->raw("REPLACE(permission, 'viewForum', 'viewDiscussions')")]);
$db->table('group_permission')
->where('permission', 'LIKE', 'searchUsers')
->update(['permission' => $db->raw("REPLACE(permission, 'searchUsers', 'viewUserList')")]);
}
];
|
Load string comparison algorithm from config
|
// utils -> chooseBestURL
import {
slugify,
} from 'bellajs';
import stringComparision from 'string-comparison';
import {getParserOptions} from '../config';
import {
error,
} from './logger';
export default (candidates = [], title) => {
let theBest = candidates.reduce((prev, curr) => {
return curr.length < prev.length ? curr : prev;
}, candidates[0]);
try {
const opts = getParserOptions();
const alg = opts['urlsCompareAlgorithm'];
const comparer = stringComparision[alg];
const titleHashed = slugify(title);
let g = comparer.similarity(theBest, titleHashed);
candidates.forEach((url) => {
const k = comparer.similarity(url, titleHashed);
if (k > g) {
g = k;
theBest = url;
}
});
} catch (err) {
error(err);
}
return theBest;
};
|
// utils -> chooseBestURL
import {
slugify,
} from 'bellajs';
import stringComparision from 'string-comparison';
import {
error,
} from './logger';
export default (candidates = [], title) => {
let theBest = candidates.reduce((prev, curr) => {
return curr.length < prev.length ? curr : prev;
}, candidates[0]);
try {
const ls = stringComparision.levenshtein;
const titleHashed = slugify(title);
let g = ls.similarity(theBest, titleHashed);
candidates.forEach((url) => {
const k = ls.similarity(url, titleHashed);
if (k > g) {
g = k;
theBest = url;
}
});
} catch (err) {
error(err);
}
return theBest;
};
|
Add bot-latency to ping command
|
package CoreModule
import (
"fmt"
"github.com/bwmarrin/discordgo"
"github.com/gendonl/genbot/Bot"
"time"
)
func initPingCommand() (cc CoreCommand) {
cc = CoreCommand{
name: "ping",
description: "Returns pong.",
usage: "`%sping`",
aliases: []string{},
permission: discordgo.PermissionSendMessages,
execute: (*CoreModule).pingCommand,
}
return
}
func (c *CoreModule) pingCommand(cmd CoreCommand, s *discordgo.Session, m *discordgo.MessageCreate, data *Bot.ServerData) {
ping := s.HeartbeatLatency() / time.Millisecond
response := Bot.NewEmbed().
SetColorFromUser(s, m.ChannelID, m.Author).
SetTitle("🏓 Pong").
SetDescription("Pinging...")
// Benchmark round-trip time of sent message
start := time.Now()
msg, err := s.ChannelMessageSendEmbed(m.ChannelID, response.MessageEmbed)
elapsed := time.Since(start) / time.Millisecond
if err != nil {
c.Bot.Log.Error(err)
return
}
// Add the new data of the round-trip
response.SetDescription("").
AddInlineField("Bot", fmt.Sprintf("%dms", elapsed), true).
AddInlineField("API", fmt.Sprintf("%dms", ping), true)
_, err = s.ChannelMessageEditEmbed(msg.ChannelID, msg.ID, response.MessageEmbed)
if err != nil {
c.Bot.Log.Error(err)
return
}
}
|
package CoreModule
import (
"fmt"
"github.com/bwmarrin/discordgo"
"github.com/gendonl/genbot/Bot"
"time"
)
func initPingCommand() (cc CoreCommand) {
cc = CoreCommand{
name: "ping",
description: "Returns pong.",
usage: "`%sping`",
aliases: []string{},
permission: discordgo.PermissionSendMessages,
execute: (*CoreModule).pingCommand,
}
return
}
func (c *CoreModule) pingCommand(cmd CoreCommand, s *discordgo.Session, m *discordgo.MessageCreate, data *Bot.ServerData) {
ping := s.HeartbeatLatency() / time.Millisecond
response := Bot.NewEmbed().
SetAuthorFromUser(m.Author).
SetColorFromUser(s, m.ChannelID, m.Author).
SetDescription(fmt.Sprintf("❤️ %dms", ping))
_, err := s.ChannelMessageSendEmbed(m.ChannelID, response.MessageEmbed)
if err != nil {
c.Bot.Log.Error(err)
return
}
}
|
Use session::put instead of flash, to preserve the session past multiple redirects until displayed
|
<?php namespace GeneaLabs\Bones\Flash;
final class FlashNotifier
{
public function success($message)
{
$this->message($message, 'success');
}
public function info($message)
{
$this->message($message);
}
public function warning($message)
{
$this->message($message, 'warning');
}
public function danger($message)
{
$this->message($message, 'danger');
}
public function modal($message)
{
$this->message($message);
Session::put('flashNotification.modal', true);
}
private function message($message, $level = 'info')
{
Session::put('flashNotification.message', $message);
Session::put('flashNotification.level', $level);
}
}
|
<?php namespace GeneaLabs\Bones\Flash;
use Illuminate\Session\Store;
class FlashNotifier
{
private $session;
public function __construct(Store $session)
{
$this->session = $session;
}
public function success($message)
{
$this->message($message, 'success');
}
public function info($message)
{
$this->message($message);
}
public function warning($message)
{
$this->message($message, 'warning');
}
public function danger($message)
{
$this->message($message, 'danger');
}
public function modal($message)
{
$this->message($message);
$this->session->flash('flashNotification.modal', true);
}
private function message($message, $level = 'info')
{
$this->session->flash('flashNotification.message', $message);
$this->session->flash('flashNotification.level', $level);
}
}
|
Fix typo on warning message
|
import React from 'react'
import {withReduxSaga} from 'configureStore'
import Layout from 'components/Layout'
import HomeHero from 'components/HomeHero'
import ProgramsList from 'containers/ProgramsList'
import SearchBar from 'containers/SearchBar'
class HomePage extends React.Component {
render () {
return (
<Layout>
<div id='home-page'>
<HomeHero />
<section className='section'>
<div className='notification is-warning content has-text-centered'>
Ce site est actuellement en développement actif. Merci de ne pas tenir compte des dysfonctionnements pour le moment.
</div>
<SearchBar />
<ProgramsList />
</section>
</div>
</Layout>
)
}
}
export default withReduxSaga(HomePage)
|
import React from 'react'
import {withReduxSaga} from 'configureStore'
import Layout from 'components/Layout'
import HomeHero from 'components/HomeHero'
import ProgramsList from 'containers/ProgramsList'
import SearchBar from 'containers/SearchBar'
class HomePage extends React.Component {
render () {
return (
<Layout>
<div id='home-page'>
<HomeHero />
<section className='section'>
<div className='notification is-warning content has-text-centered'>
Ce site en version Alpha est actuellement en développement actif. Merci de ne pas tenir compte des disfonctionnements pour le moment.
</div>
<SearchBar />
<ProgramsList />
</section>
</div>
</Layout>
)
}
}
export default withReduxSaga(HomePage)
|
Fix big fuckup from last commit
|
import logging
from urllib.parse import urlsplit, urljoin
from requests import get
#TODO: move this somewhere sensible
#TODO: useful error handling (CLI...)
class HTTPClient:
def __init__(self, base, user=None, password=None):
self.base = base
self.user = user
self.password = password
def get(self, url):
urlparts = urlsplit(url)
request_url = urljoin(self.base, urlparts.path)
if urlparts.query is not None:
request_url += "?" + urlparts.query
if self.user is not None:
response = get(request_url, auth=(self.user, self.password))
else:
response = get(request_url)
assert response.status_code is 200, 'Error when requesting {}.'.format(request_url)
return response.json()
|
import logging
from urllib.parse import urlsplit, urljoin
from requests import get
l = logging.getLogger(__name__)
#TODO: move this somewhere sensible
#TODO: useful error handling (CLI...)
class HTTPClient:
def __init__(self, base, user=None, password=None):
self.base = base
self.user = user
self.password = password
def get(self, url):
request_url = self.base + url
l.debug("Will now get: " + str(request_url))
if self.user is not None:
response = get(request_url, auth=(self.user, self.password))
else:
response = get(request_url)
assert response.status_code is 200, 'Error when requesting {}, response code {}.'.format(request_url, response.status_code)
# TODO: Need better error handling
return response.json()
|
Drop verison to 0.1.0 for internal release
|
#!/usr/bin/env python
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
import os.path
tests_require = [
'redis',
'unittest2',
]
setup(
name='Mule',
version='0.1.0',
author='DISQUS',
author_email='opensource@disqus.com',
url='http://github.com/disqus/mule',
description = 'Distributed Testing',
packages=find_packages(),
zip_safe=False,
install_requires=[
'celery',
'uuid',
],
dependency_links=[],
tests_require=tests_require,
extras_require={'test': tests_require},
test_suite='mule.runtests.runtests',
include_package_data=True,
entry_points = {
'console_scripts': [
'mule = mule.scripts.runner:main',
],
},
classifiers=[
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'Topic :: Software Development'
],
)
|
#!/usr/bin/env python
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
import os.path
tests_require = [
'redis',
'unittest2',
]
setup(
name='Mule',
version='1.0',
author='DISQUS',
author_email='opensource@disqus.com',
url='http://github.com/disqus/mule',
description = 'Distributed Testing',
packages=find_packages(),
zip_safe=False,
install_requires=[
'celery',
'uuid',
],
dependency_links=[],
tests_require=tests_require,
extras_require={'test': tests_require},
test_suite='mule.runtests.runtests',
include_package_data=True,
entry_points = {
'console_scripts': [
'mule = mule.scripts.runner:main',
],
},
classifiers=[
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'Topic :: Software Development'
],
)
|
Allow player to engage multiple enemies at once
|
'use strict';
module.exports = (srcPath) => {
const Broadcast = require(srcPath + 'Broadcast');
const Parser = require(srcPath + 'CommandParser').CommandParser;
return {
aliases: ['attack', 'slay'],
command : (state) => (args, player) => {
args = args.trim();
if (!args.length) {
return Broadcast.sayAt(player, 'Kill whom?');
}
let target = null;
try {
target = player.findCombatant(args);
} catch (e) {
return Broadcast.sayAt(player, e.message);
}
if (!target) {
return Broadcast.sayAt(player, "They aren't here.");
}
Broadcast.sayAt(player, `You attack ${target.name}.`);
player.initiateCombat(target);
Broadcast.sayAtExcept(player.room, `${player.name} attacks ${target.name}!`, [player, target]);
if (!target.isNpc) {
Broadcast.sayAt(target, `${player.name} attacks you!`);
}
}
};
};
|
'use strict';
module.exports = (srcPath) => {
const Broadcast = require(srcPath + 'Broadcast');
const Parser = require(srcPath + 'CommandParser').CommandParser;
return {
aliases: ['attack', 'slay'],
command : (state) => (args, player) => {
args = args.trim();
if (!args.length) {
return Broadcast.sayAt(player, 'Kill whom?');
}
if (player.isInCombat()) {
return Broadcast.sayAt(player, "You're too busy fighting!");
}
let target = null;
try {
target = player.findCombatant(args);
} catch (e) {
return Broadcast.sayAt(player, e.message);
}
if (!target) {
return Broadcast.sayAt(player, "They aren't here.");
}
Broadcast.sayAt(player, `You attack ${target.name}.`);
player.initiateCombat(target);
Broadcast.sayAtExcept(player.room, `${player.name} attacks ${target.name}!`, [player, target]);
if (!target.isNpc) {
Broadcast.sayAt(target, `${player.name} attacks you!`);
}
}
};
};
|
Fix index declaration for User model
|
var wompt = require("./includes"),
db = wompt.db;
wompt.mongoose.model('User',{
collection : 'users',
properties: [
//simple attributes
'name'
,'email'
,'one_time_token'
// embedded documents
,{
'sessions': [
['token', 'last_ip', 'session_id', 'last_used']
]
,'authentications': [
['provider','uid']
]
}
],
indexes : [
'email'
,'sessions.token',
,{'authentications.uid':1,'authentications.provider':1}
],
methods: {
wrap: function(){
return new wompt.MetaUser(this);
},
signed_up: function(){
return !!this.email || !!this.name;
},
authentication_for: function(provider){
var auths = this.authentications ;
if(!auths) return null;
var auth;
for(var i=0; auth=auths[i]; i++){
if(auth['provider'] == provider) return auth;
}
return null;
},
is_admin: function(){
return (this.email in {
'dbeardsl@gmail.com': true,
'abtinf@gmail.com': true
});
}
}
});
module.exports = db.model('User');
|
var wompt = require("./includes"),
db = wompt.db;
wompt.mongoose.model('User',{
collection : 'users',
properties: [
//simple attributes
'name'
,'email'
,'one_time_token'
// embedded documents
,{
'sessions': [
['token', 'last_ip', 'session_id', 'last_used']
]
,'authentications': [
['provider','uid']
]
}
],
indexes : [
'email'
,'sessions.token',
,'authentications'
],
methods: {
wrap: function(){
return new wompt.MetaUser(this);
},
signed_up: function(){
return !!this.email || !!this.name;
},
authentication_for: function(provider){
var auths = this.authentications ;
if(!auths) return null;
var auth;
for(var i=0; auth=auths[i]; i++){
if(auth['provider'] == provider) return auth;
}
return null;
},
is_admin: function(){
return (this.email in {
'dbeardsl@gmail.com': true,
'abtinf@gmail.com': true
});
}
}
});
module.exports = db.model('User');
|
Increase size of Google map embed
|
@extends('layouts.default')
@section('title')
{{ $venue->name }}
@endsection
@section('content-header')
<div class="row align-items-center">
<div class="col-md-auto">
<h1>{{ $venue->name }}</h1>
</div>
@canany(['update', 'delete'], $venue)
<div class="col text-right">
@include('pages.venues.partials.actions-dropdown', ['venue' => $venue])
</div>
@endcanany
</div>
{{ Breadcrumbs::render('venues.show', $venue) }}
@endsection
@section('content')
{!! Markdown::convertToHtml($venue->description) !!}
<h4>@lang('title.street-address')</h4>
<a href="https://www.google.co.uk/maps?q={{$venue->street_address}}" target="_blank">{{$venue->street_address}}</a>
<h4>@lang('title.map')</h4>
<iframe width="100%" height="500" frameborder="0" style="border:0"
src="https://www.google.com/maps/embed/v1/search?q={{$venue->street_address}}&key={{ env('GOOGLE_API_KEY') }}"
allowfullscreen></iframe>
@endsection
|
@extends('layouts.default')
@section('title')
{{ $venue->name }}
@endsection
@section('content-header')
<div class="row align-items-center">
<div class="col-md-auto">
<h1>{{ $venue->name }}</h1>
</div>
@canany(['update', 'delete'], $venue)
<div class="col text-right">
@include('pages.venues.partials.actions-dropdown', ['venue' => $venue])
</div>
@endcanany
</div>
{{ Breadcrumbs::render('venues.show', $venue) }}
@endsection
@section('content')
{!! Markdown::convertToHtml($venue->description) !!}
<h4>@lang('title.street-address')</h4>
<a href="https://www.google.co.uk/maps?q={{$venue->street_address}}" target="_blank">{{$venue->street_address}}</a>
<h4>@lang('title.map')</h4>
<iframe width="600" height="450" frameborder="0" style="border:0"
src="https://www.google.com/maps/embed/v1/search?q={{$venue->street_address}}&key={{ env('GOOGLE_API_KEY') }}"
allowfullscreen></iframe>
@endsection
|
Tag release script now works with semvers.
|
#!/usr/bin/env python
import os
import re
import sys
from distutils.version import StrictVersion
def main():
if len(sys.argv) != 2:
print('Usage: %s version' % sys.argv[0])
versions = os.popen('git tag').read().split('\n')
versions = [v for v in versions if re.match("\\d\\.\\d\\.\\d", v)]
versions.sort(key=StrictVersion)
print(versions[-1])
sys.exit()
version = sys.argv[1]
with open('floo/version.py', 'r') as fd:
version_py = fd.read().split('\n')
version_py[0] = "PLUGIN_VERSION = '%s'" % version
with open('floo/version.py', 'w') as fd:
fd.write('\n'.join(version_py))
os.system('git add packages.json floo/version.py')
os.system('git commit -m "Tag new release: %s"' % version)
os.system('git tag %s' % version)
os.system('git push --tags')
os.system('git push')
if __name__ == "__main__":
main()
|
#!/usr/bin/env python
import os
import sys
def main():
if len(sys.argv) != 2:
print('Usage: %s version' % sys.argv[0])
os.system('git tag | sort -n | tail -n 1')
sys.exit()
version = sys.argv[1]
with open('floo/version.py', 'r') as fd:
version_py = fd.read().split('\n')
version_py[0] = "PLUGIN_VERSION = '%s'" % version
with open('floo/version.py', 'w') as fd:
fd.write('\n'.join(version_py))
os.system('git add packages.json floo/version.py')
os.system('git commit -m "Tag new release: %s"' % version)
os.system('git tag %s' % version)
os.system('git push --tags')
os.system('git push')
if __name__ == "__main__":
main()
|
Fix enlace a manual certificación
|
<h1><?=$title?></h1>
<div id="navpanel">
<?php foreach ($nav as $link=>&$info): ?>
<div class="pull-left">
<div class="icon">
<a href="<?=$_base,'/',$module,$link?>" title="<?=$info['desc']?>">
<?php if (isset($info['icon'])) : ?>
<span class="<?=$info['icon']?>" aria-hidden="true" style="font-size:48px;margin-top:10px"></span>
<?php else : ?>
<img src="<?=$_base,$info['imag']?>" alt="<?=$info['name']?>" align="middle" />
<?php endif; ?>
<span><?=$info['name']?></span>
</a>
</div>
</div>
<?php endforeach; ?>
</div>
<div style="clear:both;margin-top:2em"> </div>
<a class="btn btn-primary btn-lg btn-block" href="http://wiki.libredte.cl/doku.php/faq/libredte/webapp/certificacion" role="button">
¿Cómo realizo el proceso de certificación utilizando LibreDTE?
</a>
|
<h1><?=$title?></h1>
<div id="navpanel">
<?php foreach ($nav as $link=>&$info): ?>
<div class="pull-left">
<div class="icon">
<a href="<?=$_base,'/',$module,$link?>" title="<?=$info['desc']?>">
<?php if (isset($info['icon'])) : ?>
<span class="<?=$info['icon']?>" aria-hidden="true" style="font-size:48px;margin-top:10px"></span>
<?php else : ?>
<img src="<?=$_base,$info['imag']?>" alt="<?=$info['name']?>" align="middle" />
<?php endif; ?>
<span><?=$info['name']?></span>
</a>
</div>
</div>
<?php endforeach; ?>
</div>
<div style="clear:both;margin-top:2em"> </div>
<a class="btn btn-primary btn-lg btn-block" href="http://wiki.libredte.cl/doku.php/webapp/certificacion" role="button">
¿Cómo realizo el proceso de certificación utilizando LibreDTE?
</a>
|
Remove whitespaces from lambda expression
|
import requests
import os
from .endpoints import *
class UnauthorizedToken(Exception):
pass
class ReviewsAPI:
def __init__(self):
token = os.environ['UDACITY_AUTH_TOKEN']
self.headers = {'Authorization': token, 'Content-Length': '0'}
def execute(self, request):
try:
raw_response = request()
response = raw_response.json()
raw_response.raise_for_status()
return response
except requests.exceptions.HTTPError:
raise UnauthorizedToken('Maybe it\'s time to change your token!')
def certifications(self):
return self.execute(lambda:requests.get(CERTIFICATIONS_URL, headers=self.headers))
def certified_languages(self):
response = self.execute(lambda:requests.get(REVIEWER_URL, headers=self.headers))
return [language for language in response['application']['languages']]
def request_reviews(self, projects):
return self.execute(lambda:requests.post(SUBMISSION_REQUESTS_URL, json=projects, headers=self.headers))
|
import requests
import os
from .endpoints import *
class UnauthorizedToken(Exception):
pass
class ReviewsAPI:
def __init__(self):
token = os.environ['UDACITY_AUTH_TOKEN']
self.headers = {'Authorization': token, 'Content-Length': '0'}
def execute(self, request):
try:
raw_response = request()
response = raw_response.json()
raw_response.raise_for_status()
return response
except requests.exceptions.HTTPError:
raise UnauthorizedToken('Maybe it\'s time to change your token!')
def certifications(self):
return self.execute(lambda : requests.get(CERTIFICATIONS_URL, headers=self.headers))
def certified_languages(self):
response = self.execute(lambda : requests.get(REVIEWER_URL, headers=self.headers))
return [language for language in response['application']['languages']]
def request_reviews(self, projects):
return self.execute(lambda : requests.post(SUBMISSION_REQUESTS_URL, json=projects, headers=self.headers))
|
Add react-dom to routerless renderer
|
<% if (router) {%><%- imports(
{ 'react': ['React']
, 'react-dom': ['ReactDOM']
, './components/$paramName': [name]
, 'react-router': [false, ['Router', 'Route']] }) %>
<% if (append){%>let mountNode = document.createElement('div')
document.body.appendChild(mountNode)
<%} else {%>let mountNode = document.body
<%}%>
ReactDOM.render((
<Router>
<Route path="/" component={<%= name %>}>
</Route>
</Router>
), mountNode)<%} else {%><%- imports(
{ 'react': ['React']
, 'react-dom': ['ReactDOM']
, './components/$paramName': [name] }) %>
<% if (append){%>let mountNode = document.createElement('div')
document.body.appendChild(mountNode)
<%} else {%>let mountNode = document.body
<%}%>
ReactDOM.render(<<%= name %> />, mountNode)<%}%>
|
<% if (router) {%><%- imports(
{ 'react': ['React']
, 'react-dom': ['ReactDOM']
, './components/$paramName': [name]
, 'react-router': [false, ['Router', 'Route']] }) %>
<% if (append){%>let mountNode = document.createElement('div')
document.body.appendChild(mountNode)
<%} else {%>let mountNode = document.body
<%}%>
ReactDOM.render((
<Router>
<Route path="/" component={<%= name %>}>
</Route>
</Router>
), mountNode)<%} else {%><%- imports(
{ 'react': ['React']
, './components/$paramName': [name] }) %>
<% if (append){%>let mountNode = document.createElement('div')
document.body.appendChild(mountNode)
<%} else {%>let mountNode = document.body
<%}%>
ReactDOM.render(<<%= name %> />, mountNode)<%}%>
|
Make checkbox columns automatically persistent.
svn commit r228
|
<?php
/**
* @package Swat
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* @copyright silverorange 2004
*/
require_once('Swat/SwatCellRenderer.php');
/**
* A renderer for a column of checkboxes.
*/
class SwatCellRendererCheckbox extends SwatCellRenderer {
/**
* The name attribute in the HTML input tag.
* @var string
*/
public $name;
/**
* The value attribute in the HTML input tag.
* @var string
*/
public $value;
public function render() {
$input_tag = new SwatHtmlTag('input');
$input_tag->type = 'checkbox';
$input_tag->name = $this->name.'[]';
$input_tag->value = $this->value;
if (isset($_POST[$this->name]))
if (in_array($this->value, $_POST[$this->name]))
$input_tag->checked = 'checked';
$input_tag->display();
}
}
|
<?php
/**
* @package Swat
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* @copyright silverorange 2004
*/
require_once('Swat/SwatCellRenderer.php');
/**
* A renderer for a column of checkboxes.
*/
class SwatCellRendererCheckbox extends SwatCellRenderer {
/**
* The name attribute in the HTML input tag.
* @var string
*/
public $name;
/**
* The value attribute in the HTML input tag.
* @var string
*/
public $value;
/**
* The checked attribute in the HTML input tag.
* @var boolean
*/
public $checked = false;
public function render() {
$input_tag = new SwatHtmlTag('input');
$input_tag->type = 'checkbox';
$input_tag->name = $this->name;
$input_tag->value = $this->value;
if ($this->checked)
$input_tag->checked = 'checked';
$input_tag->display();
}
}
|
Add validation to example script.
|
"""\
Usage:
dot.py [options] [<path>] [<address>]
dot.py -h | --help
dot.py --version
Where:
<path> is the file to serve
<address> is what to listen on, of the form <host>[:<port>], or just <port>
"""
import sys
from docopt import docopt
from path_and_address import resolve, split_address
def main(args=None):
"""The entry point of the application."""
if args is None:
args = sys.argv[1:]
# Parse command-line
args = docopt(__doc__, argv=args)
# Parse arguments
path, address = resolve(args['<path>'], args['<address>'])
host, port = split_address(address)
# Validate arguments
if address and not (host or port):
print 'Error: Invalid address', repr(address)
return
# Default values
if path is None:
path = '.'
if host is None:
host = 'localhost'
if port is None:
port = 5000
# Run server
print ' * Serving %s on http://%s:%s/' % (path, host, port)
if __name__ == '__main__':
main()
|
"""\
Usage:
dot.py [options] [<path>] [<address>]
dot.py -h | --help
dot.py --version
Where:
<path> is the file to serve
<address> is what to listen on, of the form <host>[:<port>], or just <port>
"""
import sys
from docopt import docopt
from path_and_address import resolve, split_address
def main(args=None):
"""The entry point of the application."""
if args is None:
args = sys.argv[1:]
# Parse command-line
args = docopt(__doc__, argv=args)
# Parse arguments
path, address = resolve(args['<path>'], args['<address>'])
host, port = split_address(address)
if path is None:
path = '.'
if host is None:
host = 'localhost'
if port is None:
port = 5000
# Run server
print ' * Serving %s on http://%s:%s/' % (path, host, port)
if __name__ == '__main__':
main()
|
Correct name for time checker spec
|
var timeCheck = require('../checks/time.js');
var expect = require('chai').expect;
var cases = require('cases');
describe('check response time', function() {
it('returns true for responses faster than or equal to the limit', cases([[0], [1], [2340], [5000]],
function(time) {
var checker = timeCheck.create(5000);
var result = checker.check('http://test.example.com/', {
status: 200
}, time);
expect(result).to.be.true();
})
);
it('returns false for responses slower than the limit', cases([[5001], [10000]],
function(time) {
var checker = timeCheck.create(5000);
var result = checker.check('http://test.example.com/', {
status: 200
}, time);
expect(result).to.be.false();
})
);
})
|
var timeCheck = require('../checks/time.js');
var expect = require('chai').expect;
var cases = require('cases');
describe('check response code', function() {
it('returns true for responses faster than or equal to the limit', cases([[0], [1], [2340], [5000]],
function(time) {
var checker = timeCheck.create(5000);
var result = checker.check('http://test.example.com/', {
status: 200
}, time);
expect(result).to.be.true();
})
);
it('returns false for responses slower than the limit', cases([[5001], [10000]],
function(time) {
var checker = timeCheck.create(5000);
var result = checker.check('http://test.example.com/', {
status: 200
}, time);
expect(result).to.be.false();
})
);
})
|
Read requirements from file to reduce duplication
|
from setuptools import setup, find_packages
def _is_requirement(line):
"""Returns whether the line is a valid package requirement."""
line = line.strip()
return line and not line.startswith("#")
def _read_requirements(filename):
"""Parses a file for pip installation requirements."""
with open(filename) as requirements_file:
contents = requirements_file.read()
return [line.strip() for line in contents.splitlines() if _is_requirement(line)]
setup(
name='smartmin',
version=__import__('smartmin').__version__,
license="BSD",
install_requires=_read_requirements("requirements/base.txt"),
tests_require=_read_requirements("requirements/tests.txt"),
description="Scaffolding system for Django object management.",
long_description=open('README.rst').read(),
author='Nyaruka Ltd',
author_email='code@nyaruka.com',
url='http://github.com/nyaruka/smartmin',
download_url='http://github.com/nyaruka/smartmin/downloads',
include_package_data=True,
packages=find_packages(),
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
]
)
|
from setuptools import setup, find_packages
setup(
name='smartmin',
version=__import__('smartmin').__version__,
license="BSD",
install_requires=[
"django>=1.7",
"django-guardian==1.3",
"django_compressor",
"pytz",
"xlrd",
"xlwt",
],
description="Scaffolding system for Django object management.",
long_description=open('README.rst').read(),
author='Nyaruka Ltd',
author_email='code@nyaruka.com',
url='http://github.com/nyaruka/smartmin',
download_url='http://github.com/nyaruka/smartmin/downloads',
include_package_data=True,
packages=find_packages(),
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
]
)
|
Change In Badge Code Js
Change In Badge Code Js
|
/********************************************************************************/
/********************************************************************************/
/*Function Calculate Current Date*/
function get_current_date(){
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){ dd='0'+dd; }
if(mm<10){ mm='0'+mm; }
var today = mm+'/'+dd+'/'+yyyy;
return today;
}
/********************************************************************************/
/********************************************************************************/
/*Function Calculate Current Date Difference*/
function get_date_difference(end_date)
{
var d1 = new Date(end_date);
var d2 = new Date(get_current_date());
var timeDiff = d1.getTime() - d2.getTime();
var DaysDiff = timeDiff / (1000 * 3600 * 24);
if(DaysDiff > 0){
$('.badges').append('<a href="http://www.greenschoolsprogramme.org/"><img src=http://www.greenschoolsprogramme.org/audit/assets/img/images/GSPLogocolour.jpg width=120px /></a>');
}
}
|
/********************************************************************************/
/********************************************************************************/
/*Function Calculate Current Date*/
function get_current_date(){
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){ dd='0'+dd; }
if(mm<10){ mm='0'+mm; }
var today = mm+'/'+dd+'/'+yyyy;
return today;
}
/********************************************************************************/
/********************************************************************************/
/*Function Calculate Current Date Difference*/
function get_date_difference(end_date)
{
var d1 = new Date(end_date);
var d2 = new Date(get_current_date());
var timeDiff = d1.getTime() - d2.getTime();
var DaysDiff = timeDiff / (1000 * 3600 * 24);
if(DaysDiff > 0){
$('.badges').append('<a href="http://www.greenschoolsprogramme.org/"><img src=http://www.greenschoolsprogramme.org/audit2017/assets/img/images/GSPLogocolour.jpg width=120px /></a>');
}
}
|
Use tclsh. Old habits die hard :)
|
#!/usr/bin/python
import os
import re
import commands
successRE = re.compile("Hello, GitHub!")
testsPassed = 0
# Add more tests here
tests = [
"bin/hello_c",
"bin/hello_cpp",
"java -cp bin hello",
"python hello.py",
"ruby hello.rb",
"perl hello.pl",
"sh hello.sh",
"tclsh hello.tcl"
]
def run_test(test):
global testsPassed
output = commands.getoutput(test)
output.rstrip()
if len(output) > 0 and successRE.match(output) != None:
testsPassed += 1
else:
print "\"{0}\" failed({1}). Number of tests executed: {2}".format(test, output, testsPassed)
exit(1)
if __name__ == '__main__':
# Change directory to previous directory where scripts are located
os.chdir ("..")
# Run the tests
for test in tests:
run_test(test)
# Print out the result
print "{0} total tests ran ".format(testsPassed)
print "All tests passed!"
|
#!/usr/bin/python
import os
import re
import commands
successRE = re.compile("Hello, GitHub!")
testsPassed = 0
# Add more tests here
tests = [
"bin/hello_c",
"bin/hello_cpp",
"java -cp bin hello",
"python hello.py",
"ruby hello.rb",
"perl hello.pl",
"sh hello.sh",
"expect hello.tcl"
]
def run_test(test):
global testsPassed
output = commands.getoutput(test)
output.rstrip()
if len(output) > 0 and successRE.match(output) != None:
testsPassed += 1
else:
print "\"{0}\" failed({1}). Number of tests executed: {2}".format(test, output, testsPassed)
exit(1)
if __name__ == '__main__':
# Change directory to previous directory where scripts are located
os.chdir ("..")
# Run the tests
for test in tests:
run_test(test)
# Print out the result
print "{0} total tests ran ".format(testsPassed)
print "All tests passed!"
|
Use a lambda to add a time delay function onto the mocked run method
|
import time
import datetime
import unittest
from unittest.mock import patch, call
from billybot.billybot import MessageTriage
class TestMessageTriage(unittest.TestCase):
def setUp(self):
self.thread1 = MessageTriage('USERID1', 'user1', 'Warren', 'testchanl')
self.thread1.daemon = True
self.thread2 = MessageTriage('USERID2', 'user2', 'Markey', 'testchanl')
self.thread2.daemon = True
self.thread3 = MessageTriage('USERID3', 'user3', 'Capuano', 'testchanl')
self.thread3.daemon = True
def test_time_alive(self):
time.sleep(3)
time_alive = self.thread1.time_alive
# Checking that time alive is around 3 but it won't be 3
# exactly, so we check that it's between 2 and 4
self.assertTrue(time_alive > 2)
self.assertTrue(time_alive < 4)
@patch('billybot.billybot.MessageTriage.run')
def test_run(self, mock_run):
mock_run.time_delay = lambda delay: time.sleep(delay)
mock_run.time_delay(5)
self.thread1.start()
self.assertTrue(1 == 2)
|
import time
import datetime
import unittest
from unittest.mock import patch, call
from billybot.billybot import MessageTriage
class TestMessageTriage(unittest.TestCase):
def setUp(self):
self.thread1 = MessageTriage('USERID1', 'user1', 'Warren', 'testchanl')
self.thread1.daemon = True
self.thread2 = MessageTriage('USERID2', 'user2', 'Markey', 'testchanl')
self.thread2.daemon = True
self.thread3 = MessageTriage('USERID3', 'user3', 'Capuano', 'testchanl')
self.thread3.daemon = True
def test_time_alive(self):
time.sleep(3)
time_alive = self.thread1.time_alive
# Checking that time alive is around 3 but it won't be 3
# exactly, so we check that it's between 2 and 4
self.assertTrue(time_alive > 2)
self.assertTrue(time_alive < 4)
@patch('billybot.billybot.MessageTriage.run')
def test_run(self, mock_run):
print(self.thread1.start())
self.assertTrue(1 == 2)
|
Attach wait function to window
|
import $ from 'jquery';
import Modernizr from 'modernizr';
const utils = {};
let running = false;
window.raf = (function () {
if (window.requestAnimationFrame) return window.requestAnimationFrame;
return function (cb) {
window.setTimeout(cb, 100);
};
})();
utils.replaceSVG = function () {
// If SVG is not supported replace it with png version
if (!Modernizr.svg) {
$('img[src*="svg"]').attr('src', () => {
return $(this).attr('src').replace('.svg', '.png');
});
}
};
utils.throttle = function (cb) {
return () => {
if (running) return;
running = true;
window.raf(() => {
cb.apply();
running = false;
});
};
};
export default utils;
|
import $ from 'jquery';
import Modernizr from 'modernizr';
const utils = {};
let running = false;
(function wait () {
if (window.requestAnimationFrame) return window.requestAnimationFrame;
return function (cb) {
window.setTimeout(cb, 100);
};
})();
utils.replaceSVG = function () {
// If SVG is not supported replace it with png version
if (!Modernizr.svg) {
$('img[src*="svg"]').attr('src', () => {
return $(this).attr('src').replace('.svg', '.png');
});
}
};
utils.throttle = function (cb) {
return () => {
if (running) return;
running = true;
wait(() => {
cb.apply();
running = false;
});
};
}
export default utils;
|
Remove unnecessary browser restrictions on tests:
Request, Rest, and Cache
|
define([
'./Store',
'./Model',
'./objectQueryEngine',
'./Memory',
// TODO: Examing the following has!host-browser checks to see if the tests can be made to run outside of a browser
'./Request',
'./Rest',
'intern/node_modules/dojo/has!host-browser?./RequestMemory',
'./Observable',
'./Cache',
'intern/node_modules/dojo/has!host-browser?./Csv',
'./Tree',
'./extensions/rqlQueryEngine',
'./validating',
'./extensions/validating-jsonSchema',
'./validators',
'./legacy/DstoreAdapter-Memory',
'./charting/StoreSeries',
'./legacy/StoreAdapter-Memory',
'intern/node_modules/dojo/has!host-browser?./legacy/StoreAdapter-JsonRest',
'./legacy/StoreAdapter-DojoData'
], function () {
});
|
define([
'./Store',
'./Model',
'./objectQueryEngine',
'./Memory',
// TODO: Examing the following has!host-browser checks to see if the tests can be made to run outside of a browser
'intern/node_modules/dojo/has!host-browser?./Request',
'intern/node_modules/dojo/has!host-browser?./Rest',
'intern/node_modules/dojo/has!host-browser?./RequestMemory',
'./Observable',
'intern/node_modules/dojo/has!host-browser?./Cache',
'intern/node_modules/dojo/has!host-browser?./Csv',
'./Tree',
'./extensions/rqlQueryEngine',
'./validating',
'./extensions/validating-jsonSchema',
'./validators',
'./legacy/DstoreAdapter-Memory',
'./charting/StoreSeries',
'./legacy/StoreAdapter-Memory',
'intern/node_modules/dojo/has!host-browser?./legacy/StoreAdapter-JsonRest',
'./legacy/StoreAdapter-DojoData'
], function () {
});
|
Fix a few namespaces to match file system.
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bridge\Doctrine\Tests\HttpFoundation;
use Symfony\Bridge\Doctrine\HttpFoundation\DbalSessionHandler;
/**
* Test class for DbalSessionHandler.
*
* @author Drak <drak@zikula.org>
*/
class DbalSessionHandlerTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
$this->markTestSkipped('The "HttpFoundation" component is not available');
}
}
public function testConstruct()
{
$this->connection = $this->getMock('Doctrine\DBAL\Driver\Connection');
$mock = $this->getMockBuilder('Symfony\Bridge\Doctrine\HttpFoundation\DbalSessionHandler');
$mock->setConstructorArgs(array($this->connection));
$this->driver = $mock->getMock();
}
}
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bridge\Doctrine\HttpFoundation;
use Symfony\Bridge\Doctrine\HttpFoundation\DbalSessionHandler;
/**
* Test class for DbalSessionHandler.
*
* @author Drak <drak@zikula.org>
*/
class DbalSessionHandlerTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
$this->markTestSkipped('The "HttpFoundation" component is not available');
}
}
public function testConstruct()
{
$this->connection = $this->getMock('Doctrine\DBAL\Driver\Connection');
$mock = $this->getMockBuilder('Symfony\Bridge\Doctrine\HttpFoundation\DbalSessionHandler');
$mock->setConstructorArgs(array($this->connection));
$this->driver = $mock->getMock();
}
}
|
Add ability to exit IO loop
|
#!/usr/bin/env node
/* eslint no-console: 0 */
const { parse, roll, pool } = require('../index.js')
const parseArgs = () => {
const args = process.argv.slice(2)
const parsedArgs = {
roller: roll,
expression: null
}
while (args.length > 0) {
const arg = args.shift()
if (arg === '-p') {
parsedArgs.roller = pool
} else {
parsedArgs.expression = arg
}
}
return parsedArgs
}
const rollDie = (string, roller) => {
try {
const die = parse(string)
console.log(roller(die))
} catch (error) {
console.log(error.message)
}
}
const runIoLoop = (roller) => {
console.log("Type 'quit' or 'exit' to exit")
process.stdin.setEncoding('utf8')
process.stdin.on('data', (string) => {
string = string.trim()
if (string === 'exit' || string === 'quit') {
process.exit(0)
}
rollDie(string, roller)
})
}
const parsedArgs = parseArgs()
if (parsedArgs.expression) {
rollDie(parsedArgs.expression, parsedArgs.roller)
} else {
runIoLoop(parsedArgs.roller)
}
|
#!/usr/bin/env node
/* eslint no-console: 0 */
const { parse, roll, pool } = require('../index.js')
const parseArgs = () => {
const args = process.argv.slice(2)
const parsedArgs = {
roller: roll,
expression: null
}
while (args.length > 0) {
const arg = args.shift()
if (arg === '-p') {
parsedArgs.roller = pool
} else {
parsedArgs.expression = arg
}
}
return parsedArgs
}
const rollDie = (string, roller) => {
try {
const die = parse(string.trim())
console.log(roller(die))
} catch (error) {
console.log(error.message)
}
}
const runIoLoop = (roller) => {
process.stdin.setEncoding('utf8')
process.stdin.on('data', (string) => {
rollDie(string, roller)
})
}
const parsedArgs = parseArgs()
if (parsedArgs.expression) {
rollDie(parsedArgs.expression, parsedArgs.roller)
} else {
runIoLoop(parsedArgs.roller)
}
|
Make @filenames return a DSHandle representing an array of strings, rather than a (Java level) array containing DSHandles representing strings.
git-svn-id: 6ee47c8665bf46900d9baa0afb711c5b4a0eafac@2958 e2bb083e-7f23-0410-b3a8-8253ac9ef6d8
|
/*
* Created on Dec 26, 2006
*/
package org.griphyn.vdl.karajan.lib.swiftscript;
import org.globus.cog.karajan.arguments.Arg;
import org.globus.cog.karajan.stack.VariableStack;
import org.globus.cog.karajan.workflow.ExecutionException;
import org.griphyn.vdl.karajan.lib.VDLFunction;
import org.griphyn.vdl.mapping.DSHandle;
import org.griphyn.vdl.mapping.InvalidPathException;
import org.griphyn.vdl.mapping.Path;
import org.griphyn.vdl.mapping.RootDataNode;
import org.griphyn.vdl.mapping.RootArrayDataNode;
import org.griphyn.vdl.type.Types;
public class FileNames extends VDLFunction {
static {
setArguments(FileNames.class, new Arg[] { PA_VAR });
}
public Object function(VariableStack stack) throws ExecutionException {
String[] f = filename(stack);
DSHandle returnArray = new RootArrayDataNode(Types.STRING.arrayType());
try {
for (int i = 0; i < f.length; i++) {
Path p = parsePath("["+i+"]", stack);
DSHandle h = returnArray.getField(p);
h.setValue(relativize(f[i]));
}
} catch (InvalidPathException e) {
throw new ExecutionException("Unexpected invalid path exception",e);
}
return returnArray;
}
}
|
/*
* Created on Dec 26, 2006
*/
package org.griphyn.vdl.karajan.lib.swiftscript;
import org.globus.cog.karajan.arguments.Arg;
import org.globus.cog.karajan.stack.VariableStack;
import org.globus.cog.karajan.workflow.ExecutionException;
import org.griphyn.vdl.karajan.lib.VDLFunction;
import org.griphyn.vdl.mapping.DSHandle;
import org.griphyn.vdl.mapping.RootDataNode;
import org.griphyn.vdl.type.Types;
public class FileNames extends VDLFunction {
static {
setArguments(FileNames.class, new Arg[] { PA_VAR });
}
public Object function(VariableStack stack) throws ExecutionException {
String[] f = filename(stack);
DSHandle[] h = new DSHandle[f.length];
for (int i = 0; i < f.length; i++) {
h[i] = RootDataNode.newNode(Types.STRING, relativize(f[i]));
}
return h;
}
}
|
Fix submitting query builder form params.
|
import Ember from 'ember';
export default Ember.Controller.extend({
tz: jstz.determine().name(),
search: '',
interval: 'day',
prefix: '0/',
region: 'world',
start_at: moment().subtract(29, 'days').format('YYYY-MM-DD'),
end_at: moment().format('YYYY-MM-DD'),
query: JSON.stringify({
condition: 'AND',
rules: [{
field: 'gatekeeper_denied_code',
id: 'gatekeeper_denied_code',
input: 'select',
operator: 'is_null',
type: 'string',
value: null,
}],
}),
beta_analytics: false,
actions: {
submit() {
if($('#filter_type_advanced').css('display') === 'none') {
this.set('search', '');
this.set('query', JSON.stringify($('#query_builder').queryBuilder('getRules')));
} else {
this.set('query', '');
this.set('search', $('#filter_form input[name=search]').val());
}
},
},
});
|
import Ember from 'ember';
export default Ember.Controller.extend({
tz: jstz.determine().name(),
search: null,
interval: 'day',
prefix: '0/',
region: 'world',
start_at: moment().subtract(29, 'days').format('YYYY-MM-DD'),
end_at: moment().format('YYYY-MM-DD'),
query: JSON.stringify({
condition: 'AND',
rules: [{
field: 'gatekeeper_denied_code',
id: 'gatekeeper_denied_code',
input: 'select',
operator: 'is_null',
type: 'string',
value: null,
}],
}),
beta_analytics: false,
actions: {
submit() {
let query = this.get('query');
query.beginPropertyChanges();
if($('#filter_type_advanced').css('display') === 'none') {
query.set('params.search', '');
query.set('params.query', JSON.stringify($('#query_builder').queryBuilder('getRules')));
} else {
query.set('params.query', '');
query.set('params.search', $('#filter_form input[name=search]').val());
}
query.endPropertyChanges();
},
},
});
|
Remove extra seating students during sync
|
#!/usr/bin/python
import logging
from datetime import date
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from validate_email import validate_email
from academics.models import Enrollment, AcademicYear
from seating_charts.models import SeatingStudent
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Sync academic students with seating students"
def handle(self, *args, **kwargs):
academic_year = AcademicYear.objects.current()
current_enrollments = Enrollment.objects.filter(student__current=True, academic_year=academic_year)
for enrollment in current_enrollments:
#Get the seating student based on the student, not the enrollment
try:
seating_student = SeatingStudent.objects.get(enrollment__student=enrollment.student)
#We found a seating student, but the enrollment was incorrect
if seating_student.enrollment != enrollment:
seating_student.enrollment = enrollment
seating_student.save()
except SeatingStudent.DoesNotExist:
#We did not find a seating student
seating_student = SeatingStudent()
seating_student.enrollment = enrollment
seating_student.save()
# Remove extra students
extra_students = SeatingStudent.objects.exclude(enrollment__student__in=[e.student for e in current_enrollments]).all()
extra_students.delete()
|
#!/usr/bin/python
import logging
from datetime import date
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from validate_email import validate_email
from academics.models import Enrollment, AcademicYear
from seating_charts.models import SeatingStudent
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Sync academic students with seating students"
def handle(self, *args, **kwargs):
academic_year = AcademicYear.objects.current()
current_enrollments = Enrollment.objects.filter(student__current=True, academic_year=academic_year)
for enrollment in current_enrollments:
#Get the seating student based on the student, not the enrollment
try:
seating_student = SeatingStudent.objects.get(enrollment__student=enrollment.student)
#We found a seating student, but the enrollment was incorrect
if seating_student.enrollment != enrollment:
seating_student.enrollment = enrollment
seating_student.save()
except SeatingStudent.DoesNotExist:
#We did not find a seating student
seating_student = SeatingStudent()
seating_student.enrollment = enrollment
seating_student.save()
|
Trim width of toggle icon column
|
$(document).ready(function() {
var container = document.getElementById("queue");
function plusRenderer (instance, td, row, col, prop, value, cellProperties) {
var plusIcon =
'<svg class="icon icon--plus" viewBox="0 0 5 5" height="20px" width="20px">' +
'<path d="M2 1 h1 v1 h1 v1 h-1 v1 h-1 v-1 h-1 v-1 h1 z" />' +
'</svg>';
$(td).empty().append(plusIcon);
}
var hot = new Handsontable(container, {
data: summaryRecords,
height: 396,
rowHeaders: true,
stretchH: 'all',
sortIndicator: true,
columnSorting: true,
contextMenu: true,
colWidths: [8, , , , , ,],
colHeaders: [
"", "Submitted cell line", "Cell line", "Cell type", "Anatomy",
"Species", "Disease"
],
columns: [
{data: "", renderer: plusRenderer},
{data: "sourceCellLine"},
{data: "annotCellLine"},
{data: "sourceCellType"},
{data: "sourceCellAnatomy"},
{data: "sourceSpecies"},
{data: "sourceDisease"}
]
});
})
|
$(document).ready(function() {
var container = document.getElementById("queue");
function plusRenderer (instance, td, row, col, prop, value, cellProperties) {
var plusIcon =
'<svg class="icon icon--plus" viewBox="0 0 5 5" height="20px" width="20px">' +
'<path d="M2 1 h1 v1 h1 v1 h-1 v1 h-1 v-1 h-1 v-1 h1 z" />' +
'</svg>';
$(td).empty().append(plusIcon);
}
var hot = new Handsontable(container, {
data: summaryRecords,
height: 396,
rowHeaders: true,
stretchH: 'all',
sortIndicator: true,
columnSorting: true,
contextMenu: true,
colHeaders: [
"", "Submitted cell line", "Cell line", "Cell type", "Anatomy",
"Species", "Disease"
],
columns: [
{data: "", renderer: plusRenderer},
{data: "sourceCellLine"},
{data: "annotCellLine"},
{data: "sourceCellType"},
{data: "sourceCellAnatomy"},
{data: "sourceSpecies"},
{data: "sourceDisease"}
]
});
})
|
Fix resource normalization for under_scored props
closes #1
|
import Ember from 'ember';
import DS from 'ember-data';
export default DS.JSONAPISerializer.extend({
_normalizeAttributes(attributes) {
var normalized = {};
Object.keys(attributes).forEach(function(key) {
normalized[Ember.String.camelize(key)] = attributes[key];
});
return normalized;
},
normalizeSingleResponse(_, __, payload) {
payload.data.attributes = this._normalizeAttributes(payload.data.attributes);
return this._super(...arguments);
},
normalizeArrayResponse(_, __, payload) {
payload.data = payload.data.map((record) => {
record.attributes = this._normalizeAttributes(record.attributes);
return record;
});
return this._super(...arguments);
},
keyForAttribute(key) {
return Ember.String.camelize(key);
}
});
|
import Ember from 'ember';
import DS from 'ember-data';
export default DS.JSONAPISerializer.extend({
_normalizeAttributes(attributes) {
var normalized = {};
Object.keys(attributes).forEach(function(key) {
normalized[Ember.String.camelize(key)] = attributes[key];
});
return normalized;
},
normalizeSingleResponse(_, __, payload) {
payload.data.attributes = this._normalizeAttributes(payload.data.attributes);
return this._super(...arguments);
},
normalizeArrayResponse(_, __, payload) {
payload.data = payload.data.map((record) => {
record.attributes = this._normalizeAttributes(record.attributes);
return record;
});
return this._super(...arguments);
}
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.