text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Add browser: true to env map to suppress eslint errors for browser globals
|
module.exports = {
"env": {
"es6": true,
"browser": true
},
"extends": "eslint:recommended",
"parserOptions": {
"sourceType": "module"
},
"rules": {
"indent": [
"warn",
"tab",
{
"SwitchCase": 1
}
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"double"
],
"semi": [
"error",
"always"
],
"no-console": [
"error",
{
allow: ["warn", "error"]
}
],
"no-unused-vars": [
"error",
{
"args": "none"
}
]
}
};
|
module.exports = {
"env": {
"es6": true
},
"extends": "eslint:recommended",
"parserOptions": {
"sourceType": "module"
},
"rules": {
"indent": [
"warn",
"tab",
{
"SwitchCase": 1
}
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"double"
],
"semi": [
"error",
"always"
],
"no-console": [
"error",
{
allow: ["warn", "error"]
}
],
"no-unused-vars": [
"error",
{
"args": "none"
}
]
}
};
|
Add safety check and remove debug message
|
package com.slugterra.packets;
import com.slugterra.entity.EntityMecha;
import io.netty.buffer.ByteBuf;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
public class MechaAnimPacket implements IMessage {
private String text;
public MechaAnimPacket() { }
public MechaAnimPacket(String text) {
this.text = text;
}
@Override
public void fromBytes(ByteBuf buf) {
text = ByteBufUtils.readUTF8String(buf); // this class is very useful in general for writing more complex objects
}
@Override
public void toBytes(ByteBuf buf) {
ByteBufUtils.writeUTF8String(buf, text);
}
public static class Handler implements IMessageHandler<MechaAnimPacket, IMessage> {
@Override
public IMessage onMessage(MechaAnimPacket message, MessageContext ctx) {
EntityPlayerMP player = ctx.getServerHandler().playerEntity;
if (player.getRidingEntity() instanceof EntityMecha)
((EntityMecha)player.getRidingEntity()).senseJump();
return null; // no response in this case
}
}
}
|
package com.slugterra.packets;
import com.slugterra.entity.EntityMecha;
import io.netty.buffer.ByteBuf;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
public class MechaAnimPacket implements IMessage {
private String text;
public MechaAnimPacket() { }
public MechaAnimPacket(String text) {
this.text = text;
}
@Override
public void fromBytes(ByteBuf buf) {
text = ByteBufUtils.readUTF8String(buf); // this class is very useful in general for writing more complex objects
}
@Override
public void toBytes(ByteBuf buf) {
ByteBufUtils.writeUTF8String(buf, text);
}
public static class Handler implements IMessageHandler<MechaAnimPacket, IMessage> {
@Override
public IMessage onMessage(MechaAnimPacket message, MessageContext ctx) {
EntityPlayerMP player = ctx.getServerHandler().playerEntity;
((EntityMecha)player.getRidingEntity()).senseJump();
System.out.println(String.format("Received %s from %s", message.text, ctx.getServerHandler().playerEntity.getDisplayName()));
return null; // no response in this case
}
}
}
|
Write original coords for versions that support position flags
|
package protocolsupport.protocol.packet.middleimpl.clientbound.play.v_1_9_r1__1_9_r2__1_10__1_11;
import protocolsupport.api.ProtocolVersion;
import protocolsupport.protocol.packet.ClientBoundPacket;
import protocolsupport.protocol.packet.middle.clientbound.play.MiddlePosition;
import protocolsupport.protocol.packet.middleimpl.ClientBoundPacketData;
import protocolsupport.protocol.serializer.VarNumberSerializer;
import protocolsupport.utils.recyclable.RecyclableCollection;
import protocolsupport.utils.recyclable.RecyclableSingletonList;
public class Position extends MiddlePosition {
@Override
public RecyclableCollection<ClientBoundPacketData> toData(ProtocolVersion version) {
ClientBoundPacketData serializer = ClientBoundPacketData.create(ClientBoundPacket.PLAY_POSITION_ID, version);
serializer.writeDouble(xOrig);
serializer.writeDouble(yOrig);
serializer.writeDouble(zOrig);
serializer.writeFloat(yawOrig);
serializer.writeFloat(pitchOrig);
serializer.writeByte(flags);
VarNumberSerializer.writeVarInt(serializer, teleportConfirmId);
return RecyclableSingletonList.create(serializer);
}
}
|
package protocolsupport.protocol.packet.middleimpl.clientbound.play.v_1_9_r1__1_9_r2__1_10__1_11;
import protocolsupport.api.ProtocolVersion;
import protocolsupport.protocol.packet.ClientBoundPacket;
import protocolsupport.protocol.packet.middle.clientbound.play.MiddlePosition;
import protocolsupport.protocol.packet.middleimpl.ClientBoundPacketData;
import protocolsupport.protocol.serializer.VarNumberSerializer;
import protocolsupport.utils.recyclable.RecyclableCollection;
import protocolsupport.utils.recyclable.RecyclableSingletonList;
public class Position extends MiddlePosition {
@Override
public RecyclableCollection<ClientBoundPacketData> toData(ProtocolVersion version) {
ClientBoundPacketData serializer = ClientBoundPacketData.create(ClientBoundPacket.PLAY_POSITION_ID, version);
serializer.writeDouble(x);
serializer.writeDouble(y);
serializer.writeDouble(z);
serializer.writeFloat(yaw);
serializer.writeFloat(pitch);
serializer.writeByte(flags);
VarNumberSerializer.writeVarInt(serializer, teleportConfirmId);
return RecyclableSingletonList.create(serializer);
}
}
|
Use shorthand url to open Travis.
|
#!/usr/bin/env node
/*
___ usage ___ en_US ___
usage: dots git issue create [options] [subject]
desciption:
Create a GitHub issue from the command line using the given subject. If the
creation is successful, the new issue number is printed to standard out.
___ . ___
*/
// TODO Really should be `dots node package --travis` or something.
require('arguable')(module, require('cadence')(function (async, program) {
var fs = require('fs')
var ok = require('assert').ok
var url = require('url')
async(function () {
fs.readFile('package.json', 'utf8', async())
}, function (body) {
var json = JSON.parse(body)
var repository = json.repository
ok(repository, 'repository defined')
ok(repository.type == 'git', 'repository is git')
console.log('https://travis-ci.org/' + repository.url)
})
}))
|
#!/usr/bin/env node
/*
___ usage ___ en_US ___
usage: dots git issue create [options] [subject]
desciption:
Create a GitHub issue from the command line using the given subject. If the
creation is successful, the new issue number is printed to standard out.
___ . ___
*/
// TODO Really should be `dots node package --travis` or something.
require('arguable')(module, require('cadence')(function (async, program) {
var fs = require('fs')
var ok = require('assert').ok
var url = require('url')
async(function () {
fs.readFile('package.json', 'utf8', async())
}, function (body) {
var json = JSON.parse(body)
var repository = json.repository
ok(repository, 'repository defined')
ok(repository.type == 'git', 'repository is git')
var loc = url.parse(repository.url)
ok(loc.host == 'github.com', 'repository is GitHub')
var ident = loc.path.replace(/\..*?$/, '').split('/').slice(1)
console.log('https://travis-ci.org/' + ident.join('/'))
})
}))
|
Resolve symbolic links for filename in Sublime view - without this all files available through symlinks are considered as new to git
|
import os
def git_file_path(view, git_path):
if not git_path:
return False
full_file_path = os.path.realpath(view.file_name())
git_path_to_file = full_file_path.replace(git_path,'')
if git_path_to_file[0] == "/":
git_path_to_file = git_path_to_file[1:]
return git_path_to_file
def git_root(directory):
if os.path.exists(os.path.join(directory, '.git')):
return directory
else:
parent = os.path.realpath(os.path.join(directory, os.path.pardir))
if parent == directory:
# we have reached root dir
return False
else:
return git_root(parent)
def git_tree(view):
full_file_path = view.file_name()
file_parent_dir = os.path.realpath(os.path.dirname(full_file_path))
return git_root(file_parent_dir)
def git_dir(directory):
if not directory:
return False
return os.path.join(directory, '.git')
|
import os
def git_file_path(view, git_path):
if not git_path:
return False
full_file_path = view.file_name()
git_path_to_file = full_file_path.replace(git_path,'')
if git_path_to_file[0] == "/":
git_path_to_file = git_path_to_file[1:]
return git_path_to_file
def git_root(directory):
if os.path.exists(os.path.join(directory, '.git')):
return directory
else:
parent = os.path.realpath(os.path.join(directory, os.path.pardir))
if parent == directory:
# we have reached root dir
return False
else:
return git_root(parent)
def git_tree(view):
full_file_path = view.file_name()
file_parent_dir = os.path.realpath(os.path.dirname(full_file_path))
return git_root(file_parent_dir)
def git_dir(directory):
if not directory:
return False
return os.path.join(directory, '.git')
|
Fix an irrelevant export name :P
|
export default class Model {
type;
attributes = [];
hasOnes = [];
hasManys = [];
constructor(type, model = null) {
this.type = type;
this.model = model;
}
attribute(name) {
this.attributes.push(name);
return this;
}
hasOne(type) {
this.hasOnes.push(type);
return this;
}
hasMany(type) {
this.hasManys.push(type);
return this;
}
extend(app, extension) {
if (this.model) {
app.store.models[this.type] = this.model;
}
const model = app.store.models[this.type];
this.attributes.forEach((name) => (model.prototype[name] = model.attribute(name)));
this.hasOnes.forEach((name) => (model.prototype[name] = model.hasOne(name)));
this.hasManys.forEach((name) => (model.prototype[name] = model.hasMany(name)));
}
}
|
export default class Routes {
type;
attributes = [];
hasOnes = [];
hasManys = [];
constructor(type, model = null) {
this.type = type;
this.model = model;
}
attribute(name) {
this.attributes.push(name);
return this;
}
hasOne(type) {
this.hasOnes.push(type);
return this;
}
hasMany(type) {
this.hasManys.push(type);
return this;
}
extend(app, extension) {
if (this.model) {
app.store.models[this.type] = this.model;
}
const model = app.store.models[this.type];
this.attributes.forEach((name) => (model.prototype[name] = model.attribute(name)));
this.hasOnes.forEach((name) => (model.prototype[name] = model.hasOne(name)));
this.hasManys.forEach((name) => (model.prototype[name] = model.hasMany(name)));
}
}
|
Fix RedirectIfAuthenticate middleware redirecting to wrong location
|
<?php
/*
* This file is part of Cachet.
*
* (c) James Brooks <james@cachethq.io>
* (c) Joseph Cohen <joseph.cohen@dinkbit.com>
* (c) Graham Campbell <graham@mineuk.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CachetHQ\Cachet\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\RedirectResponse;
class RedirectIfAuthenticated
{
/**
* The Guard implementation.
*
* @var Guard
*/
protected $auth;
/**
* Create a new filter instance.
*
* @param Guard $auth
*/
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($this->auth->check()) {
return new RedirectResponse(route('dashboard'));
}
return $next($request);
}
}
|
<?php
/*
* This file is part of Cachet.
*
* (c) James Brooks <james@cachethq.io>
* (c) Joseph Cohen <joseph.cohen@dinkbit.com>
* (c) Graham Campbell <graham@mineuk.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CachetHQ\Cachet\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\RedirectResponse;
class RedirectIfAuthenticated
{
/**
* The Guard implementation.
*
* @var Guard
*/
protected $auth;
/**
* Create a new filter instance.
*
* @param Guard $auth
*/
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($this->auth->check()) {
return new RedirectResponse(url('/home'));
}
return $next($request);
}
}
|
Fix old import of math intrinsics
|
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import llvm.core
from .intrinsic import IntrinsicLibrary
from .numba_intrinsic import is_numba_intrinsic
__all__ = []
all = {}
def _import_all():
global __all__
mods = ['string_intrinsic']
for k in mods:
mod = __import__(__name__ + '.' + k, fromlist=['__all__'])
__all__.extend(mod.__all__)
for k in mod.__all__:
all[k] = globals()[k] = getattr(mod, k)
_import_all()
def default_intrinsic_library(context):
'''Build an intrinsic library with a default set of external functions.
context --- numba context
TODO: It is possible to cache the default intrinsic library as a bitcode
file on disk so that we don't build it every time.
'''
intrlib = IntrinsicLibrary(context)
# install intrinsics
for fncls in all.itervalues():
intrlib.add(fncls)
return intrlib
|
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import llvm.core
from .intrinsic import IntrinsicLibrary
from .numba_intrinsic import is_numba_intrinsic
__all__ = []
all = {}
def _import_all():
global __all__
mods = ['math_intrinsic',
'string_intrinsic']
for k in mods:
mod = __import__(__name__ + '.' + k, fromlist=['__all__'])
__all__.extend(mod.__all__)
for k in mod.__all__:
all[k] = globals()[k] = getattr(mod, k)
_import_all()
def default_intrinsic_library(context):
'''Build an intrinsic library with a default set of external functions.
context --- numba context
TODO: It is possible to cache the default intrinsic library as a bitcode
file on disk so that we don't build it every time.
'''
intrlib = IntrinsicLibrary(context)
# install intrinsics
for fncls in all.itervalues():
intrlib.add(fncls)
return intrlib
|
Add footnotes to the Reader.
|
/* eslint-disable no-template-curly-in-string */
import { BasePackage, ModelComponentPackage } from '../../kit'
import ArticleNavPackage from '../ArticleNavPackage'
import EntityLabelsPackage from '../shared/EntityLabelsPackage'
import ManuscriptContentPackage from '../shared/ManuscriptContentPackage'
import ReferenceListComponent from '../shared/ReferenceListComponent'
import FootnoteGroupComponent from '../shared/FootnoteGroupComponent'
export default {
name: 'ArticleReader',
configure (config) {
config.import(BasePackage)
config.import(ModelComponentPackage)
config.import(ManuscriptContentPackage)
config.import(EntityLabelsPackage)
config.import(ArticleNavPackage)
config.addComponent('references', ReferenceListComponent)
config.addComponent('footnotes', FootnoteGroupComponent)
config.addToolPanel('toolbar', [
{
name: 'mode',
type: 'tool-dropdown',
showDisabled: false,
style: 'full',
items: [
{ type: 'command-group', name: 'switch-view' }
]
}
])
}
}
|
/* eslint-disable no-template-curly-in-string */
import { BasePackage, ModelComponentPackage } from '../../kit'
import ArticleNavPackage from '../ArticleNavPackage'
import EntityLabelsPackage from '../shared/EntityLabelsPackage'
import ManuscriptContentPackage from '../shared/ManuscriptContentPackage'
import ReferenceListComponent from '../shared/ReferenceListComponent'
export default {
name: 'ArticleReader',
configure (config) {
config.import(BasePackage)
config.import(ModelComponentPackage)
config.import(ManuscriptContentPackage)
config.import(EntityLabelsPackage)
config.import(ArticleNavPackage)
config.addComponent('references', ReferenceListComponent)
config.addToolPanel('toolbar', [
{
name: 'mode',
type: 'tool-dropdown',
showDisabled: false,
style: 'full',
items: [
{ type: 'command-group', name: 'switch-view' }
]
}
])
}
}
|
Fix onBuild callback for webpack watch mode, now it properly outputs what it should to the log (screen). Also microrefactor the webpack calling code.
|
var gulp = require('gulp');
var nodemon = require('nodemon');
var webpack = require('webpack');
var clientConfig = require('./webpack.config');
var path = require('path');
var wpCompiler = webpack(clientConfig);
function onBuild(cb) {
return function(err, stats) {
if (err)
console.log('Error', err);
else
console.log(stats.toString());
if (cb) cb();
}
}
// Serverside (backend) tasks group
// Nothing so far!
// Clientside (frontend) tasks
gulp.task('client-watch', function() {
// Changes within 100 ms = one rebuild
wpCompiler.watch({
aggregateTimeout: 100
},
onBuild());
});
gulp.task('client-build', function(cb) {
wpCompiler.run(onBuild(cb));
});
// Group tasks
// For development - rebuilds whenever something changes
gulp.task('watch', ['client-watch']);
// For production - builds everything
gulp.task('build', ['client-build']);
// Nodemon is used. Maybe it's better to use gulp's own watch system?
gulp.task('run', ['client-watch'], function() {
nodemon({
execMap: {
js: 'node'
},
script: path.join(__dirname, 'server/main.js'),
ext: 'js json'
}).on('restart', function() {
console.log('Restarted!');
});
});
|
var gulp = require('gulp');
var nodemon = require('nodemon');
var webpack = require('webpack');
var clientConfig = require('./webpack.config');
var path = require('path');
function onBuild(cb) {
return function(err, stats) {
if (err)
console.log('Error', err);
else
console.log(stats.toString());
if (cb) cb();
}
}
// Serverside (backend) tasks group
// Nothing so far!
// Clientside (frontend) tasks
gulp.task('client-watch', function() {
// Changes within 100 ms = one rebuild
webpack(clientConfig).watch(100, onBuild);
});
gulp.task('client-build', function(cb) {
webpack(clientConfig).run(onBuild(cb));
});
// Group tasks
// For development - rebuilds whenever something changes
gulp.task('watch', ['client-watch']);
// For production - builds everything
gulp.task('build', ['client-build']);
// Nodemon is used. Maybe it's better to use gulp's own watch system?
gulp.task('run', ['client-watch'], function() {
nodemon({
execMap: {
js: 'node'
},
script: path.join(__dirname, 'server/main.js'),
ext: 'js json'
}).on('restart', function() {
console.log('Restarted!');
});
});
|
Add untested support for the darwin platform
git-svn-id: 30e8e193f18ae0331cc1220771e45549f871ece9@762 b426a367-1105-0410-b9ff-cdf4ab011145
|
"""
Exports the libgeos_c shared lib, GEOS-specific exceptions, and utilities.
"""
import atexit
from ctypes import CDLL, CFUNCTYPE, c_char_p
import sys
# The GEOS shared lib
if sys.platform == 'win32':
dll = 'libgeos_c-1.dll'
elif sys.platform == 'darwin':
dll = 'libgeos_c.dylib'
else:
dll = 'libgeos_c.so'
lgeos = CDLL(dll)
# Exceptions
class ReadingError(Exception):
pass
class DimensionError(Exception):
pass
class TopologicalError(Exception):
pass
class PredicateError(Exception):
pass
# GEOS error handlers, which currently do nothing.
def error_handler(fmt, list):
pass
error_h = CFUNCTYPE(None, c_char_p, c_char_p)(error_handler)
def notice_handler(fmt, list):
pass
notice_h = CFUNCTYPE(None, c_char_p, c_char_p)(notice_handler)
# Init geos, and register a cleanup function
lgeos.initGEOS(notice_h, error_h)
atexit.register(lgeos.finishGEOS)
|
"""
Exports the libgeos_c shared lib, GEOS-specific exceptions, and utilities.
"""
import atexit
from ctypes import CDLL, CFUNCTYPE, c_char_p
import os, sys
# The GEOS shared lib
if os.name == 'nt':
dll = 'libgeos_c-1.dll'
else:
dll = 'libgeos_c.so'
lgeos = CDLL(dll)
# Exceptions
class ReadingError(Exception):
pass
class DimensionError(Exception):
pass
class TopologicalError(Exception):
pass
class PredicateError(Exception):
pass
# GEOS error handlers, which currently do nothing.
def error_handler(fmt, list):
pass
error_h = CFUNCTYPE(None, c_char_p, c_char_p)(error_handler)
def notice_handler(fmt, list):
pass
notice_h = CFUNCTYPE(None, c_char_p, c_char_p)(notice_handler)
# Init geos, and register a cleanup function
lgeos.initGEOS(notice_h, error_h)
atexit.register(lgeos.finishGEOS)
|
Use addEventListener instead of setting old onmouse* properties
|
var STATUSES = {
UP: 0,
DOWN: 1
}
var mouseStatus = {
left: STATUSES.UP,
right: STATUSES.UP
}
var BUTTONS = {
LEFT: 1,
RIGHT: 3
};
document.addEventListener('mousedown', function(event) {
if (event.which === BUTTONS.LEFT) {
mouseStatus.left = STATUSES.DOWN;
if (mouseStatus.right === STATUSES.DOWN) {
chrome.extension.sendMessage({
event: 'previous',
mouseStatus: mouseStatus
});
}
} else if (event.which === BUTTONS.RIGHT) {
mouseStatus.right = STATUSES.DOWN;
if (mouseStatus.left === STATUSES.DOWN) {
chrome.extension.sendMessage({
event: 'next',
mouseStatus: mouseStatus
});
}
}
});
document.addEventListener('mouseup', function(event) {
if (event.which === BUTTONS.LEFT) {
mouseStatus.left = STATUSES.UP;
} else if (event.which === BUTTONS.RIGHT) {
mouseStatus.right = STATUSES.UP;
}
chrome.extension.sendMessage({mouseStatus: mouseStatus});
});
document.addEventListener('contextmenu', function(event) {
if (mouseStatus.left === STATUSES.DOWN) {
return event.preventDefault();
}
});
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
mouseStatus = request;
});
|
var STATUSES = {
UP: 0,
DOWN: 1
}
var mouseStatus = {
left: STATUSES.UP,
right: STATUSES.UP
}
var BUTTONS = {
LEFT: 1,
RIGHT: 3
};
document.onmousedown = function(event) {
if (event.which === BUTTONS.LEFT) {
mouseStatus.left = STATUSES.DOWN;
if (mouseStatus.right === STATUSES.DOWN) {
chrome.extension.sendMessage({
event: 'previous',
mouseStatus: mouseStatus
});
}
} else if (event.which === BUTTONS.RIGHT) {
mouseStatus.right = STATUSES.DOWN;
if (mouseStatus.left === STATUSES.DOWN) {
chrome.extension.sendMessage({
event: 'next',
mouseStatus: mouseStatus
});
}
}
};
document.onmouseup = function(event) {
if (event.which === BUTTONS.LEFT) {
mouseStatus.left = STATUSES.UP;
} else if (event.which === BUTTONS.RIGHT) {
mouseStatus.right = STATUSES.UP;
}
chrome.extension.sendMessage({mouseStatus: mouseStatus});
};
document.oncontextmenu = function(event) {
if (mouseStatus.left === STATUSES.DOWN) {
return false;
}
};
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
mouseStatus = request;
});
|
Set tag default as enable
|
<?php
namespace Purethink\CoreBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Gedmo\SoftDeleteable\SoftDeleteable;
use Gedmo\SoftDeleteable\Traits\SoftDeleteableEntity;
use Sonata\ClassificationBundle\Entity\BaseTag;
/**
* @ORM\Table(name="cms_tag")
* @ORM\Entity()
* @Gedmo\SoftDeleteable(fieldName="deletedAt")
*/
class Tag extends BaseTag implements SoftDeleteable
{
use SoftDeleteableEntity;
/**
* @var int
*
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
public function __construct()
{
$this->enabled = true;
}
/**
* @return int
*/
public function getId()
{
return $this->id;
}
}
|
<?php
namespace Purethink\CoreBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Gedmo\SoftDeleteable\SoftDeleteable;
use Gedmo\SoftDeleteable\Traits\SoftDeleteableEntity;
use Sonata\ClassificationBundle\Entity\BaseTag;
/**
* @ORM\Table(name="cms_tag")
* @ORM\Entity()
* @Gedmo\SoftDeleteable(fieldName="deletedAt")
*/
class Tag extends BaseTag implements SoftDeleteable
{
use SoftDeleteableEntity;
/**
* @var int
*
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @return int
*/
public function getId()
{
return $this->id;
}
}
|
Add a sample of ES6
|
#!/usr/bin/env babel-node
import assert from 'assert';
//
// 分割代入内で代入ができる
//
function getObj() {
return {
x: 2,
y: 3
};
}
let {
x,
y,
z = 6
} = getObj();
assert.strictEqual(x, 2);
assert.strictEqual(y, 3);
assert.strictEqual(z, 6);
//
// 別変数名で展開できる
//
function stringifyObj({ x: xVar, y: yVar }) {
return xVar + yVar;
}
assert.strictEqual(stringifyObj({ x: 'foo', y: 'bar' }), 'foobar');
//
// 分割代入内で初期値を設定する
//
function useDefault({ x, y = 3 }) {
return x * y;
}
assert.strictEqual(useDefault({ x: 2}), 6);
assert.strictEqual(useDefault({ x: 2, y: 4}), 8);
//
//
//
let requirementWithOptions = {
requirementA: 1,
requirementB: 2,
a: 11,
b: 22,
};
const {
requirementA,
requirementB,
...options,
} = requirementWithOptions;
assert.strictEqual(requirementA, 1);
assert.strictEqual(requirementB, 2);
assert.deepEqual(options, {
a: 11,
b: 22,
});
|
#!/usr/bin/env babel-node
import assert from 'assert';
//
// 分割代入内で代入ができる
//
function getObj() {
return {
x: 2,
y: 3
};
}
let {
x,
y,
z = 6
} = getObj();
assert.strictEqual(x, 2);
assert.strictEqual(y, 3);
assert.strictEqual(z, 6);
//
// 別変数名で展開できる
//
function stringifyObj({ x: xVar, y: yVar }) {
return xVar + yVar;
}
assert.strictEqual(stringifyObj({ x: 'foo', y: 'bar' }), 'foobar');
//
// 分割代入内で初期値を設定する
//
function useDefault({ x, y = 3 }) {
return x * y;
}
assert.strictEqual(useDefault({ x: 2}), 6);
assert.strictEqual(useDefault({ x: 2, y: 4}), 8);
|
Initialize Hue service at startup
|
Nbsp = {};
Nbsp.updateColor = function() {
var red = Session.get('red'),
green = Session.get('green'),
blue = Session.get('blue');
$('body').css({
'background-color': 'rgb(' + red + ', ' + green + ', ' + blue + ')'
});
}
if (Meteor.isClient) {
Session.setDefault('red', 0);
Session.setDefault('green', 0);
Session.setDefault('blue', 0);
Template.form.onCreated(function() {
Nbsp.updateColor();
});
Template.form.helpers({
counter: function () {
return Session.get('counter');
}
});
Template.form.events({
'change input': function (event) {
Session.set(event.target.id, event.target.value)
Nbsp.updateColor();
}
});
}
if (Meteor.isServer) {
Meteor.startup(function () {
let hueSettings = Meteor.settings.hue || Meteor.settings.public.hue;
if (!hueSettings) {
throw new Meteor.Error(500, "Hue credentials not available.");
}
Nbsp.hue = new HueBridge(hueSettings.server, hueSettings.username);
});
}
|
Nbsp = {};
Nbsp.updateColor = function() {
var red = Session.get('red'),
green = Session.get('green'),
blue = Session.get('blue');
$('body').css({
'background-color': 'rgb(' + red + ', ' + green + ', ' + blue + ')'
});
}
if (Meteor.isClient) {
Session.setDefault('red', 0);
Session.setDefault('green', 0);
Session.setDefault('blue', 0);
Template.form.onCreated(function() {
Nbsp.updateColor();
});
Template.form.helpers({
counter: function () {
return Session.get('counter');
}
});
Template.form.events({
'change input': function (event) {
Session.set(event.target.id, event.target.value)
Nbsp.updateColor();
$('')
}
});
}
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
});
}
|
Change calls to Titanium to Ti
|
var tray = Ti.UI.addTray('tray.png'),
menu = Ti.UI.createMenu(),
//Add some menu items
menuItems = [
Ti.UI.createMenuItem('Change Icon', function(e) {
//Something's going on... let's change the icon.
tray.setIcon('tray-active.png');
setTimeout(function() {
tray.setIcon('tray.png');
}, 3000);
}),
Ti.UI.createMenuItem('Cat', function(e) {
alert('Meow Meow');
}),
Ti.UI.createMenuItem('Quit', function(e) {
confirm('You sure?', function() {
Ti.App.exit();
});
})
];
menuItems.forEach(function(item) {
menu.appendItem(item);
});
tray.setMenu(menu);
|
var tray = Ti.UI.addTray('tray.png'),
menu = Ti.UI.createMenu(),
//Add some menu items
menuItems = [
Titanium.UI.createMenuItem('Change Icon', function(e) {
//Something's going on... let's change the icon.
tray.setIcon('tray-active.png');
setTimeout(function() {
tray.setIcon('tray.png');
}, 3000);
}),
Titanium.UI.createMenuItem('Cat', function(e) {
alert('Meow Meow');
}),
Titanium.UI.createMenuItem('Quit', function(e) {
confirm('You sure?', function() {
Ti.App.exit();
});
})
];
menuItems.forEach(function(item) {
menu.appendItem(item);
});
tray.setMenu(menu);
|
Rework tmpdir for nose (no pytest)
|
import os
import tempfile
import fiona
def test_profile():
with fiona.open('tests/data/coutwildrnp.shp') as src:
assert src.meta['crs_wkt'] == 'GEOGCS["GCS_WGS_1984",DATUM["WGS_1984",SPHEROID["WGS_84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295],AUTHORITY["EPSG","4326"]]'
def test_profile_creation_wkt():
tmpdir = tempfile.mkdtemp()
outfilename = os.path.join(tmpdir, 'test.shp')
with fiona.open('tests/data/coutwildrnp.shp') as src:
profile = src.meta
profile['crs'] = 'bogus'
with fiona.open(outfilename, 'w', **profile) as dst:
assert dst.crs == {'init': 'epsg:4326'}
assert dst.crs_wkt == 'GEOGCS["GCS_WGS_1984",DATUM["WGS_1984",SPHEROID["WGS_84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295],AUTHORITY["EPSG","4326"]]'
|
import fiona
def test_profile():
with fiona.open('tests/data/coutwildrnp.shp') as src:
assert src.meta['crs_wkt'] == 'GEOGCS["GCS_WGS_1984",DATUM["WGS_1984",SPHEROID["WGS_84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295],AUTHORITY["EPSG","4326"]]'
def test_profile_creation_wkt(tmpdir):
outfilename = str(tmpdir.join('test.shp'))
with fiona.open('tests/data/coutwildrnp.shp') as src:
profile = src.meta
profile['crs'] = 'bogus'
with fiona.open(outfilename, 'w', **profile) as dst:
assert dst.crs == {'init': 'epsg:4326'}
assert dst.crs_wkt == 'GEOGCS["GCS_WGS_1984",DATUM["WGS_1984",SPHEROID["WGS_84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295],AUTHORITY["EPSG","4326"]]'
|
Update to prims 1.10 version
|
from django.conf import settings
def get_language_choices():
"""
Default list of language choices, if not overridden by Django.
"""
DEFAULT_LANGUAGES = (
('bash', 'Bash/Shell'),
('css', 'CSS'),
('diff', 'diff'),
('http', 'HTML'),
('javascript', 'Javascript'),
('json', 'JSON'),
('python', 'Python'),
('scss', 'SCSS'),
('yaml', 'YAML'),
)
return getattr(settings, "WAGTAIL_CODE_BLOCK_LANGUAGES", DEFAULT_LANGUAGES)
def get_theme():
"""
Returns a default theme, if not in the proejct's settings. Default theme is 'coy'.
"""
return getattr(settings, "WAGTAIL_CODE_BLOCK_THEME", 'coy')
def get_prism_version():
prism_version = "1.10.0"
return prism_version
|
from django.conf import settings
def get_language_choices():
"""
Default list of language choices, if not overridden by Django.
"""
DEFAULT_LANGUAGES = (
('bash', 'Bash/Shell'),
('css', 'CSS'),
('diff', 'diff'),
('http', 'HTML'),
('javascript', 'Javascript'),
('json', 'JSON'),
('python', 'Python'),
('scss', 'SCSS'),
('yaml', 'YAML'),
)
return getattr(settings, "WAGTAIL_CODE_BLOCK_LANGUAGES", DEFAULT_LANGUAGES)
def get_theme():
"""
Returns a default theme, if not in the proejct's settings. Default theme is 'coy'.
"""
return getattr(settings, "WAGTAIL_CODE_BLOCK_THEME", 'coy')
def get_prism_version():
prism_version = "1.9.0"
return prism_version
|
Clarify comments about overloaded constructor
|
package com.example.android.miwok;
public class Word {
private String mMiwokWord;
private String mEnglishWord;
private int mImageResourceId;
private int mRawResourceId;
// Constructor setter method
// @params strings miwokWord and englishWord, int rawResourceId
// Sets private strings mMiwokWord and mEnglishWord
public Word(String miwokWord, String englishWord, int rawResourceId) {
mMiwokWord = miwokWord;
mEnglishWord = englishWord;
mRawResourceId = rawResourceId;
} // Close method Word()
// Constructor setter method, overloaded
// Extra @param imageResourceId
public Word(String miwokWord, String englishWord, int imageResourceId, int rawResourceId) {
mMiwokWord = miwokWord;
mEnglishWord = englishWord;
mImageResourceId = imageResourceId;
mRawResourceId = rawResourceId;
} // Close method Word()
// Getter method to retrieve private string mMiwokWord
public String getmMiwokWord() {
return mMiwokWord;
}
// Getter method to retrieve private string mEnglishWord
public String getmEnglishWord() {
return mEnglishWord;
}
// Getter method to retrieve res ID for icon image resource;
public int getmImageResourceId() { return mImageResourceId; }
// Getter method to retrieve res ID for mp3 resource;
public int getmRawResourceId() { return mRawResourceId; }
} // Close class Word
|
package com.example.android.miwok;
public class Word {
private String mMiwokWord;
private String mEnglishWord;
private int mImageResourceId;
private int mRawResourceId;
// Constructor setter method
// @params strings miwokWord and englishWord
// Sets private strings mMiwokWord and mEnglishWord
public Word(String miwokWord, String englishWord, int rawResourceId) {
mMiwokWord = miwokWord;
mEnglishWord = englishWord;
mRawResourceId = rawResourceId;
} // Close method Word()
public Word(String miwokWord, String englishWord, int imageResourceId, int rawResourceId) {
mMiwokWord = miwokWord;
mEnglishWord = englishWord;
mImageResourceId = imageResourceId;
mRawResourceId = rawResourceId;
} // Close method Word()
// Getter method to retrieve private string mMiwokWord
public String getmMiwokWord() {
return mMiwokWord;
}
// Getter method to retrieve private string mEnglishWord
public String getmEnglishWord() {
return mEnglishWord;
}
// Getter method to retrieve res ID for icon image resource;
public int getmImageResourceId() { return mImageResourceId; }
// Getter method to retrieve res ID for mp3 resource;
public int getmRawResourceId() { return mRawResourceId; }
} // Close class Word
|
Add links to site detail in site list
|
from django.conf import settings
from django.contrib.gis.db import models
from django.utils.translation import gettext_lazy as _
from geotrek.authent.models import StructureRelated
from geotrek.common.mixins import NoDeleteMixin, TimeStampedModelMixin, AddPropertyMixin
from mapentity.models import MapEntityMixin
class Site(AddPropertyMixin, MapEntityMixin, StructureRelated,
TimeStampedModelMixin, NoDeleteMixin):
geom = models.GeometryField(verbose_name=_("Location"), srid=settings.SRID)
name = models.CharField(verbose_name=_("Name"), max_length=128)
description = models.TextField(verbose_name=_("Description"), blank=True)
eid = models.CharField(verbose_name=_("External id"), max_length=1024, blank=True, null=True)
class Meta:
verbose_name = _("Site")
verbose_name_plural = _("Sites")
ordering = ('name', )
def __str__(self):
return self.name
@property
def name_display(self):
return '<a data-pk="{pk}" href="{url}" title="{name}">{name}</a>'.format(
pk=self.pk,
url=self.get_detail_url(),
name=self.name
)
|
from django.conf import settings
from django.contrib.gis.db import models
from django.utils.translation import gettext_lazy as _
from geotrek.authent.models import StructureRelated
from geotrek.common.mixins import NoDeleteMixin, TimeStampedModelMixin, AddPropertyMixin
from mapentity.models import MapEntityMixin
class Site(AddPropertyMixin, MapEntityMixin, StructureRelated,
TimeStampedModelMixin, NoDeleteMixin):
geom = models.GeometryField(verbose_name=_("Location"), srid=settings.SRID)
name = models.CharField(verbose_name=_("Name"), max_length=128)
description = models.TextField(verbose_name=_("Description"), blank=True)
eid = models.CharField(verbose_name=_("External id"), max_length=1024, blank=True, null=True)
class Meta:
verbose_name = _("Site")
verbose_name_plural = _("Sites")
ordering = ('name', )
def __str__(self):
return self.name
|
Test exit status when no program
|
package main
import (
"testing"
. "github.com/VonC/godbg"
"github.com/VonC/godbg/exit"
. "github.com/smartystreets/goconvey/convey"
)
func TestMain(t *testing.T) {
exiter = exit.New(func(int) {})
Convey("senvgo main installation scenario with no command", t, func() {
SetBuffers(nil)
main()
So(ErrString(), ShouldEqualNL, ` [main:7] (func.001:14)
senvgo
`)
So(exiter.Status(), ShouldEqual, 0)
Convey("No prg means no prgs installed", func() {
SetBuffers(nil)
main()
So(OutString(), ShouldEqual, `No program to install: nothing to do`)
So(ErrString(), ShouldEqualNL, ` [main:7] (func.001:14)
senvgo
`)
So(exiter.Status(), ShouldEqual, 0)
})
})
}
|
package main
import (
"testing"
. "github.com/VonC/godbg"
"github.com/VonC/godbg/exit"
. "github.com/smartystreets/goconvey/convey"
)
func TestMain(t *testing.T) {
exiter = exit.New(func(int) {})
Convey("senvgo main installation scenario with no command", t, func() {
SetBuffers(nil)
main()
So(ErrString(), ShouldEqualNL, ` [main:7] (func.001:14)
senvgo
`)
So(exiter.Status(), ShouldEqual, 0)
Convey("No prg means no prgs installed", func() {
SetBuffers(nil)
main()
So(OutString(), ShouldEqual, `No program to install: nothing to do`)
So(ErrString(), ShouldEqualNL, ` [main:7] (func.001:14)
senvgo
`)
})
})
}
|
Add a wan simulator to reproduce timing sensitive issues with a random 0.5 ms delay.
|
package net.openhft.chronicle.network;
import net.openhft.chronicle.core.Jvm;
import java.util.Random;
/**
* Created by peter.lawrey on 16/07/2015.
*/
public enum WanSimulator {
;
private static final int NET_BANDWIDTH = Integer.getInteger("wanMB", 0);
private static final int BYTES_PER_MS = NET_BANDWIDTH * 1000;
private static final Random RANDOM = new Random();
private static long totalRead = 0;
public static void dataRead(int bytes) {
if (NET_BANDWIDTH <= 0) return;
totalRead += bytes + RANDOM.nextInt(BYTES_PER_MS);
int delay = (int) (totalRead / BYTES_PER_MS);
if (delay > 0) {
Jvm.pause(delay);
totalRead = 0;
}
}
}
|
package net.openhft.chronicle.network;
import net.openhft.chronicle.core.Jvm;
/**
* Created by peter.lawrey on 16/07/2015.
*/
public enum WanSimulator {
;
private static final int NET_BANDWIDTH = Integer.getInteger("wanMB", 0);
private static final int BYTES_PER_MS = NET_BANDWIDTH * 1000;
private static long totalRead = 0;
public static void dataRead(int bytes) {
if (NET_BANDWIDTH <= 0) return;
totalRead += bytes + 128;
int delay = (int) (totalRead / BYTES_PER_MS);
if (delay > 0) {
Jvm.pause(delay);
totalRead = 0;
}
}
}
|
Add checking if workflow-durable-task-step plugin is active
|
package jenkins.advancedqueue;
import hudson.Plugin;
import hudson.model.Job;
import hudson.model.Queue;
import jenkins.advancedqueue.sorter.ItemInfo;
import jenkins.advancedqueue.sorter.QueueItemCache;
import jenkins.model.Jenkins;
import org.jenkinsci.plugins.workflow.support.steps.ExecutorStepExecution;
class PriorityConfigurationPlaceholderTaskHelper {
boolean isPlaceholderTask(Queue.Task task) {
return isPlaceholderTaskUsed() && task instanceof ExecutorStepExecution.PlaceholderTask;
}
PriorityConfigurationCallback getPriority(ExecutorStepExecution.PlaceholderTask task, PriorityConfigurationCallback priorityCallback) {
Job<?, ?> job = (Job<?, ?>) task.getOwnerTask();
ItemInfo itemInfo = QueueItemCache.get().getItem(job.getName());
itemInfo.getPriority();
priorityCallback.setPrioritySelection(itemInfo.getPriority());
return priorityCallback;
}
static boolean isPlaceholderTaskUsed() {
Plugin plugin = Jenkins.getInstance().getPlugin("workflow-durable-task-step");
return plugin != null && plugin.getWrapper().isActive();
}
}
|
package jenkins.advancedqueue;
import hudson.model.Job;
import hudson.model.Queue;
import jenkins.advancedqueue.sorter.ItemInfo;
import jenkins.advancedqueue.sorter.QueueItemCache;
import jenkins.model.Jenkins;
import org.jenkinsci.plugins.workflow.support.steps.ExecutorStepExecution;
class PriorityConfigurationPlaceholderTaskHelper {
boolean isPlaceholderTask(Queue.Task task) {
return isPlaceholderTaskUsed() && task instanceof ExecutorStepExecution.PlaceholderTask;
}
PriorityConfigurationCallback getPriority(ExecutorStepExecution.PlaceholderTask task, PriorityConfigurationCallback priorityCallback) {
Job<?, ?> job = (Job<?, ?>) task.getOwnerTask();
ItemInfo itemInfo = QueueItemCache.get().getItem(job.getName());
itemInfo.getPriority();
priorityCallback.setPrioritySelection(itemInfo.getPriority());
return priorityCallback;
}
static boolean isPlaceholderTaskUsed() {
return Jenkins.getInstance().getPlugin("workflow-durable-task-step") != null;
}
}
|
[WEB-559] Fix issue with button focus styles
|
export default ({ colors, borders }) => ({
primary: {
backgroundColor: colors.purpleMedium,
border: borders.input,
borderColor: colors.purpleMedium,
color: colors.white,
'&:hover,&:active': {
backgroundColor: colors.text.primary,
borderColor: colors.text.primary,
},
'&:disabled': {
backgroundColor: colors.lightestGrey,
borderColor: colors.lightestGrey,
color: colors.text.primaryDisabled,
},
},
secondary: {
bg: colors.white,
color: colors.text.primary,
border: borders.input,
'&:hover,&:active': {
color: colors.white,
backgroundColor: colors.text.primary,
borderColor: colors.text.primary,
},
'&:disabled': {
backgroundColor: colors.lightestGrey,
borderColor: colors.lightestGrey,
color: colors.text.primaryDisabled,
},
},
});
|
export default ({ colors, borders }) => ({
primary: {
backgroundColor: colors.purpleMedium,
border: borders.input,
borderColor: colors.purpleMedium,
color: colors.white,
'&:hover,&:active,&:focus': {
backgroundColor: colors.text.primary,
borderColor: colors.text.primary,
},
'&:disabled': {
backgroundColor: colors.lightestGrey,
borderColor: colors.lightestGrey,
color: colors.text.primaryDisabled,
},
},
secondary: {
bg: colors.white,
color: colors.text.primary,
border: borders.input,
'&:hover,&:active,&:focus': {
color: colors.white,
backgroundColor: colors.text.primary,
borderColor: colors.text.primary,
},
'&:disabled': {
backgroundColor: colors.lightestGrey,
borderColor: colors.lightestGrey,
color: colors.text.primaryDisabled,
},
},
});
|
Move destroy checks just before set
|
import Ember from 'ember'
import layout from './template'
import PropTypeMixin, { PropTypes } from 'ember-prop-types'
const { K } = Ember
export default Ember.Component.extend(PropTypeMixin, {
layout,
propTypes: {
onOutsideClick: PropTypes.func
},
getDefaultProps() {
return { onOutsideClick: K }
},
init() {
this._super(...arguments)
this.handleDown = this.handleDown.bind(this)
this.handleUp = this.handleUp.bind(this)
},
didInsertElement() {
this._super(...arguments)
document.addEventListener('mousedown', this.handleDown, true)
document.addEventListener('mouseup', this.handleUp, true)
},
willDestroyElement() {
this._super(...arguments)
document.removeEventListener('mousedown', this.handleDown, true)
document.removeEventListener('mouseup', this.handleUp, true)
},
isOutside: false,
handleDown(e) {
const el = this.$()[0];
if (this.isDestroyed || this.isDestroying) return;
if (!el.contains(e.target)) this.set('isOutside', true)
},
handleUp(e) {
if (this.get('isOutside')) this.get('onOutsideClick')(e)
if (this.isDestroyed || this.isDestroying) return;
this.set('isOutside', false)
}
})
|
import Ember from 'ember'
import layout from './template'
import PropTypeMixin, { PropTypes } from 'ember-prop-types'
const { K } = Ember
export default Ember.Component.extend(PropTypeMixin, {
layout,
propTypes: {
onOutsideClick: PropTypes.func
},
getDefaultProps() {
return { onOutsideClick: K }
},
init() {
this._super(...arguments)
this.handleDown = this.handleDown.bind(this)
this.handleUp = this.handleUp.bind(this)
},
didInsertElement() {
this._super(...arguments)
document.addEventListener('mousedown', this.handleDown, true)
document.addEventListener('mouseup', this.handleUp, true)
},
willDestroyElement() {
this._super(...arguments)
document.removeEventListener('mousedown', this.handleDown, true)
document.removeEventListener('mouseup', this.handleUp, true)
},
isOutside: false,
handleDown(e) {
if (this.isDestroyed || this.isDestroying) {
return;
}
const el = this.$()[0];
if (!el.contains(e.target)) this.set('isOutside', true)
},
handleUp(e) {
if (this.isDestroyed || this.isDestroying) {
return;
}
if (this.get('isOutside')) this.get('onOutsideClick')(e)
this.set('isOutside', false)
}
})
|
MenuApi: Fix link-intern on invisible page
|
<?php
class Kwc_Basic_LinkTag_Intern_ApiContent implements Kwf_Component_ApiContent_Interface
{
public function getContent(Kwf_Component_Data $data)
{
$targetData = $data->getLinkedData();
$ret = array(
'rel' => $data->rel,
'class' => $data->getLinkClass(),
'dataAttributes' => $data->getLinkDataAttributes(),
);
return array_merge($ret, $this->getTargetLinkContent($targetData));
}
public function getTargetLinkContent($targetData)
{
if (!$targetData) return array();
$targetContentType = Kwc_Abstract::getSetting($targetData->componentClass, 'apiContentType');
if (is_instance_of (Kwc_Abstract::getSetting($targetData->componentClass, 'contentSender'), 'Kwf_Component_Abstract_ContentSender_Lightbox')) {
$targetContentType = 'lightbox';
}
return array(
"href" => $targetData->url,
"targetId" => $targetData->componentId,
"targetContentType" => $targetContentType
);
}
}
|
<?php
class Kwc_Basic_LinkTag_Intern_ApiContent implements Kwf_Component_ApiContent_Interface
{
public function getContent(Kwf_Component_Data $data)
{
$targetData = $data->getLinkedData();
$ret = array(
'rel' => $data->rel,
'class' => $data->getLinkClass(),
'dataAttributes' => $data->getLinkDataAttributes(),
);
return array_merge($ret, $this->getTargetLinkContent($targetData));
}
public function getTargetLinkContent($targetData)
{
$targetContentType = Kwc_Abstract::getSetting($targetData->componentClass, 'apiContentType');
if (is_instance_of (Kwc_Abstract::getSetting($targetData->componentClass, 'contentSender'), 'Kwf_Component_Abstract_ContentSender_Lightbox')) {
$targetContentType = 'lightbox';
}
return array(
"href" => $targetData->url,
"targetId" => $targetData->componentId,
"targetContentType" => $targetContentType
);
}
}
|
Add error of compilation to test pipelines
This will make sure that build are triggered on develop branch and that it can fail
|
package banane.io.pdb.validator;
import banane.io.pdb.model.Hero;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
@Component
public class HeroValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return Hero.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors) {
Hero hero = (Hero) target;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "NotEmpty");
if (hero.getUsername().length() < 6 || hero.getUsername().length() > 32) {
errors.rejectValue("username", "Size.userForm.username");
}
if(hero.getAgility() + hero.getIntelligence() + hero.getStrength() != 15) {
errors.rejectValue("agility", "Size.userForm.username");fmj
}
}
}
|
package banane.io.pdb.validator;
import banane.io.pdb.model.Hero;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
@Component
public class HeroValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return Hero.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors) {
Hero hero = (Hero) target;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "NotEmpty");
if (hero.getUsername().length() < 6 || hero.getUsername().length() > 32) {
errors.rejectValue("username", "Size.userForm.username");
}
if(hero.getAgility() + hero.getIntelligence() + hero.getStrength() != 15) {
errors.rejectValue("agility", "Size.userForm.username");
}
}
}
|
Change new line to prevent jshint warning
|
'use strict';
angular.module('tweets')
.config([
'$stateProvider',
function($stateProvider) {
$stateProvider
.state('me', {
url: '/me',
templateUrl: '/modules/tweets/views/me.client.view.jade'
})
.state('feed', {
url: '/',
templateUrl: '/modules/tweets/views/feed.client.view.jade'
});
}
])
.run([
'$rootScope',
'$state',
'Authentication',
function($rootScope, $state, Authentication) {
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
if ( (( toState.name !== 'signup') && ( toState.name !== 'signin')) &&
!Authentication.user) {
event.preventDefault();
$state.go('signup');
}
});
}
]);
|
'use strict';
angular.module('tweets')
.config([
'$stateProvider',
function($stateProvider) {
$stateProvider
.state('me', {
url: '/me',
templateUrl: '/modules/tweets/views/me.client.view.jade'
})
.state('feed', {
url: '/',
templateUrl: '/modules/tweets/views/feed.client.view.jade'
});
}
])
.run([
'$rootScope',
'$state',
'Authentication',
function($rootScope, $state, Authentication) {
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
if ( (( toState.name !== 'signup') && ( toState.name !== 'signin'))
&& !Authentication.user) {
event.preventDefault();
$state.go('signup');
}
});
}
]);
|
Update test to reflect the refactor
|
from mythril.laser.ethereum.transaction import execute_contract_creation
from mythril.ether import util
import mythril.laser.ethereum.svm as svm
from mythril.disassembler.disassembly import Disassembly
from datetime import datetime
from mythril.ether.soliditycontract import SolidityContract
import tests
from mythril.analysis.security import fire_lasers
from mythril.analysis.symbolic import SymExecWrapper
def test_create():
contract = SolidityContract(str(tests.TESTDATA_INPUTS_CONTRACTS / 'calls.sol'))
laser_evm = svm.LaserEVM({})
laser_evm.time = datetime.now()
execute_contract_creation(laser_evm, contract.creation_code)
resulting_final_state = laser_evm.open_states[0]
for address, created_account in resulting_final_state.accounts.items():
created_account_code = created_account.code
actual_code = Disassembly(contract.code)
for i in range(len(created_account_code.instruction_list)):
found_instruction = created_account_code.instruction_list[i]
actual_instruction = actual_code.instruction_list[i]
assert found_instruction['opcode'] == actual_instruction['opcode']
def test_sym_exec():
contract = SolidityContract(str(tests.TESTDATA_INPUTS_CONTRACTS / 'calls.sol'))
sym = SymExecWrapper(contract, address=(util.get_indexed_address(0)), strategy="dfs")
issues = fire_lasers(sym)
assert len(issues) != 0
|
import mythril.laser.ethereum.transaction as transaction
from mythril.ether import util
import mythril.laser.ethereum.svm as svm
from mythril.disassembler.disassembly import Disassembly
from datetime import datetime
from mythril.ether.soliditycontract import SolidityContract
import tests
from mythril.analysis.security import fire_lasers
from mythril.analysis.symbolic import SymExecWrapper
def test_create():
contract = SolidityContract(str(tests.TESTDATA_INPUTS_CONTRACTS / 'calls.sol'))
laser_evm = svm.LaserEVM({})
laser_evm.time = datetime.now()
laser_evm.execute_contract_creation(contract.creation_code)
resulting_final_state = laser_evm.open_states[0]
for address, created_account in resulting_final_state.accounts.items():
created_account_code = created_account.code
actual_code = Disassembly(contract.code)
for i in range(len(created_account_code.instruction_list)):
found_instruction = created_account_code.instruction_list[i]
actual_instruction = actual_code.instruction_list[i]
assert found_instruction['opcode'] == actual_instruction['opcode']
def test_sym_exec():
contract = SolidityContract(str(tests.TESTDATA_INPUTS_CONTRACTS / 'calls.sol'))
sym = SymExecWrapper(contract, address=(util.get_indexed_address(0)), strategy="dfs")
issues = fire_lasers(sym)
assert len(issues) != 0
|
Remove quotes from header line
|
#!/usr/bin/python
import requests
import json
import csv
import sys
def parse_dataset_metadata(dataset):
if 'rights' in dataset.keys():
rights = dataset['rights'].encode('utf-8').strip()
rights = rights.replace("\n", "")
else:
rights = 'not supplied'
return [dataset['key'].encode('utf-8'), rights]
def get_gbif_datasets(limit, offset):
params = {'limit': limit, 'offset': offset}
r = requests.get('http://api.gbif.org/v0.9/dataset/', params=params)
request_result = r.json()['results']
return request_result
results = []
more_results_to_find = True
offset = 0
limit = 20
print '#dataset-key,rights'
csvwriter = csv.writer(sys.stdout)
while more_results_to_find:
datasets = get_gbif_datasets(limit, offset)
for dataset in datasets:
csvwriter.writerow(parse_dataset_metadata(dataset))
offset += 20
if len(datasets) == 0:
more_results_to_find = False
|
#!/usr/bin/python
import requests
import json
import csv
import sys
def parse_dataset_metadata(dataset):
if 'rights' in dataset.keys():
rights = dataset['rights'].encode('utf-8').strip()
rights = rights.replace("\n", "")
else:
rights = 'not supplied'
return [dataset['key'].encode('utf-8'), rights]
def get_gbif_datasets(limit, offset):
params = {'limit': limit, 'offset': offset}
r = requests.get('http://api.gbif.org/v0.9/dataset/', params=params)
request_result = r.json()['results']
return request_result
results = []
more_results_to_find = True
offset = 0
limit = 20
print '"#dataset-key","rights"'
csvwriter = csv.writer(sys.stdout)
while more_results_to_find:
datasets = get_gbif_datasets(limit, offset)
for dataset in datasets:
csvwriter.writerow(parse_dataset_metadata(dataset))
offset += 20
if len(datasets) == 0:
more_results_to_find = False
|
Apply stacked graph improvements to LPA graph as example
|
define([
'require',
'extensions/views/timeseries-graph/timeseries-graph',
'extensions/views/graph/linelabel',
'./callout'
],
function (require, TimeseriesGraph, LineLabel, Callout) {
var LPATimeseriesGraph = TimeseriesGraph.extend({
components: function () {
return [
{ view: this.sharedComponents.xaxis },
{ view: this.sharedComponents.yaxis },
{
view: this.sharedComponents.stack,
options: {
selectGroup: false,
drawCursorLine: true
}
},
{
view: this.sharedComponents.linelabel,
options: {
showValues: true,
showValuesPercentage: true
}
},
{ view: Callout },
{ view: this.sharedComponents.hover }
];
},
getConfigNames: function () {
return ['stack', 'week'];
}
});
return LPATimeseriesGraph;
});
|
define([
'require',
'extensions/views/timeseries-graph/timeseries-graph',
'extensions/views/graph/linelabel',
'./callout'
],
function (require, TimeseriesGraph, LineLabel, Callout) {
var LPATimeseriesGraph = TimeseriesGraph.extend({
components: function () {
return [
{ view: this.sharedComponents.xaxis },
{ view: this.sharedComponents.yaxis },
{ view: this.sharedComponents.stack },
{ view: LineLabel },
{ view: Callout },
{ view: this.sharedComponents.hover }
];
},
getConfigNames: function () {
return ['stack', 'week'];
}
});
return LPATimeseriesGraph;
});
|
Use only one env var for the database url
|
package main
import (
"database/sql"
"fmt"
"log"
"net/http"
"os"
"github.com/sotoz/Ferrytale/controller"
"github.com/sotoz/Ferrytale/database"
)
// Config describes the configuration struct for the application.
type Config struct {
Host string
Port string
}
func main() {
db, err := sql.Open("mysql", fmt.Sprintf("%s", os.Getenv("DATABASE_URL")))
if err != nil {
log.Fatalf("Could not open database: %s", err)
}
database.DBCon = db
err = db.Ping()
if err != nil {
log.Fatalf("cannot connect to the database: %s", err)
}
defer db.Close()
c := Config{
Host: os.Getenv("APPLICATION_HOST"),
Port: os.Getenv("APPLICATION_PORT"),
}
log.Print("Ferrytale started...")
http.ListenAndServe(c.Host+":"+c.Port, controller.Router())
}
|
package main
import (
"database/sql"
"fmt"
"log"
"net/http"
"os"
"github.com/sotoz/Ferrytale/controller"
"github.com/sotoz/Ferrytale/database"
)
// Config describes the configuration struct for the application.
type Config struct {
Host string
Port string
}
func main() {
db, err := sql.Open(
"mysql",
fmt.Sprintf(
"%s:%s@tcp(%s)/%s?parseTime=true&time_zone=UTC",
os.Getenv("DATABASE_USER"),
os.Getenv("DATABASE_PASSWORD"),
os.Getenv("DATABASE_HOST")+":"+os.Getenv("DATABASE_PORT"),
"ferrytale",
),
)
if err != nil {
log.Fatalf("Could not open database: %s", err)
}
database.DBCon = db
err = db.Ping()
if err != nil {
log.Fatalf("cannot connect to the database: %s", err)
}
defer db.Close()
c := Config{
Host: os.Getenv("APPLICATION_HOST"),
Port: os.Getenv("APPLICATION_PORT"),
}
log.Print("Ferrytale started...")
http.ListenAndServe(c.Host+":"+c.Port, controller.Router())
}
|
Hide the "Read" role as being something users can select
|
/*************************************************
* Copyright (c) 2015 Ansible, Inc.
*
* All Rights Reserved
*************************************************/
/* jshint unused: vars */
export default
[
'CreateSelect2',
function(CreateSelect2) {
return {
restrict: 'E',
scope: false,
template: '<select ng-cloak class="AddPermissions-selectHide roleSelect2 form-control" ng-model="obj.roles" ng-options="role.label for role in roles | filter:{label: \'!Read\'} track by role.value" multiple required></select>',
link: function(scope, element, attrs, ctrl) {
CreateSelect2({
element: '.roleSelect2',
multiple: true,
placeholder: 'Select roles'
});
}
};
}
];
|
/*************************************************
* Copyright (c) 2015 Ansible, Inc.
*
* All Rights Reserved
*************************************************/
/* jshint unused: vars */
export default
[
'CreateSelect2',
function(CreateSelect2) {
return {
restrict: 'E',
scope: false,
template: '<select ng-cloak class="AddPermissions-selectHide roleSelect2 form-control" ng-model="obj.roles" ng-options="role.label for role in roles track by role.value" multiple required></select>',
link: function(scope, element, attrs, ctrl) {
CreateSelect2({
element: '.roleSelect2',
multiple: true,
placeholder: 'Select roles'
});
}
};
}
];
|
Drop log entry when closing the Kubernetes client
If we start logging something for every client we close, shutdown will
be far too verbose.
|
package io.quarkus.kubernetes.client.runtime;
import javax.annotation.PreDestroy;
import javax.enterprise.inject.Produces;
import javax.inject.Singleton;
import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.quarkus.arc.DefaultBean;
@Singleton
public class KubernetesClientProducer {
private KubernetesClient client;
@DefaultBean
@Singleton
@Produces
public Config config(KubernetesClientBuildConfig buildConfig) {
return KubernetesClientUtils.createConfig(buildConfig);
}
@DefaultBean
@Singleton
@Produces
public KubernetesClient kubernetesClient(Config config) {
client = new DefaultKubernetesClient(config);
return client;
}
@PreDestroy
public void destroy() {
if (client != null) {
client.close();
}
}
}
|
package io.quarkus.kubernetes.client.runtime;
import javax.annotation.PreDestroy;
import javax.enterprise.inject.Produces;
import javax.inject.Singleton;
import org.jboss.logging.Logger;
import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.quarkus.arc.DefaultBean;
@Singleton
public class KubernetesClientProducer {
private static final Logger LOGGER = Logger.getLogger(KubernetesClientProducer.class);
private KubernetesClient client;
@DefaultBean
@Singleton
@Produces
public Config config(KubernetesClientBuildConfig buildConfig) {
return KubernetesClientUtils.createConfig(buildConfig);
}
@DefaultBean
@Singleton
@Produces
public KubernetesClient kubernetesClient(Config config) {
client = new DefaultKubernetesClient(config);
return client;
}
@PreDestroy
public void destroy() {
if (client != null) {
LOGGER.info("Closing Kubernetes client");
client.close();
}
}
}
|
Change indentation; Shorter line length for better readability
|
<?php
/**
* @author Pierre-Henry Soria <hi@ph7.me>
* @copyright (c) 2018, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / App / System / Core / Class
*/
namespace PH7;
class UserMilestoneCore
{
const NUMBER_USERS = [
100,
500,
1000,
2500,
5000,
7500,
10000,
25000,
50000,
100000,
250000,
500000,
1000000 // Congrats!
];
/** @var UserCoreModel */
private $oUserModel;
public function __construct(UserCoreModel $oUserModel)
{
$this->oUserModel = $oUserModel;
}
/**
* @return bool
*/
public function isTotalUserReached()
{
return in_array(
$this->oUserModel->total(),
self::NUMBER_USERS,
true
);
}
}
|
<?php
/**
* @author Pierre-Henry Soria <hi@ph7.me>
* @copyright (c) 2018, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / App / System / Core / Class
*/
namespace PH7;
class UserMilestoneCore
{
const NUMBER_USERS = [
100,
500,
1000,
2500,
5000,
7500,
10000,
25000,
50000,
100000,
250000,
500000,
1000000 // Congrats!
];
/** @var UserCoreModel */
private $oUserModel;
public function __construct(UserCoreModel $oUserModel)
{
$this->oUserModel = $oUserModel;
}
/**
* @return bool
*/
public function isTotalUserReached()
{
return in_array($this->oUserModel->total(), self::NUMBER_USERS, true);
}
}
|
Fix getAuthorization tokens keys names
|
var _ = require("lodash");
var conf = require("./configuration.js");
var Logger = require("../logger.js");
module.exports = function() {
var s_oauthData = conf.loadOAuthConf();
var s_api = s_oauthData.map(function(tokens) {
var api = require("clever-client")(_.defaults(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
}));
// Waiting for clever-client to be fully node compliant
api.session.getAuthorization = function(httpMethod, url, params) {
return api.session.getHMACAuthorization(httpMethod, url, params, {
user_oauth_token: tokens.token,
user_oauth_token_secret: tokens.secret
});
};
return api;
});
return s_api;
};
|
var _ = require("lodash");
var conf = require("./configuration.js");
var Logger = require("../logger.js");
module.exports = function() {
var s_oauthData = conf.loadOAuthConf();
var s_api = s_oauthData.map(function(tokens) {
var userTokens = {
API_OAUTH_TOKEN: tokens.token,
API_OAUTH_TOKEN_SECRET: tokens.secret
};
var api = require("clever-client")(_.defaults(conf, {
API_HOST: conf.API_HOST,
API_CONSUMER_KEY: conf.OAUTH_CONSUMER_KEY,
API_CONSUMER_SECRET: conf.OAUTH_CONSUMER_SECRET,
logger: Logger
}, userTokens));
// Waiting for clever-client to be fully node compliant
api.session.getAuthorization = function(httpMethod, url, params) {
return api.session.getHMACAuthorization(httpMethod, url, params, userTokens);
};
return api;
});
return s_api;
};
|
Add pruning step to skeletonization
This requires an updated Fiji, as detailed in this mailing list thread:
https://list.nih.gov/cgi-bin/wa.exe?A1=ind1308&L=IMAGEJ#41
https://list.nih.gov/cgi-bin/wa.exe?A2=ind1308&L=IMAGEJ&F=&S=&P=36891
|
import sys
from ij import IJ
def ij_binary_skeletonize(impath_in, impath_out):
"""Load image `impath`, skeletonize it, and save it to the same file.
Parameters
----------
impath_in : string
Path to a 3D image file.
impath_out : string
Path to which to write the skeleton image file.
Returns
-------
None
"""
imp = IJ.openImage(impath_in)
IJ.run(imp, "Skeletonize (2D/3D)", "")
IJ.run(imp, "Analyze Skeleton (2D/3D)", "prune=none prune")
IJ.saveAs(imp, "Tiff", impath_out)
imp.close()
if __name__ == '__main__':
print sys.argv
ij_binary_skeletonize(sys.argv[1], sys.argv[2])
|
import sys
from ij import IJ
def ij_binary_skeletonize(impath_in, impath_out):
"""Load image `impath`, skeletonize it, and save it to the same file.
Parameters
----------
impath_in : string
Path to a 3D image file.
impath_out : string
Path to which to write the skeleton image file.
Returns
-------
None
"""
imp = IJ.openImage(impath_in)
IJ.run(imp, "Skeletonize (2D/3D)", "")
IJ.saveAs(imp, "Tiff", impath_out)
imp.close()
if __name__ == '__main__':
print sys.argv
ij_binary_skeletonize(sys.argv[1], sys.argv[2])
|
Add Python 2.6 to the classifiers list
|
#!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import base32_crockford
package_data = {
'': ['LICENSE', 'README.rst'],
}
setup(
name='base32-crockford',
version='0.2.0',
description=("A Python implementation of Douglas Crockford's "
"base32 encoding scheme"),
long_description=base32_crockford.__doc__,
license='BSD',
author='Jason Bittel',
author_email='jason.bittel@gmail.com',
url='https://github.com/jbittel/base32-crockford',
download_url='https://github.com/jbittel/base32-crockford/downloads',
py_modules=['base32_crockford'],
package_data=package_data,
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Utilities',
],
)
|
#!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import base32_crockford
package_data = {
'': ['LICENSE', 'README.rst'],
}
setup(
name='base32-crockford',
version='0.2.0',
description=("A Python implementation of Douglas Crockford's "
"base32 encoding scheme"),
long_description=base32_crockford.__doc__,
license='BSD',
author='Jason Bittel',
author_email='jason.bittel@gmail.com',
url='https://github.com/jbittel/base32-crockford',
download_url='https://github.com/jbittel/base32-crockford/downloads',
py_modules=['base32_crockford'],
package_data=package_data,
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Utilities',
],
)
|
Use update instead of setting key directly
|
from django.conf import settings
class Registry(object):
def __init__(self):
self._partitions = {}
def register(self, key, app_model, expression):
if not isinstance(app_model, basestring):
app_model = "%s.%s" % (
app_model._meta.app_label,
app_model._meta.object_name
)
if key in self._partitions and app_model in self._partitions[key]:
raise Exception("'%s' is already registered." % key)
if app_model.split(".")[0] not in settings.INSTALLED_APPS:
raise Exception("'%s' is not in INSTALLED_APPS" % app_model.split(".")[0])
self._partitions.update({
key: {
app_model: expression
}
})
def expression_for(self, key, app_model):
return self._partitions.get(key, {}).get(app_model)
registry = Registry()
def register(key, app_model, expression):
registry.register(key, app_model, expression)
|
from django.conf import settings
class Registry(object):
def __init__(self):
self._partitions = {}
def register(self, key, app_model, expression):
if not isinstance(app_model, basestring):
app_model = "%s.%s" % (
app_model._meta.app_label,
app_model._meta.object_name
)
if key in self._partitions and app_model in self._partitions[key]:
raise Exception("'%s' is already registered." % key)
if app_model.split(".")[0] not in settings.INSTALLED_APPS:
raise Exception("'%s' is not in INSTALLED_APPS" % app_model.split(".")[0])
self._partitions[key].update({app_model: expression})
def expression_for(self, key, app_model):
return self._partitions.get(key, {}).get(app_model)
registry = Registry()
def register(key, app_model, expression):
registry.register(key, app_model, expression)
|
Add missing typehint for PHPStan/PHP 7.2
|
<?php
declare(strict_types=1);
namespace League\Tactician\Handler;
use BadMethodCallException;
use League\Tactician\Exception;
use Throwable;
use function get_class;
use function gettype;
use function is_object;
/**
* Thrown when a specific handler object can not be used on a command object.
*
* The most common reason is the receiving method is missing or incorrectly
* named.
*/
final class CanNotInvokeHandler extends BadMethodCallException implements Exception
{
/** @var object */
private $command;
public static function forCommand(object $command, string $reason): self
{
$type = \get_class($command);
$exception = new self(
'Could not invoke handler for command ' . $type .
' for reason: ' . $reason
);
$exception->command = $command;
return $exception;
}
private function __construct(string $message = '', int $code = 0, Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
}
/**
* Returns the command that could not be invoked
*/
public function getCommand(): object
{
return $this->command;
}
}
|
<?php
declare(strict_types=1);
namespace League\Tactician\Handler;
use BadMethodCallException;
use League\Tactician\Exception;
use Throwable;
use function get_class;
use function gettype;
use function is_object;
/**
* Thrown when a specific handler object can not be used on a command object.
*
* The most common reason is the receiving method is missing or incorrectly
* named.
*/
final class CanNotInvokeHandler extends BadMethodCallException implements Exception
{
/** @var object */
private $command;
public static function forCommand(object $command, string $reason): self
{
$type = \get_class($command);
$exception = new self(
'Could not invoke handler for command ' . $type .
' for reason: ' . $reason
);
$exception->command = $command;
return $exception;
}
private function __construct(string $message = '', $code = 0, Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
}
/**
* Returns the command that could not be invoked
*/
public function getCommand(): object
{
return $this->command;
}
}
|
Add env defaults for redis config
|
exports = module.exports = {
production: {
provider : 'redis',
options : {
'redis' : {
port: process.env.WATCHMEN_REDIS_PORT_PRODUCTION || 1216,
host: '127.0.0.1',
db: process.env.WATCHMEN_REDIS_DB_PRODUCTION || 1
}
}
},
development: {
provider : 'redis',
options : {
'redis' : {
port: process.env.WATCHMEN_REDIS_PORT_DEVELOPMENT || 1216,
host: '127.0.0.1',
db: process.env.WATCHMEN_REDIS_DB_DEVELOPMENT || 2
}
}
},
test: {
provider : 'redis',
options : {
'redis' : {
port: process.env.WATCHMEN_REDIS_PORT_TEST || 6666,
host: '127.0.0.1',
db: process.env.WATCHMEN_REDIS_DB_TEST || 1
}
}
}
};
|
exports = module.exports = {
production: {
provider : 'redis',
options : {
'redis' : {
port: 1216,
host: '127.0.0.1',
db: 1
}
}
},
development: {
provider : 'redis',
options : {
'redis' : {
port: 1216,
host: '127.0.0.1',
db: 2
}
}
},
test: {
provider : 'redis',
options : {
'redis' : {
port: 6666,
host: '127.0.0.1',
db: 5
}
}
}
};
|
Fix invitations in Russian and Bulgarian, add locales to moment.js
Fixes #940
|
//= require jquery
//= require jquery_ujs
//= require twitter/bootstrap
//= require lodash
//= require handlebars.runtime
//= require diacritics
// To use placeholders in inputs in browsers that do not support it
// natively yet.
//= require jquery/jquery.placeholder
// Notifications (flash messages).
//= require jquery/jquery.noty
// To crop logos.
//= require jquery/jquery.Jcrop
// For modals.
//= require bootstrap/bootstrap-modal
//= require bootstrap/bootstrap-modalmanager
// Used in crop, modals and possibly other places. Grep for `ajaxForm`
// and `ajaxSubmit`.
//= require jquery/jquery.form
// Use to search for models (e.g. users) dynamically.
//= require select2
//= require i18n/translations
// Moment.js for dates
//= require moment
//= require moment/pt-br
//= require moment/de
//= require moment/es
//= require moment/bg
//= require moment/ru
// Datetime picker for bootstrap
//= require bootstrap-datetimepicker
//= require fineuploader
// 'base' HAS to be the first one included
//= require ./app/application/base
//= require_tree ./templates
//= require_tree ./app/application/
//= require_tree ./app/_all/
|
//= require jquery
//= require jquery_ujs
//= require twitter/bootstrap
//= require lodash
//= require handlebars.runtime
//= require diacritics
// To use placeholders in inputs in browsers that do not support it
// natively yet.
//= require jquery/jquery.placeholder
// Notifications (flash messages).
//= require jquery/jquery.noty
// To crop logos.
//= require jquery/jquery.Jcrop
// For modals.
//= require bootstrap/bootstrap-modal
//= require bootstrap/bootstrap-modalmanager
// Used in crop, modals and possibly other places. Grep for `ajaxForm`
// and `ajaxSubmit`.
//= require jquery/jquery.form
// Use to search for models (e.g. users) dynamically.
//= require select2
//= require i18n/translations
// Moment.js for dates
//= require moment
//= require moment/pt-br
//= require moment/de
//= require moment/es
// Datetime picker for bootstrap
//= require bootstrap-datetimepicker
//= require fineuploader
// 'base' HAS to be the first one included
//= require ./app/application/base
//= require_tree ./templates
//= require_tree ./app/application/
//= require_tree ./app/_all/
|
Add tests for the countryByName() method
|
<?php
use Galahad\LaravelAddressing\Entity\Country;
use Galahad\LaravelAddressing\LaravelAddressing;
/**
* Class LaravelAddressingTest
*
* @author Junior Grossi <juniorgro@gmail.com>
*/
class LaravelAddressingTest extends PHPUnit_Framework_TestCase
{
/**
* @var LaravelAddressing
*/
protected $addressing;
/**
* Setup the LaravelAddressing instance
*/
protected function setUp()
{
$this->addressing = new LaravelAddressing();
}
public function testTheReturningTypeOfCountryMethod()
{
$country = $this->addressing->country('US');
$this->assertTrue($country instanceof Country);
}
public function testIfTheCountryHasTheCorrectName()
{
$country = $this->addressing->country('US');
$this->assertEquals($country->getName(), 'United States');
$this->assertEquals($country->getCountryCode(), 'US');
}
public function testIfTheCountryByNameMethodIsReturningTheCorrectCountry()
{
$country = $this->addressing->countryByName('United States');
$this->assertTrue($country instanceof Country);
$this->assertEquals($country->getCountryCode(), 'US');
$country = $this->addressing->countryByName('Brazil');
$this->assertEquals($country->getCountryCode(), 'BR');
}
}
|
<?php
use Galahad\LaravelAddressing\Entity\Country;
use Galahad\LaravelAddressing\LaravelAddressing;
/**
* Class LaravelAddressingTest
*
* @author Junior Grossi <juniorgro@gmail.com>
*/
class LaravelAddressingTest extends PHPUnit_Framework_TestCase
{
/**
* @var LaravelAddressing
*/
protected $addressing;
/**
* Setup the LaravelAddressing instance
*/
protected function setUp()
{
$this->addressing = new LaravelAddressing();
}
/**
* Testing the returning type of the country() method
*/
public function testCountryMethodReturningType()
{
$country = $this->addressing->country('US');
$this->assertTrue($country instanceof Country);
}
/**
* Testing if the country has the correct name
*/
public function testCountryMethod()
{
$country = $this->addressing->country('US');
$this->assertEquals($country->getName(), 'United States');
$this->assertEquals($country->getCountryCode(), 'US');
}
}
|
Add docopt as a dependency.
|
import distutils.core
# Uploading to PyPI
# =================
# $ python setup.py register -r pypi
# $ python setup.py sdist upload -r pypi
version = '0.0'
distutils.core.setup(
name='kxg',
version=version,
author='Kale Kundert and Alex Mitchell',
url='https://github.com/kxgames/GameEngine',
download_url='https://github.com/kxgames/GameEngine/tarball/'+version,
license='LICENSE.txt',
description="A multiplayer game engine.",
long_description=open('README.rst').read(),
keywords=['game', 'network', 'gui', 'pyglet'],
packages=['kxg'],
install_requires=[
'pyglet',
'nonstdlib',
'linersock',
'pytest',
'docopt',
],
)
|
import distutils.core
# Uploading to PyPI
# =================
# $ python setup.py register -r pypi
# $ python setup.py sdist upload -r pypi
version = '0.0'
distutils.core.setup(
name='kxg',
version=version,
author='Kale Kundert and Alex Mitchell',
url='https://github.com/kxgames/GameEngine',
download_url='https://github.com/kxgames/GameEngine/tarball/'+version,
license='LICENSE.txt',
description="A multiplayer game engine.",
long_description=open('README.rst').read(),
keywords=['game', 'network', 'gui', 'pyglet'],
packages=['kxg'],
install_requires=[
'pyglet',
'nonstdlib',
'linersock',
'pytest',
],
)
|
Handle the guest-POST case better
|
<?php
namespace autoauth;
$config = require('config.php');
$class = new \ReflectionClass($config->hook->class);
if(!$class->isSubclassOf(hooks\IHook::class))
return http_response_code(500);
$hook = $class->newInstanceArgs($config->hook->args);
$layout = new layout\Page("pages/index.{$hook->userRole()}.xml");
if($_SERVER['REQUEST_METHOD'] === 'POST')
{
switch($hook->userRole())
{
case 'admin':
$name = $_POST['name'];
break;
case 'user':
$name = $hook->userName();
break;
}
}
if(isset($name))
{
$out = $layout->{'//html:input[@readonly]'}->item(0);
if(!strlen($name))
$out->setAttribute('value', 'Username cannot be empty!');
else
{
//TODO
$out->setAttribute('value', "UUID for '$name'");
}
}
$layout->display();
|
<?php
namespace autoauth;
$config = require('config.php');
$class = new \ReflectionClass($config->hook->class);
if(!$class->isSubclassOf(hooks\IHook::class))
return http_response_code(500);
$hook = $class->newInstanceArgs($config->hook->args);
$layout = new layout\Page("pages/index.{$hook->userRole()}.xml");
if($_SERVER['REQUEST_METHOD'] === 'POST')
{
switch($hook->userRole())
{
case 'admin':
$name = $_POST['name'];
break;
case 'user':
$name = $hook->userName();
break;
default:
return;
}
$out = $layout->{'//html:input[@readonly]'}->item(0);
if(!strlen($name))
$out->setAttribute('value', 'Username cannot be empty!');
else
{
//TODO
$out->setAttribute('value', "UUID for '$name'");
}
}
$layout->display();
|
Set image title in list container views
|
package com.wrapp.android.webimageexample;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
public class WebImageListAdapter extends BaseAdapter {
private static final boolean USE_AWESOME_IMAGES = true;
private static final int NUM_IMAGES = 100;
private static final int IMAGE_SIZE = 100;
public int getCount() {
return NUM_IMAGES;
}
private String getImageUrl(int i) {
if(USE_AWESOME_IMAGES) {
// Unicorns!
return "http://unicornify.appspot.com/avatar/" + i + "?s=" + IMAGE_SIZE;
}
else {
// Boring identicons
return "http://www.gravatar.com/avatar/" + i + "?s=" + IMAGE_SIZE + "&d=identicon";
}
}
public Object getItem(int i) {
return getImageUrl(i);
}
public long getItemId(int i) {
return i;
}
public View getView(int i, View convertView, ViewGroup parentViewGroup) {
WebImageContainerView containerView;
if(convertView != null) {
containerView = (WebImageContainerView)convertView;
}
else {
containerView = new WebImageContainerView(parentViewGroup.getContext());
}
containerView.setImageUrl(getImageUrl(i));
containerView.setImageText("Image #" + i);
return containerView;
}
}
|
package com.wrapp.android.webimageexample;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
public class WebImageListAdapter extends BaseAdapter {
private static final boolean USE_AWESOME_IMAGES = true;
private static final int NUM_IMAGES = 100;
private static final int IMAGE_SIZE = 100;
public int getCount() {
return NUM_IMAGES;
}
private String getImageUrl(int i) {
if(USE_AWESOME_IMAGES) {
// Unicorns!
return "http://unicornify.appspot.com/avatar/" + i + "?s=" + IMAGE_SIZE;
}
else {
// Boring identicons
return "http://www.gravatar.com/avatar/" + i + "?s=" + IMAGE_SIZE + "&d=identicon";
}
}
public Object getItem(int i) {
return getImageUrl(i);
}
public long getItemId(int i) {
return i;
}
public View getView(int i, View convertView, ViewGroup parentViewGroup) {
WebImageContainerView containerView;
if(convertView != null) {
containerView = (WebImageContainerView)convertView;
}
else {
containerView = new WebImageContainerView(parentViewGroup.getContext());
}
containerView.setImageUrl(getImageUrl(i));
return containerView;
}
}
|
Use os.path.join instead of string concatenation.
Use `join` in order to create path intelligently on all operating
systems. See: http://docs.python.org/2/library/os.path.html#os.path.join
|
# -*- coding: utf-8 -*-
from nose.tools import *
import time
from os.path import abspath, dirname, join
from shellstreaming.inputstream.textfile import TextFile
TEST_FILE = join(abspath(dirname(__file__)), 'test_textfile_input01.txt')
def test_textfile_usage():
n_batches = n_records = 0
stream = TextFile(TEST_FILE, batch_span_ms=20)
for batch in stream:
if batch is None:
time.sleep(0.1)
continue
assert_greater_equal(len(batch), 1)
n_batches += 1
for record in batch:
eq_(len(record), 1)
line = record[0]
eq_('line ', line[0:5])
ok_(0 <= int(line[5:]) < 100) # record order in a batch is not always 'oldest-first'
n_records += 1
print('number of batches (%d) >= 1 ?' % (n_batches))
assert_greater_equal(n_batches, 1)
eq_(n_records, 100)
|
# -*- coding: utf-8 -*-
from nose.tools import *
import os
import time
from shellstreaming.inputstream.textfile import TextFile
TEST_FILE = os.path.abspath(os.path.dirname(__file__)) + '/test_textfile_input01.txt'
def test_textfile_usage():
n_batches = n_records = 0
stream = TextFile(TEST_FILE, batch_span_ms=20)
for batch in stream:
if batch is None:
time.sleep(0.1)
continue
assert_greater_equal(len(batch), 1)
n_batches += 1
for record in batch:
eq_(len(record), 1)
line = record[0]
eq_('line ', line[0:5])
ok_(0 <= int(line[5:]) < 100) # record order in a batch is not always 'oldest-first'
n_records += 1
print('number of batches (%d) >= 1 ?' % (n_batches))
assert_greater_equal(n_batches, 1)
eq_(n_records, 100)
|
Add IRC on header as pageLink
|
<?php
if (!defined('BLARG')) die();
$headerlinks = array
(
pageLink('irc') => 'IRC',
);
$sidelinks = array
(
Settings::get('menuMainName') => array
(
actionLink('home') => 'Home page',
actionLink('board') => 'Forums',
actionLink('faq') => 'FAQ',
actionLink('memberlist') => 'Member list',
actionLink('ranks') => 'Ranks',
actionLink('online') => 'Online users',
actionLink('lastposts') => 'Last posts',
actionLink('search') => 'Search',
),
);
$dropdownlinks = array
(
Settings::get('menuMainName') => array
(
actionLink('board') => 'Index',
actionLink('faq') => 'FAQ',
actionLink('memberlist') => 'Member list',
actionLink('ranks') => 'Ranks',
actionLink('online') => 'Online users',
actionLink('lastposts') => 'Last posts',
actionLink('search') => 'Search',
),
);
$bucket = "headerlinks"; include(BOARD_ROOT."lib/pluginloader.php");
$bucket = "sidelinks"; include(BOARD_ROOT."lib/pluginloader.php");
$bucket = "dropdownlinks"; include(BOARD_ROOT."lib/pluginloader.php");
?>
|
<?php
if (!defined('BLARG')) die();
$headerlinks = array
(
actionLink('irc') => 'IRC',
);
$sidelinks = array
(
Settings::get('menuMainName') => array
(
actionLink('home') => 'Home page',
actionLink('board') => 'Forums',
actionLink('faq') => 'FAQ',
actionLink('memberlist') => 'Member list',
actionLink('ranks') => 'Ranks',
actionLink('online') => 'Online users',
actionLink('lastposts') => 'Last posts',
actionLink('search') => 'Search',
),
);
$dropdownlinks = array
(
Settings::get('menuMainName') => array
(
actionLink('board') => 'Index',
actionLink('faq') => 'FAQ',
actionLink('memberlist') => 'Member list',
actionLink('ranks') => 'Ranks',
actionLink('online') => 'Online users',
actionLink('lastposts') => 'Last posts',
actionLink('search') => 'Search',
),
);
$bucket = "headerlinks"; include(BOARD_ROOT."lib/pluginloader.php");
$bucket = "sidelinks"; include(BOARD_ROOT."lib/pluginloader.php");
$bucket = "dropdownlinks"; include(BOARD_ROOT."lib/pluginloader.php");
?>
|
Add another url pattern for debugging public layers
--HG--
branch : bookmarks
|
from django.conf.urls.defaults import *
import time
urlpatterns = patterns('lingcod.layers.views',
url(r'^public/$',
'get_public_layers',
name='public-data-layers'),
# Useful for debugging, avoids GE caching interference
url(r'^public/cachebuster/%s' % str(time.time()),
'get_public_layers',
name='public-data-layers-cachebuster'),
url(r'^kml_file/(?P<session_key>\w+)/(?P<uid>[\w_]+).kml',
'get_kml_file',
name='kml-file'),
url(r'^privatekml/(?P<session_key>\w+)/$',
'get_privatekml_list',
name='layers-privatekml-list'),
url(r'^privatekml/(?P<session_key>\w+)/(?P<pk>\d+)/$',
'get_privatekml',
name='layers-privatekml'),
url(r'^privatekml/(?P<session_key>\w+)/(?P<pk>\d+)/(?P<path>[^\z]+)$',
'get_relative_to_privatekml',
name='layers-privatekml-relative'),
)
|
from django.conf.urls.defaults import *
urlpatterns = patterns('lingcod.layers.views',
url(r'^public/',
'get_public_layers',
name='public-data-layers'),
url(r'^kml_file/(?P<session_key>\w+)/(?P<uid>[\w_]+).kml',
'get_kml_file',
name='kml-file'),
url(r'^privatekml/(?P<session_key>\w+)/$',
'get_privatekml_list',
name='layers-privatekml-list'),
url(r'^privatekml/(?P<session_key>\w+)/(?P<pk>\d+)/$',
'get_privatekml',
name='layers-privatekml'),
url(r'^privatekml/(?P<session_key>\w+)/(?P<pk>\d+)/(?P<path>[^\z]+)$',
'get_relative_to_privatekml',
name='layers-privatekml-relative'),
)
|
Fix typo in the shared ui webpack snippets preventing content pages from building
Signed-off-by: Victor Porof <7d8eebacd0931807085fa6b9af29638ed74e0886@mozilla.com>
|
// Any copyright is dedicated to the Public Domain.
// http://creativecommons.org/publicdomain/zero/1.0/
import path from 'path';
import CopyWebpackPlugin from 'copy-webpack-plugin';
export const uiFiles = (srcDir, dstDir) => ([
new CopyWebpackPlugin([{
from: path.join(srcDir, '*.html'),
to: dstDir,
flatten: true,
}]),
new CopyWebpackPlugin([{
from: path.join(srcDir, 'css', '*.css'),
to: path.join(dstDir, 'css'),
flatten: true,
}]),
new CopyWebpackPlugin([{
from: path.join(srcDir, '*.ico'),
to: path.join(dstDir),
flatten: true,
}]),
]);
export const sharedFiles = (sharedDir, dstDir) => ([
new CopyWebpackPlugin([{
from: path.join(sharedDir, 'css', '*.css'),
to: path.join(dstDir, 'css'),
flatten: true,
}]),
new CopyWebpackPlugin([{
from: path.join(sharedDir, 'assets'),
to: path.join(dstDir, 'assets'),
flatten: true,
}]),
new CopyWebpackPlugin([{
from: path.join(sharedDir, 'fonts'),
to: path.join(dstDir, 'fonts'),
flatten: true,
}]),
]);
|
// Any copyright is dedicated to the Public Domain.
// http://creativecommons.org/publicdomain/zero/1.0/
import path from 'path';
import CopyWebpackPlugin from 'copy-webpack-plugin';
export const uiFiles = (srcDir, dstDir) => ([
new CopyWebpackPlugin([{
from: path.join(srcDir, '*.html'),
to: dstDir,
flatten: true,
}]),
new CopyWebpackPlugin([{
from: path.join(srcDir, 'css', '*.css'),
to: path.join(dstDir, 'css'),
flatten: true,
}]),
new CopyWebpackPlugin([{
from: path.join(srcDir, 'favicon.ico'),
to: path.join(dstDir, 'favicon.ico'),
}]),
]);
export const sharedFiles = (sharedDir, dstDir) => ([
new CopyWebpackPlugin([{
from: path.join(sharedDir, 'css', '*.css'),
to: path.join(dstDir, 'css'),
flatten: true,
}]),
new CopyWebpackPlugin([{
from: path.join(sharedDir, 'assets'),
to: path.join(dstDir, 'assets'),
flatten: true,
}]),
new CopyWebpackPlugin([{
from: path.join(sharedDir, 'fonts'),
to: path.join(dstDir, 'fonts'),
flatten: true,
}]),
]);
|
Use urls without a slash in project/media project/support
BB-7765 #resolve
|
from bluebottle.projects.views import ProjectMediaDetail, ProjectSupportDetail
from ..views import (
ManageProjectBudgetLineDetail, ManageProjectBudgetLineList,
ManageProjectDocumentList, ManageProjectDocumentDetail)
from django.conf.urls import patterns, url
urlpatterns = patterns(
'',
url(r'^media/(?P<slug>[\w-]+)$',
ProjectMediaDetail.as_view(),
name='project-media-detail'),
url(r'^support/(?P<slug>[\w-]+)$',
ProjectSupportDetail.as_view(),
name='project-supporters-detail'),
url(r'^budgetlines/$',
ManageProjectBudgetLineList.as_view(),
name='project-budgetline-list'),
url(r'^budgetlines/(?P<pk>\d+)$',
ManageProjectBudgetLineDetail.as_view(),
name='project-budgetline-detail'),
url(r'^documents/manage/$',
ManageProjectDocumentList.as_view(),
name='manage-project-document-list'),
url(r'^documents/manage/(?P<pk>\d+)$',
ManageProjectDocumentDetail.as_view(),
name='manage-project-document-detail'),
)
|
from bluebottle.projects.views import ProjectMediaDetail, ProjectSupportDetail
from ..views import (
ManageProjectBudgetLineDetail, ManageProjectBudgetLineList,
ManageProjectDocumentList, ManageProjectDocumentDetail)
from django.conf.urls import patterns, url
urlpatterns = patterns(
'',
url(r'^media/(?P<slug>[\w-]+)/$',
ProjectMediaDetail.as_view(),
name='project-media-detail'),
url(r'^support/(?P<slug>[\w-]+)/$',
ProjectSupportDetail.as_view(),
name='project-supporters-detail'),
url(r'^budgetlines/$',
ManageProjectBudgetLineList.as_view(),
name='project-budgetline-list'),
url(r'^budgetlines/(?P<pk>\d+)$',
ManageProjectBudgetLineDetail.as_view(),
name='project-budgetline-detail'),
url(r'^documents/manage/$',
ManageProjectDocumentList.as_view(),
name='manage-project-document-list'),
url(r'^documents/manage/(?P<pk>\d+)$',
ManageProjectDocumentDetail.as_view(),
name='manage-project-document-detail'),
)
|
Use Callable to be able to retrieve the result of cancel
git-svn-id: 4e353c0944fe8da334633afc35765ef362dec675@5095 b4e469a2-07ce-4b26-9273-4d7d95a670c7
|
package org.helioviewer.jhv.threads;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class CancelTask extends FutureTask<Boolean> {
public CancelTask(FutureTask<?> cancelTask) {
super(new Callable<Boolean>() {
private FutureTask<?> _cancelTask;
public Callable init(FutureTask<?> _cancelTask) {
this._cancelTask = _cancelTask;
return this;
}
@Override
public Boolean call() {
return _cancelTask.cancel(true);
}
}.init(cancelTask));
}
}
|
package org.helioviewer.jhv.threads;
import java.util.concurrent.FutureTask;
public class CancelTask extends FutureTask<Void> {
public CancelTask(FutureTask<?> abolishTask) {
super(new Runnable() {
private FutureTask<?> abolishTask;
public Runnable init(FutureTask<?> abolishTask) {
this.abolishTask = abolishTask;
return this;
}
@Override
public void run() {
abolishTask.cancel(true);
}
}.init(abolishTask), null);
}
}
|
Add some more acts as list tests.
|
import unittest2
from querylist import QueryList
class QueryListActsAsList(unittest2.TestCase):
"""QueryLists should act just like lists"""
def setUp(self):
self.src_list = [{'foo': 1}, {'foo': 2}, {'foo': 3}]
self.query_list = QueryList(self.src_list)
def test_QueryList_items_are_equal_to_its_source_lists_items(self):
self.assertEqual(self.src_list, self.query_list)
def test_QueryList_length_is_equal_to_its_source_lists_length(self):
self.assertEqual(len(self.src_list), len(self.query_list))
def test_QueryLists_can_append_like_lists(self):
dbl_list = self.src_list + self.src_list
dbl_query_list = self.query_list + self.query_list
self.assertEqual(dbl_query_list, dbl_list)
def test_QueryList_slicing_works_like_list_slicing(self):
self.assertEqual(self.query_list[:2], self.src_list[:2])
def test_QueryList_indexing_works_like_list_indexing(self):
self.assertEqual(self.query_list[1], self.src_list[1])
|
import unittest2
from querylist import QueryList
class QueryListActsAsList(unittest2.TestCase):
"""QueryList should behave as lists behave"""
def setUp(self):
self.src_list = [{'foo': 1}, {'foo': 2}, {'foo': 3}]
self.query_list = QueryList(self.src_list)
def test_QueryList_items_are_equal_to_its_source_lists_items(self):
self.assertEqual(self.src_list, self.query_list)
def test_QueryList_length_is_equal_to_its_source_lists_length(self):
self.assertEqual(len(self.src_list), len(self.query_list))
def test_QueryLists_can_append_like_lists(self):
dbl_list = self.src_list + self.src_list
dbl_query_list = self.query_list + self.query_list
self.assertEqual(dbl_query_list, dbl_list)
|
Add typing as a dependency.
Change-Id: I5da9534f1e3d79fc38ce39771ac8d21459b16c59
|
# Copyright 2017 Verily Life Sciences Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Package configuration."""
from setuptools import find_packages
from setuptools import setup
REQUIRED_PACKAGES = ['pandas',
'google-cloud==0.27.0',
'pysqlite>=2.8.3',
'ddt',
'typing']
setup(
name='analysis-py-utils',
version='0.1',
license='Apache 2.0',
author='Verily Life Sciences',
url='https://github.com/verilylifesciences/analysis-py-utils',
install_requires=REQUIRED_PACKAGES,
packages=find_packages(),
include_package_data=True,
description='Python utilities for data analysis.',
requires=[])
|
# Copyright 2017 Verily Life Sciences Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Package configuration."""
from setuptools import find_packages
from setuptools import setup
REQUIRED_PACKAGES = ['pandas',
'google-cloud==0.27.0',
'pysqlite>=2.8.3',
'ddt']
setup(
name='analysis-py-utils',
version='0.1',
license='Apache 2.0',
author='Verily Life Sciences',
url='https://github.com/verilylifesciences/analysis-py-utils',
install_requires=REQUIRED_PACKAGES,
packages=find_packages(),
include_package_data=True,
description='Python utilities for data analysis.',
requires=[])
|
Change default log level to info and above
|
'use strict';
// Load requirements
const winston = require('winston'),
path = require('path'),
fs = require('fs');
// Add rotation to winston logs
require('winston-daily-rotate-file');
// Get log directory
let logDirectory = path.resolve(path.join(__base, '../logs'));
// Ensure the directory exists
fs.mkdir(logDirectory, (err) => { return; });
// Setup the logger interfaces for console, file and exception handling
const logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({
level: process.env.CONSOLE_LEVEL || 'info',
colorize: true
})/*,
new (winston.transports.DailyRotateFile)({
filename: path.join(logDirectory, process.env.ENV + '.'),
datePattern: 'yyyy-MM-dd.log',
level: process.env.LOG_LEVEL
})*/
]/*,
exceptionHandlers: [
new (winston.transports.DailyRotateFile)({
filename: path.join(logDirectory, 'exceptions.'),
datePattern: 'yyyy-MM-dd.log',
humanReadableUnhandledException: true
})
]*/
});
// Add colorize support
logger.filters.push((level, msg, meta) => {
return __require('libs/utils/methods/color-string')(msg);
});
// Export for use
module.exports = logger;
|
'use strict';
// Load requirements
const winston = require('winston'),
path = require('path'),
fs = require('fs');
// Add rotation to winston logs
require('winston-daily-rotate-file');
// Get log directory
let logDirectory = path.resolve(path.join(__base, '../logs'));
// Ensure the directory exists
fs.mkdir(logDirectory, (err) => { return; });
// Setup the logger interfaces for console, file and exception handling
const logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({
level: process.env.CONSOLE_LEVEL || 'debug',
colorize: true
})/*,
new (winston.transports.DailyRotateFile)({
filename: path.join(logDirectory, process.env.ENV + '.'),
datePattern: 'yyyy-MM-dd.log',
level: process.env.LOG_LEVEL
})*/
]/*,
exceptionHandlers: [
new (winston.transports.DailyRotateFile)({
filename: path.join(logDirectory, 'exceptions.'),
datePattern: 'yyyy-MM-dd.log',
humanReadableUnhandledException: true
})
]*/
});
// Add colorize support
logger.filters.push((level, msg, meta) => {
return __require('libs/utils/methods/color-string')(msg);
});
// Export for use
module.exports = logger;
|
Update the Roll notation functions implementation
Added `Roll.toSimpleNotation()` implementation.
Fixed range value in `Roll.toClassicNotation()`.
|
/*
{count}d{dice}{modifier} ({bottom},{top})
*/
function Roll( dice = 20, count = 1, modifier = 0, bottom = 0, top = Number.MAX_SAFE_INTEGER ) {
this.dice = dice;
this.count = count;
this.modifier = modifier;
this.top = Math.max( top, 1 );
this.bottom = Math.min( bottom, this.top );
}
Roll.prototype.toSimpleNotation = function toSimpleNotation() {
const count = this.count > 1 ? `${ this.count } ` : '';
const modifier = this.modifier || '';
const max = ( this.count * this.dice ) + this.modifier;
const top = this.top < max ? ` ${ this.top }` : '';
const bottom = this.bottom > 1 ? ` ${ this.bottom }` : '';
return `${ count }${ this.dice }${ modifier }${ bottom }${ top }`;
};
Roll.prototype.toClassicNotation = function toClassicNotation() {
const count = this.count > 1 ? this.count : '';
const modifier = this.modifier > 0 ? `+${ this.modifier }` : ( this.modifier || '' );
const max = ( this.count * this.dice ) + this.modifier;
const hasBottomRange = this.bottom > 1;
const hasTopRange = this.top < max;
const hasRange = hasBottomRange || hasTopRange;
let range = '';
if ( hasRange ) {
const bottom = hasBottomRange ? this.bottom : '';
const top = hasTopRange ? `,${ this.top }` : '';
range = `(${ bottom }${ top })`;
}
return `${ count }d${ this.dice }${ modifier }${ range }`;
};
module.exports = Roll;
|
/*
{count}d{dice}{modifier} ({bottom},{top})
*/
function Roll( dice = 20, count = 1, modifier = 0, bottom = 0, top = Number.MAX_SAFE_INTEGER ) {
this.dice = dice;
this.count = count;
this.modifier = modifier;
this.top = Math.max( top, 1 );
this.bottom = Math.min( bottom, this.top );
}
Roll.prototype.toSimpleNotation = function toSimpleNotation() {
return '';
};
Roll.prototype.toClassicNotation = function toClassicNotation() {
const count = this.count > 1 ? this.count : '';
const modifier = this.modifier > 0 ? `+${ this.modifier }` : ( this.modifier || '' );
const max = ( this.count * this.dice ) + this.modifier;
const top = this.top < max ? `,${ this.top }` : '';
const range = this.bottom > 1 ? ` (${ this.bottom }${ top })` : '';
return `${ count }d${ this.dice }${ modifier }${ range }`;
};
module.exports = Roll;
|
Disable auto-update until next year
|
'use strict';
var config = require('./server/config');
var helper = require('./server/helper');
var express = require('express');
var expressLayouts = require('express-ejs-layouts');
var compression = require('compression');
var app = express();
// Middlewares configuration
var oneWeek = 604800000;
app.use(compression());
app.use(express.static('client/statics'));
app.use(express.static('client/images', { maxAge: oneWeek }));
app.use(express.static('dist', { maxAge: oneWeek }));
// Handlebars configuration
app.set('views', 'client/views');
app.set('view engine', '.ejs');
app.set('layout', 'commons/_layout');
app.use(expressLayouts);
// Starts application listening
app.listen(config.port, () => {
helper.log('running on ' + config.port);
});
// Regsiters routes
app.use('/', require('./server/routes/manifestRoute'));
app.use('/', require('./server/routes/sitemapRoute'));
app.use('/', require('./server/routes/homeRoute'));
app.use('/', require('./server/routes/itemRoute'));
// Setup cron jobs
// Disable auto-update until next year
// require('./server/cronJobs').setupCrons();
|
'use strict';
var config = require('./server/config');
var helper = require('./server/helper');
var express = require('express');
var expressLayouts = require('express-ejs-layouts');
var compression = require('compression');
var app = express();
// Middlewares configuration
var oneWeek = 604800000;
app.use(compression());
app.use(express.static('client/statics'));
app.use(express.static('client/images', { maxAge: oneWeek }));
app.use(express.static('dist', { maxAge: oneWeek }));
// Handlebars configuration
app.set('views', 'client/views');
app.set('view engine', '.ejs');
app.set('layout', 'commons/_layout');
app.use(expressLayouts);
// Starts application listening
app.listen(config.port, () => {
helper.log('running on ' + config.port);
});
// Regsiters routes
app.use('/', require('./server/routes/manifestRoute'));
app.use('/', require('./server/routes/sitemapRoute'));
app.use('/', require('./server/routes/homeRoute'));
app.use('/', require('./server/routes/itemRoute'));
// Setup cron jobs
require('./server/cronJobs').setupCrons();
|
Add 'inline-block' to status-bar item for proper margin-left
|
'use babel'
export default class StatusBarItem {
constructor () {
this.element = document.createElement('a')
this.element.className = 'line-ending-tile inline-block'
this.setLineEndings(new Set())
}
setLineEndings (lineEndings) {
this.lineEndings = lineEndings
this.element.textContent = lineEndingName(lineEndings)
}
hasLineEnding (lineEnding) {
return this.lineEndings.has(lineEnding)
}
onClick (callback) {
this.element.addEventListener('click', callback)
}
}
function lineEndingName (lineEndings) {
if (lineEndings.size > 1) {
return 'Mixed'
} else if (lineEndings.has('\n')) {
return 'LF'
} else if (lineEndings.has('\r\n')) {
return 'CRLF'
} else {
return ''
}
}
|
'use babel'
export default class StatusBarItem {
constructor () {
this.element = document.createElement('a')
this.element.className = 'line-ending-tile'
this.setLineEndings(new Set())
}
setLineEndings (lineEndings) {
this.lineEndings = lineEndings
this.element.textContent = lineEndingName(lineEndings)
}
hasLineEnding (lineEnding) {
return this.lineEndings.has(lineEnding)
}
onClick (callback) {
this.element.addEventListener('click', callback)
}
}
function lineEndingName (lineEndings) {
if (lineEndings.size > 1) {
return 'Mixed'
} else if (lineEndings.has('\n')) {
return 'LF'
} else if (lineEndings.has('\r\n')) {
return 'CRLF'
} else {
return ''
}
}
|
Disable file inputs on browsers that don't support FileReader / FormData.
|
"use strict";
angular.module("hikeio").
directive("fileUploader", ["$window", function($window) {
return {
compile: function(tplElm, tplAttr) {
var mulitpleStr = tplAttr.multiple === "true" ? "multiple" : "";
tplElm.after("<input type='file' " + mulitpleStr + " accept='image/png, image/jpeg' style='display: none;'>");
return function(scope, elm, attr) {
if (scope.$eval(attr.enabled)) {
var input = angular.element(elm[0].nextSibling);
input.bind("change", function() {
if (input[0].files.length > 0) {
scope.$eval(attr.fileUploader, {files: input[0].files});
input[0].value = ""; // Allow the user to select the same file again
}
});
elm.bind("click", function() {
if (input[0].disabled || !$window.FileReader || !window.FormData) {
$window.alert("Sorry, you cannot upload photos from this browser.");
return;
}
input[0].click();
});
elm.css("cursor", "pointer");
}
};
},
replace: true,
template: "<div data-ng-transclude></div>",
transclude: true
};
}]);
|
"use strict";
angular.module("hikeio").
directive("fileUploader", ["$window", function($window) {
return {
compile: function(tplElm, tplAttr) {
var mulitpleStr = tplAttr.multiple === "true" ? "multiple" : "";
tplElm.after("<input type='file' " + mulitpleStr + " accept='image/png, image/jpeg' style='display: none;'>");
return function(scope, elm, attr) {
if (scope.$eval(attr.enabled)) {
var input = angular.element(elm[0].nextSibling);
input.bind("change", function() {
if (input[0].files.length > 0) {
scope.$eval(attr.fileUploader, {files: input[0].files});
input[0].value = ""; // Allow the user to select the same file again
}
});
elm.bind("click", function() {
if (input[0].disabled) {
$window.alert("Sorry this browser doesn't support file upload.");
}
input[0].click();
});
elm.css("cursor", "pointer");
}
};
},
replace: true,
template: "<div data-ng-transclude></div>",
transclude: true
};
}]);
|
Test refactoring (Main reason: Trigger a travis build)
|
package com.xaadin;
import com.vaadin.ui.*;
import org.junit.Test;
import java.net.URL;
import static org.fest.assertions.api.Assertions.assertThat;
public class ParserTest {
public static final String PARSER_TEST_ALL_COMPONENTS = "ParserTestAllComponents.xml";
private Class[] TEST_COMPONENTS_TO_PARSE = new Class[]{
Label.class,
TextField.class,
Button.class,
ComboBox.class,
Table.class,
ProgressBar.class,
TextArea.class,
Panel.class,
TabSheet.class,
VerticalLayout.class,
HorizontalLayout.class,
GridLayout.class
};
@Test
public void shouldParseAllComponentsInGivenXml() throws Exception {
URL url = ClassLoader.getSystemResource(PARSER_TEST_ALL_COMPONENTS);
VisualTreeNode visualTreeNode = Parser.parse(url, null);
for (Class clazz : TEST_COMPONENTS_TO_PARSE) {
String className = clazz.getSimpleName().substring(0, 1).toLowerCase() + clazz.getSimpleName().substring(1);
Component component = visualTreeNode.findComponentById(className);
assertThat(component).isOfAnyClassIn(clazz);
}
}
}
|
package com.xaadin;
import com.vaadin.ui.*;
import org.junit.Test;
import java.net.URL;
import static org.fest.assertions.api.Assertions.assertThat;
public class ParserTest {
public static final String PARSER_TEST_ALL_COMPONENTS = "ParserTestAllComponents.xml";
@Test
public void testParseAllComponents() throws Exception {
Class[] componentsToCheck = {
Label.class,
TextField.class,
Button.class,
ComboBox.class,
Table.class,
ProgressBar.class,
TextArea.class,
Panel.class,
TabSheet.class,
VerticalLayout.class,
HorizontalLayout.class,
GridLayout.class
};
URL url = ClassLoader.getSystemResource(PARSER_TEST_ALL_COMPONENTS);
VisualTreeNode visualTreeNode = Parser.parse(url, null);
for (Class clazz : componentsToCheck) {
String className = clazz.getSimpleName().substring(0, 1).toLowerCase() + clazz.getSimpleName().substring(1);
Component component = visualTreeNode.findComponentById(className);
assertThat(component).isNotNull();
assertThat(component).isOfAnyClassIn(clazz);
}
}
}
|
Add version information under trombi module
|
# Copyright (c) 2010 Inoi Oy
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
version = (0, 9, 0)
from .client import *
|
# Copyright (c) 2010 Inoi Oy
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from .client import *
|
Fix bug de premier fichier
Lors du premier upload, le fichier n'apparaissait pas, c'est corrigé.
|
<?php
define('ID_FILE','id.txt');
define('UPLOAD_PATH','uploads/');
$behaviour['FILES_TO_ECHO']=array('txt','js','html','php','htm','shtml','shtm');
$behaviour['FILES_TO_RETURN']=array('jpg','jpeg','gif','png','pdf','swf');
if (!is_dir(UPLOAD_PATH)){mkdir(UPLOAD_PATH);}
if (!is_file(UPLOAD_PATH.'index.html')){file_put_contents(UPLOAD_PATH.'index.html',' ');}
if (!is_dir('thumbs/')){mkdir('thumbs/');}
if (!is_file('thumbs/index.html')){file_put_contents('thumbs/index.html',' ');}
if (!file_exists(ID_FILE)){$ids=array();store(ID_FILE,$ids);}
$ids=unstore(ID_FILE);
function is_in($ext,$type){global $behaviour;if (!empty($behaviour[$type])){return array_search($ext,$behaviour[$type]);}}
function store($file,$datas){file_put_contents($file,gzdeflate(json_encode($datas)));}
function unstore($file){return json_decode(gzinflate(file_get_contents($file)),true);}
function id2file($id){
global $ids;
if (isset($ids[$id])){return $ids[$id];}else{return false;}
}
?>
|
<?php
define('ID_FILE','id.txt');
define('UPLOAD_PATH','uploads/');
$behaviour['FILES_TO_ECHO']=array('txt','js','html','php','htm','shtml','shtm');
$behaviour['FILES_TO_RETURN']=array('jpg','jpeg','gif','png','pdf','swf');
if (!is_dir(UPLOAD_PATH)){mkdir(UPLOAD_PATH);}
if (!is_dir('thumbs/')){mkdir('thumbs/');}
if (!file_exists(ID_FILE)){$ids=array();store(ID_FILE,$ids);}
$ids=unstore(ID_FILE);
function is_in($ext,$type){global $behaviour;if (!empty($behaviour[$type])){return array_search($ext,$behaviour[$type]);}}
function store($file,$datas){file_put_contents($file,gzdeflate(json_encode($datas)));}
function unstore($file){return json_decode(gzinflate(file_get_contents($file)),true);}
function id2file($id){
global $ids;
if (isset($ids[$id])){return $ids[$id];}else{return false;}
}
?>
|
Remove use of numpCpus lookup
|
module.exports = createServerCluster
var http = require('http')
, clusterMaster = require('clustered')
, extend = require('lodash.assign')
function createServerCluster(server, logger, options) {
if (!server) {
throw new Error('Must pass in an instance of a server')
}
if (!logger) {
throw new Error('Must pass in an instance of a logger')
}
var defaults =
{ port: 5678
, numProcesses: 1
}
options = extend({}, defaults, options)
clusterMaster(function () {
var httpServer = http.createServer(function (req, res) {
return server(req, res)
}).listen(options.port, function () {
server.emit('started', httpServer)
})
}
, { logger: logger
, size: options.numProcesses
}
)
}
|
module.exports = createServerCluster
var http = require('http')
, clusterMaster = require('clustered')
, cpus = require('os').cpus()
, extend = require('lodash.assign')
function createServerCluster(server, logger, options) {
if (!server) {
throw new Error('Must pass in an instance of a server')
}
if (!logger) {
throw new Error('Must pass in an instance of a logger')
}
var defaults =
{ port: 5678
, numProcesses: Math.ceil(cpus.length * 0.7)
}
options = extend({}, defaults, options)
clusterMaster(function () {
var httpServer = http.createServer(function (req, res) {
return server(req, res)
}).listen(options.port, function () {
server.emit('started', httpServer)
})
}
, { logger: logger
, size: options.numProcesses
}
)
}
|
Include the source path in the list
|
/**
* @license
* grunt-template-progeny
* Copyright 2014 Luis Aleman <https://github.com/Lalem001/>
*/
(function (module) {
module.exports = function (grunt, config) {
var progeny = require('progeny').Sync(config);
/**
* Grunt Template Helper: Progeny
* Get the dependencies of the specified path in a glob ready list of paths
*
* @function "grunt.template.progeny"
* @param {string} path Source path or grunt template
* @returns {string} glob ready list of paths
* @example
* ```js
* {
* src: '<%= grunt.template.progeny("path/to/source.less") %>'
* }
* ```
* @example
* ```js
* {
* // using source path from another task
* src: '<%= grunt.template.progeny(less.main.src) %>'
* }
* ```
*/
grunt.template.progeny = function (path) {
path = grunt.template.process(path);
return '{' + [path].concat(progeny(path)) + ',}';
};
return grunt.template.progeny;
};
})(module);
|
/**
* @license
* grunt-template-progeny
* Copyright 2014 Luis Aleman <https://github.com/Lalem001/>
*/
(function (module) {
module.exports = function (grunt, config) {
var progeny = require('progeny').Sync(config);
/**
* Grunt Template Helper: Progeny
* Get the dependencies of the specified path in a glob ready list of paths
*
* @function "grunt.template.progeny"
* @param {string} path Source path or grunt template
* @returns {string} glob ready list of paths
* @example
* ```js
* {
* src: '<%= grunt.template.progeny("path/to/source.less") %>'
* }
* ```
* @example
* ```js
* {
* // using source path from another task
* src: '<%= grunt.template.progeny(less.main.src) %>'
* }
* ```
*/
grunt.template.progeny = function (path) {
path = grunt.template.process(path);
return '{' + progeny(path) + ',}';
};
return grunt.template.progeny;
};
})(module);
|
Adjust the order to reduce latency
|
import logmodule
from eve.client.script.ui.shared.fleet.fleetbroadcast import FleetBroadcastView
def PatchFn(fn):
def wrapper(self):
ret = fn(self)
try:
br = sm.GetService('fleet').GetBroadcastHistory()[0]
logmodule.general.Log("GetBroadcastListEntry invoked: %s %d %d" % (br.name, br.charID, br.itemID), logmodule.LGNOTICE)
if br.name in ("Target", "HealArmor", "HealShield"):
sm.GetService('target').TryLockTarget(br.itemID)
except:
pass
return ret
return wrapper
def RunPatch():
FleetBroadcastView.LoadBroadcastHistory = PatchFn(FleetBroadcastView.LoadBroadcastHistory)
logmodule.general.Log("Code Injected", logmodule.LGNOTICE)
|
import logmodule
from eve.client.script.ui.shared.fleet.fleetbroadcast import FleetBroadcastView
def PatchFn(fn):
def wrapper(self):
try:
br = sm.GetService('fleet').GetBroadcastHistory()[0]
logmodule.general.Log("GetBroadcastListEntry invoked: %s %d %d" % (br.name, br.charID, br.itemID), logmodule.LGNOTICE)
if br.name in ("Target", "HealArmor", "HealShield"):
sm.GetService('target').TryLockTarget(br.itemID)
except:
pass
return fn(self)
return wrapper
def RunPatch():
FleetBroadcastView.LoadBroadcastHistory = PatchFn(FleetBroadcastView.LoadBroadcastHistory)
logmodule.general.Log("Code Injected", logmodule.LGNOTICE)
|
Convert callbacks to arrow functions
|
'use strict';
/* eslint-env node */
let TEST_SELECTOR_PREFIX = /data-test-.*/;
function isTestSelector(attribute) {
return TEST_SELECTOR_PREFIX.test(attribute);
}
function stripTestSelectors(node) {
node.params = node.params.filter(param => !isTestSelector(param.original));
node.hash.pairs = node.hash.pairs.filter(pair => !isTestSelector(pair.key));
}
function transform() {
return {
name: 'strip-test-selectors',
visitor: {
ElementNode(node) {
node.attributes = node.attributes.filter(attribute => !isTestSelector(attribute.name));
},
MustacheStatement(node) {
stripTestSelectors(node);
},
BlockStatement(node) {
stripTestSelectors(node);
},
}
};
}
module.exports = transform;
|
'use strict';
/* eslint-env node */
let TEST_SELECTOR_PREFIX = /data-test-.*/;
function isTestSelector(attribute) {
return TEST_SELECTOR_PREFIX.test(attribute);
}
function stripTestSelectors(node) {
node.params = node.params.filter(function(param) {
return !isTestSelector(param.original);
});
node.hash.pairs = node.hash.pairs.filter(function(pair) {
return !isTestSelector(pair.key);
});
}
function transform() {
return {
name: 'strip-test-selectors',
visitor: {
ElementNode(node) {
node.attributes = node.attributes.filter(function(attribute) {
return !isTestSelector(attribute.name);
});
},
MustacheStatement(node) {
stripTestSelectors(node);
},
BlockStatement(node) {
stripTestSelectors(node);
},
}
};
}
module.exports = transform;
|
Add reminder to myself to to importlib fallback.
|
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
# TODO: When Python 2.7 is released this becomes a try/except falling
# back to Django's implementation.
from django.utils.importlib import import_module
def get_backend():
"""
Return an instance of the registration backend for use on this
site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise
``django.core.exceptions.ImproperlyConfigured`` if the specified
backend cannot be located.
"""
i = settings.REGISTRATION_BACKEND.rfind('.')
module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:]
try:
mod = import_module(module)
except ImportError, e:
raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e))
try:
backend_class = getattr(mod, attr)
except AttributeError:
raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr))
return backend_class()
|
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module
def get_backend():
"""
Return an instance of the registration backend for use on this
site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise
``django.core.exceptions.ImproperlyConfigured`` if the specified
backend cannot be located.
"""
i = settings.REGISTRATION_BACKEND.rfind('.')
module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:]
try:
mod = import_module(module)
except ImportError, e:
raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e))
try:
backend_class = getattr(mod, attr)
except AttributeError:
raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr))
return backend_class()
|
Remove SpringServices Config and add missing beans to showcase config
Cleaned up configuration file of wte4j-shwocase
|
/**
* Copyright (C) 2015 Born Informatik AG (www.born.ch)
*
* 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.wte4j.examples.showcase.server.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportResource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.wte4j.examples.showcase.server.services.OrderServiceImpl;
import org.wte4j.examples.showcase.shared.service.OrderService;
@Configuration
@EnableTransactionManagement
@ImportResource({ "classpath:wte4j-core-application-context.xml" })
@Import({ DatabaseConfig.class, Wte4jConfiguration.class })
public class RootApplicationConfig {
@Bean
public OrderService orderService() {
return new OrderServiceImpl();
}
}
|
/**
* Copyright (C) 2015 Born Informatik AG (www.born.ch)
*
* 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.wte4j.examples.showcase.server.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportResource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.wte4j.examples.showcase.server.services.SpringServices;
@Configuration
@EnableTransactionManagement
@ImportResource({ "classpath:wte4j-core-application-context.xml" })
@Import({ DatabaseConfig.class, Wte4jConfiguration.class })
@ComponentScan(basePackageClasses = { SpringServices.class })
public class RootApplicationConfig {
}
|
Clear up Status naming confusion
|
class _base_model_class(dict):
def __init__(self, json={}):
self.update(json)
self.update(self.__dict__)
self.__dict__ = self
def __repr__(self):
return '%s(%s)' % (self.__class__.__name__, self.json())
def json(self):
return dict.__repr__(self)
def _model_class(class_name):
return type(class_name, (_base_model_class,), {})
APIStatus = _model_class('APIStatus')
Team = _model_class('Team')
Event = _model_class('Event')
Match = _model_class('Match')
Award = _model_class('Award')
District = _model_class('District')
Media = _model_class('Media')
Robot = _model_class('Robot')
Profile = _model_class('Profile')
Alliance = _model_class('Alliance')
DistrictPoints = _model_class('DistrictPoints')
Insights = _model_class('Insights')
OPRs = _model_class('OPRs')
Prediction = _model_class('Prediction')
Rankings = _model_class('Rankings')
DistrictRanking = _model_class('DistrictRanking')
Status = _model_class('Status')
|
class _base_model_class(dict):
def __init__(self, json={}):
self.update(json)
self.update(self.__dict__)
self.__dict__ = self
def __repr__(self):
return '%s(%s)' % (self.__class__.__name__, self.json())
def json(self):
return dict.__repr__(self)
def _model_class(class_name):
return type(class_name, (_base_model_class,), {})
APIStatus = _model_class('Status')
Team = _model_class('Team')
Event = _model_class('Event')
Match = _model_class('Match')
Award = _model_class('Award')
District = _model_class('District')
Media = _model_class('Media')
Robot = _model_class('Robot')
Profile = _model_class('Profile')
Alliance = _model_class('Alliance')
DistrictPoints = _model_class('DistrictPoints')
Insights = _model_class('Insights')
OPRs = _model_class('OPRs')
Prediction = _model_class('Prediction')
Rankings = _model_class('Rankings')
DistrictRanking = _model_class('DistrictRanking')
Status = _model_class('TeamStatus')
|
Store registered route handlers in a slice.
They were directly registered using `http.HandleFunc` before.
|
package routes
import (
"encoding/json"
"net/http"
)
var registeredHandlers = make([]RegisteredHandler, 0x40)
type RegisteredHandler struct {
Pattern string
Handler http.HandlerFunc
}
type Arguments map[interface{}]interface{}
type Handler func(*http.Request, Arguments) (int, interface{})
type IntermediateHandler func(http.ResponseWriter, *http.Request, Arguments) (int, interface{})
type Decorator interface {
Decorate(IntermediateHandler) IntermediateHandler
}
type ErrorBody struct {
Error string `json:"error"`
}
func Register(pattern string, handler Handler, decorators ...Decorator) {
stage := baseIntermediate(handler)
l := len(decorators) - 1
for i := range decorators {
d := decorators[l-i]
stage = d.Decorate(stage)
}
registeredHandlers = append(registeredHandlers, RegisteredHandler{
pattern,
func(w http.ResponseWriter, r *http.Request) {
arguments := make(Arguments)
status, output := stage(w, r, arguments)
w.WriteHeader(status)
json.NewEncoder(w).Encode(output)
},
})
}
func baseIntermediate(handler Handler) IntermediateHandler {
return func(w http.ResponseWriter, r *http.Request, a Arguments) (int, interface{}) {
return handler(r, a)
}
}
|
package routes
import (
"encoding/json"
"net/http"
)
type Arguments map[interface{}]interface{}
type Handler func(*http.Request, Arguments) (int, interface{})
type IntermediateHandler func(http.ResponseWriter, *http.Request, Arguments) (int, interface{})
type Decorator interface {
Decorate(IntermediateHandler) IntermediateHandler
}
type ErrorBody struct {
Error string `json:"error"`
}
func Register(pattern string, handler Handler, decorators ...Decorator) error {
stage := baseIntermediate(handler)
l := len(decorators) - 1
for i := range decorators {
d := decorators[l-i]
stage = d.Decorate(stage)
}
http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
arguments := make(Arguments)
status, output := stage(w, r, arguments)
w.WriteHeader(status)
json.NewEncoder(w).Encode(output)
})
return nil
}
func baseIntermediate(handler Handler) IntermediateHandler {
return func(w http.ResponseWriter, r *http.Request, a Arguments) (int, interface{}) {
return handler(r, a)
}
}
|
Make it so you have to explicitly initialize the mixin
Also lets you add the mixin to other classes
|
//
// Add boundary-handling to a Leaflet map
//
// The boundary layer allows exactly one boundary at a time and fires events
// (boundarieschange) when this layer changes.
//
var mixin = {
boundariesLayer: null,
_initBoundaries: function () {
this.boundariesLayer = L.geoJson(null, {
color: '#FFA813',
fill: false,
opacity: 1
}).addTo(this);
},
removeBoundaries: function (data, options) {
this.boundariesLayer.clearLayers();
this.fire('boundarieschange');
},
updateBoundaries: function (data, options) {
this.boundariesLayer.clearLayers();
this.boundariesLayer.addData(data);
this.fire('boundarieschange');
if (options.zoomToBounds) {
this.fitBounds(this.boundariesLayer.getBounds());
}
}
};
module.exports = {
initialize: function (mapClass) {
mapClass = mapClass || L.Map;
mapClass.include(mixin);
mapClass.addInitHook('_initBoundaries');
},
mixin: mixin
};
|
//
// Add boundary-handling to a Leaflet map
//
// The boundary layer allows exactly one boundary at a time and fires events
// (boundarieschange) when this layer changes.
//
L.Map.include({
boundariesLayer: null,
_initBoundaries: function () {
this.boundariesLayer = L.geoJson(null, {
color: '#FFA813',
fill: false,
opacity: 1
}).addTo(this);
},
removeBoundaries: function (data, options) {
this.boundariesLayer.clearLayers();
this.fire('boundarieschange');
},
updateBoundaries: function (data, options) {
this.boundariesLayer.clearLayers();
this.boundariesLayer.addData(data);
this.fire('boundarieschange');
if (options.zoomToBounds) {
this.fitBounds(this.boundariesLayer.getBounds());
}
}
});
L.Map.addInitHook('_initBoundaries');
|
Add a memory used metric
|
#!/usr/bin/python2
# vim:set ts=4 sw=4 et nowrap syntax=python ff=unix:
##############################################################################
import sys, time
def memory ():
f = open('/proc/meminfo', 'r')
lines = f.readlines()
f.close()
mem = []
for x in range(4):
mem.append(int(lines[x].split()[1], 10) * 1024)
print 'mem.total %d' % (mem[0])
print 'mem.free %d' % (mem[1])
print 'mem.buffers %d' % (mem[2])
print 'mem.cached %d' % (mem[3])
print 'mem.used %d' %(mem[0] - sum(mem[1:]))
sys.stdout.flush()
def run (poll_interval):
while True:
start = time.time()
memory()
done = time.time()
delay = poll_interval - (done - start)
if delay > 0.0: time.sleep(delay)
if __name__ == '__main__':
run(10.0)
##############################################################################
## THE END
|
#!/usr/bin/python2
# vim:set ts=4 sw=4 et nowrap syntax=python ff=unix:
##############################################################################
import sys, time
def memory ():
f = open('/proc/meminfo', 'r')
lines = f.readlines()
f.close()
mem = []
for x in range(4):
mem.append(int(lines[x].split()[1], 10) * 1024)
print 'mem.total %d' % (mem[0])
print 'mem.free %d' % (mem[1])
print 'mem.buffers %d' % (mem[2])
print 'mem.cached %d' % (mem[3])
sys.stdout.flush()
def run (poll_interval):
while True:
start = time.time()
memory()
done = time.time()
delay = poll_interval - (done - start)
if delay > 0.0: time.sleep(delay)
if __name__ == '__main__':
run(10.0)
##############################################################################
## THE END
|
Add missing index of Numpad number
|
const kspecial = {
32 : 'Spacebar',
96 : 'Numpad 0',
97 : 'Numpad 1',
98 : 'Numpad 2',
99 : 'Numpad 3',
100 : 'Numpad 4',
101 : 'Numpad 5',
102 : 'Numpad 6',
103 : 'Numpad 7',
104 : 'Numpad 8',
105 : 'Numpad 9'
}
const kcode = document.getElementById('key-code');
const kchar = document.getElementById('key-char');
window.addEventListener('keydown', function (event) {
if (event.defaultPrevented) {
return; // Should do nothing if the default action has been cancelled
}
var handled = false;
if (event.keyCode !== undefined) {
// Handle the event with KeyboardEvent.keyCode and set handled true.
kcode.innerHTML = event.keyCode;
handled = true;
}
if (event.key !== undefined) {
// Handle the event with KeyboardEvent.key and set handled true.
kchar.innerHTML = kspecial[event.keyCode] !== undefined ?
kspecial[event.keyCode] : event.key;
kchar.style.visibility = 'visible';
handled = true;
}
if (handled) {
// Suppress "double action" if event handled
event.preventDefault();
}
}, true);
|
const kspecial = {
32 : 'Spacebar',
97 : 'Numpad 1',
98 : 'Numpad 2',
99 : 'Numpad 3',
100 : 'Numpad 4',
101 : 'Numpad 5',
102 : 'Numpad 6',
103 : 'Numpad 7',
104 : 'Numpad 8',
105 : 'Numpad 9'
}
const kcode = document.getElementById('key-code');
const kchar = document.getElementById('key-char');
window.addEventListener('keydown', function (event) {
if (event.defaultPrevented) {
return; // Should do nothing if the default action has been cancelled
}
var handled = false;
if (event.keyCode !== undefined) {
// Handle the event with KeyboardEvent.keyCode and set handled true.
kcode.innerHTML = event.keyCode;
handled = true;
}
if (event.key !== undefined) {
// Handle the event with KeyboardEvent.key and set handled true.
kchar.innerHTML = kspecial[event.keyCode] !== undefined ?
kspecial[event.keyCode] : event.key;
kchar.style.visibility = 'visible';
handled = true;
}
if (handled) {
// Suppress "double action" if event handled
event.preventDefault();
}
}, true);
|
Change post json handling on success
|
var router = require( 'express' ).Router()
var Post = require( '../../models/post' )
var websockets = require( '../../websockets' )
router.get( '/', function( req, res, next ) {
Post.find()
.sort( '-date' )
.exec( function( err, posts ) {
if ( err ) { return next( err ) }
res.json( posts )
})
})
router.post( '/', function( req, res, next ) {
var post = new Post({
body: req.body.body
})
post.username = req.auth.username
post.save( function ( err, post ) {
if ( err ) { return next( err ) }
websockets.broadcast( 'new_post', post )
res.status( 201).json( post )
})
})
module.exports = router
|
var router = require( 'express' ).Router()
var Post = require( '../../models/post' )
var websockets = require( '../../websockets' )
router.get( '/', function( req, res, next ) {
Post.find()
.sort( '-date' )
.exec( function( err, posts ) {
if ( err ) { return next( err ) }
res.json( posts )
})
})
router.post( '/', function( req, res, next ) {
var post = new Post({
body: req.body.body
})
post.username = req.auth.username
post.save( function ( err, post ) {
if ( err ) { return next( err ) }
websockets.broadcast( 'new_post', post )
res.json( 201, post )
})
})
module.exports = router
|
Fix plugin dir setting for updated Smarty.
|
<?php
error_reporting(E_ALL|E_STRICT);
require_once(__DIR__ . '/../lib/smarty/Smarty.class.php');
//
// Global application state
//
global $APP;
$APP = new StdClass();
$APP->root = __DIR__ . '/..';
set_include_path(get_include_path() . PATH_SEPARATOR .
$APP->root . "/lib/controllers" . PATH_SEPARATOR .
$APP->root . "/lib");
//
// Load web controller path mappings.
//
require_once(__DIR__ . '/paths.php');
//
// Set up the database
//
require_once(__DIR__ . '/database.php');
//
// Fire up the Smarty template engine.
//
// load and configure Smarty
$APP->smarty = new Smarty();
$APP->smarty->error_reporting = 0;
$APP->smarty->template_dir = $APP->root . "/views/templates/";
$APP->smarty->compile_dir = $APP->root . "/views/templates_c/";
$APP->smarty->config_dir = $APP->root . "/views/config/";
$APP->smarty->cache_dir = $APP->root . "/views/cache/";
$APP->smarty->addPluginsDir($APP->root . "/views/plugins");
// autoload classes from <classname>.php
spl_autoload_register(function ($class_name) {
require_once $class_name . '.php';
});
// end
|
<?php
error_reporting(E_ALL|E_STRICT);
require_once(__DIR__ . '/../lib/smarty/Smarty.class.php');
//
// Global application state
//
global $APP;
$APP = new StdClass();
$APP->root = __DIR__ . '/..';
set_include_path(get_include_path() . PATH_SEPARATOR .
$APP->root . "/lib/controllers" . PATH_SEPARATOR .
$APP->root . "/lib");
//
// Load web controller path mappings.
//
require_once(__DIR__ . '/paths.php');
//
// Set up the database
//
require_once(__DIR__ . '/database.php');
//
// Fire up the Smarty template engine.
//
// load and configure Smarty
$APP->smarty = new Smarty();
$APP->smarty->error_reporting = 0;
$APP->smarty->template_dir = $APP->root . "/views/templates/";
$APP->smarty->compile_dir = $APP->root . "/views/templates_c/";
$APP->smarty->config_dir = $APP->root . "/views/config/";
$APP->smarty->cache_dir = $APP->root . "/views/cache/";
array_push($APP->smarty->plugins_dir, $APP->root . "/views/plugins");
// autoload classes from <classname>.php
spl_autoload_register(function ($class_name) {
require_once $class_name . '.php';
});
// end
|
Use dark theme if possible.
|
import os
import signal
import sys
from argparse import ArgumentParser
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('GtkSource', '3.0')
from gi.repository import Gio, GLib, Gtk
from rsr import __version__
from rsr.app import Application
parser = ArgumentParser(prog='runsqlrun', description='Run SQL statements')
parser.add_argument(
'--version', action='version', version='%(prog)s ' + __version__)
# See issue3. Unfortunately this needs to be done before opening
# any Oracle connection.
os.environ.setdefault('NLS_LANG', '.AL32UTF8')
def main():
parser.parse_args()
signal.signal(signal.SIGINT, signal.SIG_DFL)
GLib.set_application_name('RunSQLRun')
GLib.set_prgname('runsqlrun')
resource = Gio.resource_load('data/runsqlrun.gresource')
Gio.Resource._register(resource)
Gtk.Settings.get_default().set_property(
'gtk-application-prefer-dark-theme', True)
app = Application()
sys.exit(app.run(sys.argv))
|
import os
import signal
import sys
from argparse import ArgumentParser
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('GtkSource', '3.0')
from gi.repository import Gio, GLib
from rsr import __version__
from rsr.app import Application
parser = ArgumentParser(prog='runsqlrun', description='Run SQL statements')
parser.add_argument(
'--version', action='version', version='%(prog)s ' + __version__)
# See issue3. Unfortunately this needs to be done before opening
# any Oracle connection.
os.environ.setdefault('NLS_LANG', '.AL32UTF8')
def main():
parser.parse_args()
signal.signal(signal.SIGINT, signal.SIG_DFL)
GLib.set_application_name('RunSQLRun')
GLib.set_prgname('runsqlrun')
resource = Gio.resource_load('data/runsqlrun.gresource')
Gio.Resource._register(resource)
app = Application()
sys.exit(app.run(sys.argv))
|
Add import-time check for pygame (since we can't install automatically)
|
try:
import pygame
except ImportError:
print 'Failed to import pygame'
print '-----------------------'
print ''
print 'tingbot-python requires pygame. Please download and install pygame 1.9.1'
print 'or later from http://www.pygame.org/download.shtml'
print ''
print "If you're using a virtualenv, you should make the virtualenv with the "
print "--system-site-packages flag so the system-wide installation is still "
print "accessible."
print ''
print '-----------------------'
print ''
raise
from . import platform_specific, input
from .graphics import screen, Surface, Image
from .run_loop import main_run_loop, every
from .input import touch
from .button import press
from .web import webhook
platform_specific.fixup_env()
def run(loop=None):
if loop is not None:
every(seconds=1.0/30)(loop)
main_run_loop.add_after_action_callback(screen.update_if_needed)
main_run_loop.add_wait_callback(input.poll)
# in case screen updates happen in input.poll...
main_run_loop.add_wait_callback(screen.update_if_needed)
main_run_loop.run()
__all__ = ['run', 'screen', 'Surface', 'Image', 'every', 'touch', 'press', 'button', 'webhook']
__author__ = 'Joe Rickerby'
__email__ = 'joerick@mac.com'
__version__ = '0.3'
|
from . import platform_specific, input
from .graphics import screen, Surface, Image
from .run_loop import main_run_loop, every
from .input import touch
from .button import press
from .web import webhook
platform_specific.fixup_env()
def run(loop=None):
if loop is not None:
every(seconds=1.0/30)(loop)
main_run_loop.add_after_action_callback(screen.update_if_needed)
main_run_loop.add_wait_callback(input.poll)
# in case screen updates happen in input.poll...
main_run_loop.add_wait_callback(screen.update_if_needed)
main_run_loop.run()
__all__ = ['run', 'screen', 'Surface', 'Image', 'every', 'touch', 'press', 'button', 'webhook']
__author__ = 'Joe Rickerby'
__email__ = 'joerick@mac.com'
__version__ = '0.3'
|
Store by fully qualified domain name.
|
// module for interacting with tabs
var data = require('sdk/self').data;
var storage = require("storage");
var tabs = require("sdk/tabs");
var item_position = '';
// getting domain name from url
function retrieve_domain(str) {
var re = /[^\/]+\/\/(([^\/]+\.?)+)/;
return str.match(re)[0];
}
function current_tab_domain() {
return retrieve_domain(tabs.activeTab.url);
}
function bind_current () {
var worker = tabs.activeTab.attach({
contentScriptFile: [data.url('jquery-2.1.0.min.js'),
data.url('bind.js')],
onMessage: function (message) {
console.log('Getting message: ' + message);
storage.insert(current_tab_domain(), message);
}
});
worker.port.emit('get_path');
}
function focus_search_bar () {
var worker = tabs.activeTab.attach({
contentScriptFile: [data.url('jquery-2.1.0.min.js'),
data.url('set-focus.js')]
});
var saved = storage.retrieve(current_tab_domain());
if (saved !== undefined) {
worker.port.emit('set_focus', saved[1]);
}
}
exports.bind_current = bind_current;
exports.focus_search_bar = focus_search_bar;
|
// module for interacting with tabs
var data = require('sdk/self').data;
var storage = require("storage");
var tabs = require("sdk/tabs");
var item_position = '';
function bind_current () {
var worker = tabs.activeTab.attach({
contentScriptFile: [data.url('jquery-2.1.0.min.js'),
data.url('bind.js')],
onMessage: function (message) {
console.log('Getting message: ' + message);
storage.insert(tabs.activeTab.url, message);
}
});
worker.port.emit('get_path');
}
function focus_search_bar () {
var worker = tabs.activeTab.attach({
contentScriptFile: [data.url('jquery-2.1.0.min.js'),
data.url('set-focus.js')]
});
var saved = storage.retrieve(tabs.activeTab.url);
if (saved !== undefined) {
worker.port.emit('set_focus', saved[1]);
}
}
exports.bind_current = bind_current;
exports.focus_search_bar = focus_search_bar;
|
Revert change, @evan’s fix is better
|
const bunyan = require('bunyan')
const {getLogStreams} = require('./log-streams')
const NODE_ENV = process.env.NODE_ENV || 'unknown'
function createLogger(name, env = NODE_ENV) {
const childLogs = new Map()
const logger = bunyan.createLogger({
name,
env,
serializers: bunyan.stdSerializers,
streams: getLogStreams(name, env),
})
return Object.assign(logger, {
forAccount(account = {}) {
if (!childLogs.has(account.id)) {
const childLog = logger.child({
account_id: account.id,
account_email: account.emailAddress,
})
childLogs.set(account.id, childLog)
}
return childLogs.get(account.id)
},
})
}
module.exports = {
createLogger,
}
|
const bunyan = require('bunyan')
const {getLogStreams} = require('./log-streams')
const NODE_ENV = process.env.NODE_ENV || 'unknown'
function createLogger(name, env = NODE_ENV) {
if (process.env.USE_CONSOLE_LOG) {
console.forAccount = () => {
return console;
}
console.child = () => {
return console;
}
return console;
}
const childLogs = new Map()
const logger = bunyan.createLogger({
name,
env,
serializers: bunyan.stdSerializers,
streams: getLogStreams(name, env),
})
return Object.assign(logger, {
forAccount(account = {}) {
if (!childLogs.has(account.id)) {
const childLog = logger.child({
account_id: account.id,
account_email: account.emailAddress,
})
childLogs.set(account.id, childLog)
}
return childLogs.get(account.id)
},
})
}
module.exports = {
createLogger,
}
|
Add test case for forum crawler
The forum include: 'inside', 'techorange', 'media'
|
from arrange_schedule import *
def test_read_system_setting():
keys = ['board_py_dir','shutdown','max_db_log','min_db_activity']
system_setting = read_system_setting()
for key in keys:
assert key in system_setting
return system_setting
def test_read_arrange_mode():
keys = ['arrange_sn','arrange_mode','condition']
receive_msg = read_arrange_mode()
for key in keys:
assert key in receive_msg
def test_crawler_cwb_img(system_setting):
send_msg = {}
send_msg['server_dir'] = system_setting['board_py_dir']
send_msg['user_id'] = 1
receive_msg = crawler_cwb_img(send_msg)
assert receive_msg['result'] == 'success'
def test_crawler_inside_img():
receive_msg = crawler_inside_news()
assert receive_msg['result'] == 'success'
def test_crawler_techorange_news():
receive_msg = crawler_techorange_news()
assert receive_msg['result'] == 'success'
def test_crawler_medium_news():
receive_msg = crawler_medium_news()
assert receive_msg['result'] == 'success'
if __name__ == "__main__":
system_setting = test_read_system_setting()
test_read_arrange_mode()
test_crawler_cwb_img(system_setting)
test_crawler_inside_img()
test_crawler_techorange_news()
test_crawler_medium_news()
print("All test passed")
|
from arrange_schedule import *
def test_read_system_setting():
keys = ['board_py_dir','shutdown','max_db_log','min_db_activity']
system_setting = read_system_setting()
for key in keys:
assert key in system_setting
return system_setting
def test_read_arrange_mode():
keys = ['arrange_sn','arrange_mode','condition']
receive_msg = read_arrange_mode()
for key in keys:
assert key in receive_msg
def test_crawler_cwb_img(system_setting):
send_msg = {}
send_msg['server_dir'] = system_setting['board_py_dir']
send_msg['user_id'] = 1
receive_msg = crawler_cwb_img(send_msg)
assert receive_msg['result'] == 'success'
if __name__ == "__main__":
system_setting = test_read_system_setting()
test_read_arrange_mode()
test_crawler_cwb_img(system_setting)
print("All test passed")
|
Fix wrong redirect on logout
|
from django.contrib import messages
from django.contrib.auth import REDIRECT_FIELD_NAME, logout
from django.core.urlresolvers import reverse_lazy
from django.views.generic import RedirectView, TemplateView
from django.utils.http import is_safe_url
from django.utils.translation import ugettext
class IndexView(TemplateView):
"""View for the index page"""
template_name = 'sleepy/web/index.html'
class LogoutView(RedirectView):
url = reverse_lazy('sleepy-home')
permanent = False
def dispatch(self, request, *args, **kwargs):
if request.user.is_authenticated():
logout(self.request)
messages.success(request, ugettext('You have successfully logged out.'))
return super(LogoutView, self).get(request, *args, **kwargs)
def get_redirect_url(self, *args, **kwargs):
url = super(LogoutView, self).get_redirect_url(*args, **kwargs)
next_url = self.request.REQUEST.get(REDIRECT_FIELD_NAME, None)
if next_url and is_safe_url(url=next_url, host=self.request.get_host()):
url = next_url
return url
|
from django.contrib import messages
from django.contrib.auth import REDIRECT_FIELD_NAME, logout
from django.core.urlresolvers import reverse_lazy
from django.views.generic import RedirectView, TemplateView
from django.utils.http import is_safe_url
from django.utils.translation import ugettext
class IndexView(TemplateView):
"""View for the index page"""
template_name = 'sleepy/web/index.html'
class LogoutView(RedirectView):
url = reverse_lazy('home')
permanent = False
def dispatch(self, request, *args, **kwargs):
if request.user.is_authenticated():
logout(self.request)
messages.success(request, ugettext('You have successfully logged out.'))
return super(LogoutView, self).get(request, *args, **kwargs)
def get_redirect_url(self, *args, **kwargs):
url = super(LogoutView, self).get_redirect_url(*args, **kwargs)
next_url = self.request.REQUEST.get(REDIRECT_FIELD_NAME, None)
if next_url and is_safe_url(url=next_url, host=self.request.get_host()):
url = next_url
return url
|
Use Count() in Blood Knight
|
from ..utils import *
# Big Game Hunter
class EX1_005:
action = [Destroy(TARGET)]
# Mountain Giant
class EX1_105:
def cost(self, value):
return value - (len(self.controller.hand) - 1)
# Sea Giant
class EX1_586:
def cost(self, value):
return value - len(self.game.board)
# Blood Knight
class EX1_590:
action = [
Buff(SELF, "EX1_590e") * Count(ALL_MINIONS + DIVINE_SHIELD),
SetTag(ALL_MINIONS, {GameTag.DIVINE_SHIELD: False})
]
# Molten Giant
class EX1_620:
def cost(self, value):
return value - self.controller.hero.damage
# Captain's Parrot
class NEW1_016:
action = [ForceDraw(CONTROLLER, CONTROLLER_DECK + PIRATE)]
# Hungry Crab
class NEW1_017:
action = [Destroy(TARGET), Buff(SELF, "NEW1_017e")]
# Doomsayer
class NEW1_021:
events = [
OWN_TURN_BEGIN.on(Destroy(ALL_MINIONS))
]
|
from ..utils import *
# Big Game Hunter
class EX1_005:
action = [Destroy(TARGET)]
# Mountain Giant
class EX1_105:
def cost(self, value):
return value - (len(self.controller.hand) - 1)
# Sea Giant
class EX1_586:
def cost(self, value):
return value - len(self.game.board)
# Blood Knight
class EX1_590:
def action(self):
count = len(self.game.board.filter(divine_shield=True))
return [
SetTag(ALL_MINIONS, {GameTag.DIVINE_SHIELD: False}),
Buff(self, "EX1_590e") * count,
]
# Molten Giant
class EX1_620:
def cost(self, value):
return value - self.controller.hero.damage
# Captain's Parrot
class NEW1_016:
action = [ForceDraw(CONTROLLER, CONTROLLER_DECK + PIRATE)]
# Hungry Crab
class NEW1_017:
action = [Destroy(TARGET), Buff(SELF, "NEW1_017e")]
# Doomsayer
class NEW1_021:
events = [
OWN_TURN_BEGIN.on(Destroy(ALL_MINIONS))
]
|
Remove statusCode variable from service.js test assertions
|
'use strict';
const express = require('express');
const expect = require('expect');
const request = require('supertest');
const config = require('../src/config');
const services = require('../src/services');
describe('services.js', () => {
const app = express();
let userServices;
before(async () => {
userServices = await services(config.token);
});
app.get('/', (req, res) => {
res.status(200).json(userServices);
});
it('should response with a status 200 for valid request', done => {
request(app)
.get('/')
.expect(200)
.end(done);
});
it('should return an array', done => {
request(app)
.get('/')
.expect(res => {
expect(Array.isArray(res.body)).toBe(true);
})
.end(done);
});
it('should return a list of all services', done => {
request(app)
.get('/')
.expect(res => {
expect(res.body.length).toBeGreaterThanOrEqualTo(1);
})
.end(done);
});
it('should include version and id properties for each service', done => {
request(app)
.get('/')
.expect(res => {
expect(res.body[0]).toIncludeKeys([ 'version', 'id' ]);
})
.end(done);
});
});
|
'use strict';
const express = require('express');
const expect = require('expect');
const request = require('supertest');
const config = require('../src/config');
const services = require('../src/services');
describe('services.js', () => {
const app = express();
let userServices;
let statusCode;
before(async () => {
userServices = await services(config.token);
statusCode = 200;
});
app.get('/', (req, res) => {
res.status(statusCode).json(userServices);
});
it('should response with a status 200 for valid request', done => {
request(app)
.get('/')
.expect(200)
.end(done);
});
it('should return an array', done => {
request(app)
.get('/')
.expect(res => {
expect(Array.isArray(res.body)).toBe(true);
})
.end(done);
});
it('should return a list of all services', done => {
request(app)
.get('/')
.expect(res => {
expect(res.body.length).toBeGreaterThanOrEqualTo(1);
})
.end(done);
});
it('should include version and id properties for each service', done => {
request(app)
.get('/')
.expect(res => {
expect(res.body[0]).toIncludeKeys([ 'version', 'id' ]);
})
.end(done);
});
});
|
Add functools32 to the requirements for Python < 3.2
|
import sys
from setuptools import setup, find_packages
import populous
requirements = [
"click",
"cached-property",
"fake-factory",
]
if sys.version_info < (3, 2):
requirements.append('functools32')
setup(
name="populous",
version=populous.__version__,
url=populous.__url__,
description=populous.__doc__,
author=populous.__author__,
license=populous.__license__,
long_description="TODO",
packages=find_packages(),
install_requires=requirements,
entry_points={
'console_scripts': [
'populous = populous.__main__:cli'
]
},
classifiers=[
"Development Status :: 3 - Alpha",
"License :: OSI Approved :: MIT License",
"Operating System :: POSIX",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Topic :: Utilities",
],
keywords='populous populate database',
)
|
from setuptools import setup, find_packages
import populous
requirements = [
"click",
"cached-property",
"fake-factory",
]
setup(
name="populous",
version=populous.__version__,
url=populous.__url__,
description=populous.__doc__,
author=populous.__author__,
license=populous.__license__,
long_description="TODO",
packages=find_packages(),
install_requires=requirements,
entry_points={
'console_scripts': [
'populous = populous.__main__:cli'
]
},
classifiers=[
"Development Status :: 3 - Alpha",
"License :: OSI Approved :: MIT License",
"Operating System :: POSIX",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Topic :: Utilities",
],
keywords='populous populate database',
)
|
Refactor ember-utils imports in ember-template-compiler package.
|
import { assign } from 'ember-utils';
import PLUGINS from '../plugins';
let USER_PLUGINS = [];
export default function compileOptions(_options) {
let options = assign({ meta: { } }, _options);
// move `moduleName` into `meta` property
if (options.moduleName) {
let meta = options.meta;
meta.moduleName = options.moduleName;
}
if (!options.plugins) {
options.plugins = { ast: [...USER_PLUGINS, ...PLUGINS] };
} else {
let potententialPugins = [...USER_PLUGINS, ...PLUGINS];
let pluginsToAdd = potententialPugins.filter((plugin) => {
return options.plugins.ast.indexOf(plugin) === -1;
});
options.plugins.ast = options.plugins.ast.slice().concat(pluginsToAdd);
}
return options;
}
export function registerPlugin(type, PluginClass) {
if (type !== 'ast') {
throw new Error(`Attempting to register ${PluginClass} as "${type}" which is not a valid Glimmer plugin type.`);
}
if (USER_PLUGINS.indexOf(PluginClass) === -1) {
USER_PLUGINS = [PluginClass, ...USER_PLUGINS];
}
}
export function removePlugin(type, PluginClass) {
if (type !== 'ast') {
throw new Error(`Attempting to unregister ${PluginClass} as "${type}" which is not a valid Glimmer plugin type.`);
}
USER_PLUGINS = USER_PLUGINS.filter((plugin) => plugin !== PluginClass);
}
|
import PLUGINS from '../plugins';
import { assign } from 'ember-metal';
let USER_PLUGINS = [];
export default function compileOptions(_options) {
let options = assign({ meta: { } }, _options);
// move `moduleName` into `meta` property
if (options.moduleName) {
let meta = options.meta;
meta.moduleName = options.moduleName;
}
if (!options.plugins) {
options.plugins = { ast: [...USER_PLUGINS, ...PLUGINS] };
} else {
let potententialPugins = [...USER_PLUGINS, ...PLUGINS];
let pluginsToAdd = potententialPugins.filter((plugin) => {
return options.plugins.ast.indexOf(plugin) === -1;
});
options.plugins.ast = options.plugins.ast.slice().concat(pluginsToAdd);
}
return options;
}
export function registerPlugin(type, PluginClass) {
if (type !== 'ast') {
throw new Error(`Attempting to register ${PluginClass} as "${type}" which is not a valid Glimmer plugin type.`);
}
if (USER_PLUGINS.indexOf(PluginClass) === -1) {
USER_PLUGINS = [PluginClass, ...USER_PLUGINS];
}
}
export function removePlugin(type, PluginClass) {
if (type !== 'ast') {
throw new Error(`Attempting to unregister ${PluginClass} as "${type}" which is not a valid Glimmer plugin type.`);
}
USER_PLUGINS = USER_PLUGINS.filter((plugin) => plugin !== PluginClass);
}
|
Add a mock API path for project details, used in e.g. test_init
|
from uuid import uuid4
import requests_mock
from tests.utils import get_project_list_data
from valohai_cli.utils import get_random_string
def get_project_mock(create_project_name=None, existing_projects=None):
username = get_random_string()
project_id = uuid4()
m = requests_mock.mock()
if isinstance(existing_projects, int):
existing_projects = get_project_list_data([get_random_string() for x in range(existing_projects)])
if existing_projects is not None:
m.get('https://app.valohai.com/api/v0/projects/', json=existing_projects)
if create_project_name:
m.post('https://app.valohai.com/api/v0/projects/', json=lambda request, context: {
'id': str(project_id),
'name': create_project_name,
'owner': {
'id': 8,
'username': username,
}
})
m.get('https://app.valohai.com/api/v0/projects/ownership_options/', json=[username])
m.get(f'https://app.valohai.com/api/v0/projects/{project_id}/', json={
'id': str(project_id),
'yaml_path': 'valohai.yaml',
})
return m
|
from uuid import uuid4
import requests_mock
from tests.utils import get_project_list_data
from valohai_cli.utils import get_random_string
def get_project_mock(create_project_name=None, existing_projects=None):
username = get_random_string()
m = requests_mock.mock()
if isinstance(existing_projects, int):
existing_projects = get_project_list_data([get_random_string() for x in range(existing_projects)])
if existing_projects is not None:
m.get('https://app.valohai.com/api/v0/projects/', json=existing_projects)
if create_project_name:
m.post('https://app.valohai.com/api/v0/projects/', json=lambda request, context: {
'id': str(uuid4()),
'name': create_project_name,
'owner': {
'id': 8,
'username': username,
}
})
m.get('https://app.valohai.com/api/v0/projects/ownership_options/', json=[username])
return m
|
Fix starting inet client when should use unix socket instead.
Fix port to be int.
git-svn-id: ffaf500d3baede20d2f41eac1d275ef07405e077@1240 a8f5125c-1e01-0410-8897-facf34644b8e
|
import os
import logging
from socket import gethostbyname, gethostname
from kaa.base import ipc
from client import *
from server import *
__all__ = [ 'connect', 'DEFAULT_EPG_PORT', 'GuideClient', 'GuideServer' ]
# connected client object
_client = None
def connect(epgdb, address='127.0.0.1', logfile='/tmp/kaa-epg.log', loglevel=logging.INFO):
"""
"""
global _client
if _client:
return _client
if address.split(':')[0] not in ['127.0.0.1', '0.0.0.0'] and \
address.split(':')[0] != gethostbyname(gethostname()):
# epg is remote: host:port
if address.find(':') >= 0:
host, port = address.split(':', 1)
else:
host = address
port = DEFAULT_EPG_PORT
# create socket, pass it to client
_client = GuideClient((host, int(port)))
else:
# EPG is local, only use unix socket
# get server filename
server = os.path.join(os.path.dirname(__file__), 'server.py')
_client = ipc.launch([server, logfile, str(loglevel), epgdb, address],
2, GuideClient, "epg")
return _client
|
import os
import logging
from socket import gethostbyname, gethostname
from kaa.base import ipc
from client import *
from server import *
__all__ = [ 'connect', 'DEFAULT_EPG_PORT', 'GuideClient', 'GuideServer' ]
# connected client object
_client = None
def connect(epgdb, address='127.0.0.1', logfile='/tmp/kaa-epg.log', loglevel=logging.INFO):
"""
"""
global _client
if _client:
return _client
if address.split(':')[0] not in ['127.0.0.1', '0.0.0.0'] and \
address != gethostbyname(gethostname()):
# epg is remote: host:port
if address.find(':') >= 0:
host, port = address.split(':', 1)
else:
host = address
port = DEFAULT_EPG_PORT
# create socket, pass it to client
_client = GuideClient((host, port))
else:
# EPG is local, only use unix socket
# get server filename
server = os.path.join(os.path.dirname(__file__), 'server.py')
_client = ipc.launch([server, logfile, str(loglevel), epgdb, address],
2, GuideClient, "epg")
return _client
|
Copy readme.md to readme when building
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
from os import path
import shutil
if path.isfile('README.md'):
shutil.copyfile('README.md', 'README')
setup(name = "MarkdownPP",
description = "Markdown preprocessor",
version = "1.0",
author = "John Reese",
author_email = "john@noswap.com",
url = "https://github.com/jreese/markdown-pp",
classifiers=['License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Topic :: Utilities',
'Development Status :: 4 - Beta',
],
license='MIT License',
scripts = ['bin/markdown-pp'],
packages = ['MarkdownPP', 'MarkdownPP/Modules'],
)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
setup(name = "MarkdownPP",
description = "Markdown preprocessor",
version = "1.0",
author = "John Reese",
author_email = "john@noswap.com",
url = "https://github.com/jreese/markdown-pp",
classifiers=['License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Topic :: Utilities',
'Development Status :: 4 - Beta',
],
license='MIT License',
scripts = ['bin/markdown-pp'],
packages = ['MarkdownPP', 'MarkdownPP/Modules'],
)
|
Add Semester str method for admin interface.
Fixes #149
|
import datetime
from django.conf import settings
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
class Milestone(models.Model):
date = models.DateTimeField()
@python_2_unicode_compatible
class School(models.Model):
name = models.TextField()
slug = models.SlugField(max_length=256, unique=True)
url = models.URLField(unique=True)
milestones_url = models.URLField()
def __str__(self):
return self.name
@python_2_unicode_compatible
class Semester(models.Model):
active = models.BooleanField(default=True)
date = models.DateField()
def __str__(self):
return str(self.date)
# XXX: This is locked in for the default value of the initial migration.
# I'm not sure what needs to be done to let me safely delete this and
# have migrations continue to work.
def current_year():
today = datetime.date.today()
return today.year
@python_2_unicode_compatible
class Student(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='students')
first_name = models.TextField()
last_name = models.TextField()
# XXX: Remove null constraint after migration.
matriculation_semester = models.ForeignKey(
Semester, null=True, on_delete=models.PROTECT)
def __str__(self):
return '{} {}'.format(self.first_name, self.last_name)
|
import datetime
from django.conf import settings
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
class Milestone(models.Model):
date = models.DateTimeField()
@python_2_unicode_compatible
class School(models.Model):
name = models.TextField()
slug = models.SlugField(max_length=256, unique=True)
url = models.URLField(unique=True)
milestones_url = models.URLField()
def __str__(self):
return self.name
class Semester(models.Model):
active = models.BooleanField(default=True)
date = models.DateField()
# XXX: This is locked in for the default value of the initial migration.
# I'm not sure what needs to be done to let me safely delete this and
# have migrations continue to work.
def current_year():
today = datetime.date.today()
return today.year
@python_2_unicode_compatible
class Student(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='students')
first_name = models.TextField()
last_name = models.TextField()
# XXX: Remove null constraint after migration.
matriculation_semester = models.ForeignKey(
Semester, null=True, on_delete=models.PROTECT)
def __str__(self):
return '{} {}'.format(self.first_name, self.last_name)
|
Support None arguments in chainerx.clip and chainerx.ndarray.clip
|
import chainerx
# TODO(sonots): Implement in C++
def clip(a, a_min, a_max):
"""Clips the values of an array to a given interval.
Given an interval, values outside the interval are clipped to the
interval edges. For example, if an interval of ``[0, 1]`` is specified,
values smaller than 0 become 0, and values larger than 1 become 1.
Args:
a (~chainerx.ndarray): Array containing elements to clip.
a_min (scalar): Maximum value.
a_max (scalar): Minimum value.
Returns:
~chainerx.ndarray: An array with the elements of ``a``, but where
values < ``a_min`` are replaced with ``a_min``,
and those > ``a_max`` with ``a_max``.
Note:
The :class:`~chainerx.ndarray` typed ``a_min`` and ``a_max`` are
not supported yet.
Note:
During backpropagation, this function propagates the gradient
of the output array to the input array ``a``.
.. seealso:: :func:`numpy.clip`
"""
if a_min is None:
a_min = a.min()
if a_max is None:
a_max = a.max()
return -chainerx.maximum(-chainerx.maximum(a, a_min), -a_max)
|
import chainerx
# TODO(sonots): Implement in C++
def clip(a, a_min, a_max):
"""Clips the values of an array to a given interval.
Given an interval, values outside the interval are clipped to the
interval edges. For example, if an interval of ``[0, 1]`` is specified,
values smaller than 0 become 0, and values larger than 1 become 1.
Args:
a (~chainerx.ndarray): Array containing elements to clip.
a_min (scalar): Maximum value.
a_max (scalar): Minimum value.
Returns:
~chainerx.ndarray: An array with the elements of ``a``, but where
values < ``a_min`` are replaced with ``a_min``,
and those > ``a_max`` with ``a_max``.
Note:
The :class:`~chainerx.ndarray` typed ``a_min`` and ``a_max`` are
not supported yet.
Note:
During backpropagation, this function propagates the gradient
of the output array to the input array ``a``.
.. seealso:: :func:`numpy.clip`
"""
return -chainerx.maximum(-chainerx.maximum(a, a_min), -a_max)
|
Make failing test-lint/ tests easier to understand
|
"use strict";
const test = require("ava");
const childProcess = require("child_process");
const fs = require("fs");
const path = require("path");
const ruleFiles = fs
.readdirSync(".")
.filter(name => !name.startsWith(".") && name.endsWith(".js"));
test("test-lint/ causes errors without eslint-config-prettier", t => {
const result = childProcess.spawnSync(
"npm",
["run", "test:lint-verify-fail", "--silent"],
{ encoding: "utf8" }
);
const output = JSON.parse(result.stdout);
t.is(
output.length,
ruleFiles.length,
"every test-lint/ file must cause an error"
);
output.forEach(data => {
const name = path.basename(data.filePath).replace(/\.js$/, "");
const ruleIds = data.messages.map(message => message.ruleId);
t.true(name && ruleIds.length > 0);
// Every test-lint/ file must only cause errors related to its purpose.
if (name === "index") {
t.true(ruleIds.every(ruleId => ruleId.indexOf("/") === -1));
} else {
t.true(ruleIds.every(ruleId => ruleId.startsWith(`${name}/`)));
}
});
});
|
"use strict";
const test = require("ava");
const childProcess = require("child_process");
const fs = require("fs");
const path = require("path");
const ruleFiles = fs
.readdirSync(".")
.filter(name => !name.startsWith(".") && name.endsWith(".js"));
test("test-lint/ causes errors without eslint-config-prettier", t => {
const result = childProcess.spawnSync(
"npm",
["run", "test:lint-verify-fail", "--silent"],
{ encoding: "utf8" }
);
const output = JSON.parse(result.stdout);
t.is(
output.length,
ruleFiles.length,
"every test-lint/ file must cause an error"
);
output.forEach(data => {
const name = path.basename(data.filePath).replace(/\.js$/, "");
const ruleIds = data.messages.map(message => message.ruleId);
t.true(ruleIds.length > 0);
// Every test-lint/ file must only cause errors related to its purpose.
if (name === "index") {
t.true(ruleIds.every(ruleId => ruleId.indexOf("/") === -1));
} else {
t.true(ruleIds.every(ruleId => ruleId.startsWith(`${name}/`)));
}
});
});
|
Change content data type to longtext
|
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePageContents extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('page_contents', function (Blueprint $table) {
$table->timestamps();
$table->increments('id');
$table->longText('content');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('page_contents');
}
}
|
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePageContents extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('page_contents', function (Blueprint $table) {
$table->timestamps();
$table->increments('id');
$table->text('content');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('page_contents');
}
}
|
Mark the package as Python 3 compatible.
|
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name="django-twitter-bootstrap",
version="3.0.0",
packages=find_packages(),
package_data={
'twitter_bootstrap': [
'static/fonts/glyphicons-halflings-regular.*',
'static/js/*.js',
'static/less/*.less',
],
},
# metadata for upload to PyPI
author="Steven Cummings",
author_email="cummingscs@gmail.com",
description="Provides a Django app whose static folder contains Twitter Bootstrap assets",
license="MIT",
keywords="django app staticfiles twitter bootstrap",
url="https://github.com/estebistec/django-twitter-bootstrap",
download_url="http://pypi.python.org/pypi/django-twitter-bootstrap",
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Topic :: Software Development :: Libraries',
]
)
|
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name="django-twitter-bootstrap",
version="3.0.0",
packages=find_packages(),
package_data={
'twitter_bootstrap': [
'static/fonts/glyphicons-halflings-regular.*',
'static/js/*.js',
'static/less/*.less',
],
},
# metadata for upload to PyPI
author="Steven Cummings",
author_email="cummingscs@gmail.com",
description="Provides a Django app whose static folder contains Twitter Bootstrap assets",
license="MIT",
keywords="django app staticfiles twitter bootstrap",
url="https://github.com/estebistec/django-twitter-bootstrap",
download_url="http://pypi.python.org/pypi/django-twitter-bootstrap",
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries',
]
)
|
Return events for the next week in data api
|
<?php
class Denkmal_Response_Api_Data extends Denkmal_Response_Api_Abstract {
public function __construct(CM_Request_Get $request) {
parent::__construct($request);
}
protected function _process() {
$venueListArray = array();
/** @var Denkmal_Model_Venue $venue */
foreach (new Denkmal_Paging_Venue_All() as $venue) {
$venueListArray[] = $venue->toArrayApi();
}
$eventListArray = array();
/** @var DateTime $date */
foreach (new Denkmal_Paging_DateTime_Week() as $date) {
/** @var Denkmal_Model_Event $event */
foreach (new Denkmal_Paging_Event_Date($date, true) as $event) {
$eventListArray[] = $event->toArrayApi($this->getRender());
}
}
$messageListArray = array();
/** @var Denkmal_Model_Message $message */
foreach (new Denkmal_Paging_Message_All() as $message) {
$messageListArray[] = $message->toArrayApi();
}
$this->_setContent(array('venues' => $venueListArray, 'events' => $eventListArray, 'messages' => $messageListArray));
}
public static function match(CM_Request_Abstract $request) {
if (!parent::match($request)) {
return false;
}
return $request->getPathPart(1) === 'data';
}
}
|
<?php
class Denkmal_Response_Api_Data extends Denkmal_Response_Api_Abstract {
public function __construct(CM_Request_Get $request) {
parent::__construct($request);
}
protected function _process() {
$venueListArray = array();
$venueList = new Denkmal_Paging_Venue_All();
/** @var Denkmal_Model_Venue $venue */
foreach ($venueList as $venue) {
$venueListArray[] = $venue->toArrayApi();
}
$eventListArray = array();
$eventList = new Denkmal_Paging_Event_Date(new DateTime(), true);
/** @var Denkmal_Model_Event $event */
foreach ($eventList as $event) {
$eventListArray[] = $event->toArrayApi($this->getRender());
}
$messageListArray = array();
$messageList = new Denkmal_Paging_Message_All();
/** @var Denkmal_Model_Message $message */
foreach ($messageList as $message) {
$messageListArray[] = $message->toArrayApi();
}
$this->_setContent(array('venues' => $venueListArray, 'events' => $eventListArray, 'messages' => $messageListArray));
}
public static function match(CM_Request_Abstract $request) {
if (!parent::match($request)) {
return false;
}
return $request->getPathPart(1) === 'data';
}
}
|
Fix lightsoff to not use signal this..
svn path=/trunk/; revision=452
|
function pushed_arrow(actor, event)
{
if(animating_board)
return true;
// TODO: Need to check that click count is 1
var direction = (actor.flipped ? 1 : -1);
if(score.value + direction < 1)
return true;
score.set_value(score.value + direction);
swap_animation(direction);
gconf_client.set_int("/apps/lightsoff/score", score.value);
return true;
}
ArrowType = {
parent: Clutter.Group.type,
name: "Arrow",
class_init: function(klass, prototype)
{
prototype.set_arrow_flipped = function ()
{
this.flipped = 1;
this.remove_all();
var bkg = Clutter.Texture.new_from_file("./arrow-r.svg");
bkg.filter_quality = Clutter.TextureQuality.high;
this.add_actor(bkg);
}
},
instance_init: function(klass)
{
this.flipped = 0;
var bkg = Clutter.Texture.new_from_file("./arrow-l.svg");
bkg.filter_quality = Clutter.TextureQuality.high;
this.reactive = true;
this.signal.button_press_event.connect(pushed_arrow);
this.add_actor(bkg);
}};
Arrow = new GType(ArrowType);
|
function pushed_arrow()
{
if(animating_board)
return true;
// TODO: Need to check that click count is 1
var direction = (this.flipped ? 1 : -1);
if(score.value + direction < 1)
return true;
score.set_value(score.value + direction);
swap_animation(direction);
gconf_client.set_int("/apps/lightsoff/score", score.value);
return true;
}
ArrowType = {
parent: Clutter.Group.type,
name: "Arrow",
class_init: function(klass, prototype)
{
prototype.set_arrow_flipped = function ()
{
this.flipped = 1;
this.remove_all();
var bkg = Clutter.Texture.new_from_file("./arrow-r.svg");
bkg.filter_quality = Clutter.TextureQuality.high;
this.add_actor(bkg);
}
},
instance_init: function(klass)
{
this.flipped = 0;
var bkg = Clutter.Texture.new_from_file("./arrow-l.svg");
bkg.filter_quality = Clutter.TextureQuality.high;
this.reactive = true;
this.signal.button_press_event.connect(pushed_arrow, this);
this.add_actor(bkg);
}};
Arrow = new GType(ArrowType);
|
Disable the indent rule in eslint
|
module.exports = {
parser: "babel-eslint",
env: {
es6: true,
node: true,
},
extends: "eslint:recommended",
parserOptions: {
sourceType: "module",
ecmaFeatures: {
experimentalObjectRestSpread: true,
},
},
globals: {
atom: true,
},
rules: {
"comma-dangle": [0],
"no-this-before-super": [2],
"constructor-super": [2],
// prettier handles indentation, and they disagree on some of the code in
// find-destination-spec.jw
// indent: [2, 2],
"linebreak-style": [2, "unix"],
"no-var": [1],
"prefer-const": [1],
"no-const-assign": [2],
"no-unused-vars": [2],
semi: [2, "never"],
"no-extra-semi": [0],
},
}
|
module.exports = {
parser: "babel-eslint",
env: {
es6: true,
node: true,
},
extends: "eslint:recommended",
parserOptions: {
sourceType: "module",
ecmaFeatures: {
experimentalObjectRestSpread: true,
},
},
globals: {
atom: true,
},
rules: {
"comma-dangle": [0],
"no-this-before-super": [2],
"constructor-super": [2],
indent: [2, 2],
"linebreak-style": [2, "unix"],
"no-var": [1],
"prefer-const": [1],
"no-const-assign": [2],
"no-unused-vars": [2],
semi: [2, "never"],
"no-extra-semi": [0],
},
}
|
Fix issue on object crawling, again.
|
<?php
function ex($object, $coords, $default = null)
{
if (!is_array($object) and !is_object($object))
{
return $default;
}
$keys = explode('.', $coords);
foreach ($keys as $key)
{
if (is_array($object))
{
if (isset($object[$key]))
{
$object = $object[$key];
}
else
{
return $default;
}
}
elseif (is_object($object))
{
if (isset($object->$key))
{
$object = $object->$key;
}
else
{
return $default;
}
}
else
{
return $default;
}
}
return $object ? $object : $default;
}
|
<?php
function ex($object, $coords, $default = null)
{
if (!is_array($object) and !is_object($object))
{
return $default;
}
$keys = explode('.', $coords);
foreach ($keys as $key)
{
if (is_array($object))
{
if (isset($object[$key]))
{
$object = $object[$key];
}
else
{
return $default;
}
}
elseif (is_object($object))
{
$test = $object->$key;
if ($test)
{
$object = $test;
}
else
{
return $default;
}
}
else
{
return $default;
}
}
return $object ? $object : $default;
}
|
Add mobile as a contact field.
|
<?php
/**
* @package elemental
*/
class ElementContact extends BaseElement {
private static $db = array(
'ContactName' => 'Varchar(255)',
'Phone' => 'Varchar(100)',
'Mobile' => 'Varchar(100)',
'Fax' => 'Varchar(100)',
'Email' => 'Varchar(255)',
'Website' => 'Varchar(255)',
);
private static $extensions = array(
'Addressable',
'Geocodable'
);
/**
* @var string
*/
private static $title = "Contact Element";
public function getCMSFields() {
$this->beforeUpdateCMSFields(function($fields) {
$fields->addFieldsToTab('Root.Main', array(
Textfield::create('ContactName', 'Name'),
TextField::create('Phone', 'Phone'),
TextField::create('Mobile', 'Mobile'),
TextField::create('Fax', 'Fax'),
EmailField::create('Email', 'Email'),
$website = TextField::create('Website', 'Website')
));
$website->setRightTitle('e.g '.Director::absoluteBaseURL());
});
return parent::getCMSFields();
}
}
/**
* @package elemental
*/
class ElementContact_Controller extends BaseElement_Controller {
public function ObfuscatedEmail() {
return ($this->data()->Email) ? Email::obfuscate($this->data()->Email, 'hex') : null;
}
}
|
<?php
/**
* @package elemental
*/
class ElementContact extends BaseElement {
private static $db = array(
'ContactName' => 'Varchar(255)',
'Phone' => 'Varchar(100)',
'Fax' => 'Varchar(100)',
'Email' => 'Varchar(255)',
'Website' => 'Varchar(255)',
);
private static $extensions = array(
'Addressable',
'Geocodable'
);
/**
* @var string
*/
private static $title = "Contact Element";
public function getCMSFields() {
$this->beforeUpdateCMSFields(function($fields) {
$fields->addFieldsToTab('Root.Main', array(
Textfield::create('ContactName', 'Name'),
TextField::create('Phone', 'Phone'),
TextField::create('Fax', 'Fax'),
EmailField::create('Email', 'Email'),
$website = TextField::create('Website', 'Website')
));
$website->setRightTitle('e.g '.Director::absoluteBaseURL());
});
return parent::getCMSFields();
}
}
/**
* @package elemental
*/
class ElementContact_Controller extends BaseElement_Controller {
public function ObfuscatedEmail() {
return ($this->data()->Email) ? Email::obfuscate($this->data()->Email, 'hex') : null;
}
}
|
Rename package so it doesn't clash
|
import os
from setuptools import setup
NAME = 'sleuth-mock'
MODULES = ['sleuth']
DESCRIPTION = 'A minimal Python mocking library'
URL = "https://github.com/kazade/sleuth"
LONG_DESCRIPTION = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
AUTHOR = 'Luke Benstead'
AUTHOR_EMAIL = 'kazade@gmail.com'
setup(
name=NAME,
version='0.1',
py_modules=MODULES,
# metadata for upload to PyPI
author=AUTHOR,
author_email=AUTHOR_EMAIL,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
keywords=(
"python", "mock", "testing", "test",
"unittest", "monkeypatch", "patch", "stub"
),
url=URL
)
|
import os
from setuptools import setup
NAME = 'sleuth'
MODULES = ['sleuth']
DESCRIPTION = 'A minimal Python mocking library'
URL = "https://github.com/kazade/sleuth"
LONG_DESCRIPTION = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
AUTHOR = 'Luke Benstead'
AUTHOR_EMAIL = 'kazade@gmail.com'
setup(
name=NAME,
version='0.1',
py_modules=MODULES,
# metadata for upload to PyPI
author=AUTHOR,
author_email=AUTHOR_EMAIL,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
keywords=(
"python", "mock", "testing", "test",
"unittest", "monkeypatch", "patch", "stub"
),
url=URL
)
|
Put comment text back as commented
|
(function(ext) {
// Cleanup function when the extension is unloaded
ext._shutdown = function() {};
// Status reporting code
// Use this to report missing hardware, plugin or unsupported browser
ext._getStatus = function() {
return {status: 2, msg: 'Ready'};
};
// Block and block menu descriptions
var descriptor = {
blocks: [
['', 'My First Block', 'my_first_block'],
]
};
// Block and block menu descriptions
var descriptor = {
blocks: [
['r', 'A block that has a parameter', 'param_block', 2, 3],
]
};
// Register the extension
ScratchExtensions.register('Kinect2Scratch', descriptor, ext);
})({});
|
(function(ext) {
// Cleanup function when the extension is unloaded
ext._shutdown = function() {};
// Status reporting code
// Use this to report missing hardware, plugin or unsupported browser
ext._getStatus = function() {
return {status: 2, msg: 'Ready'};
};
// Block and block menu descriptions
var descriptor = {
blocks: [
['', 'My First Block', 'my_first_block'],
]
};
Block and block menu descriptions
var descriptor = {
blocks: [
['r', 'A block that has a parameter', 'param_block', 2, 3],
]
};
// Register the extension
ScratchExtensions.register('Kinect2Scratch', descriptor, ext);
})({});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.