text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Add experience drop to ores | package net.shadowfacts.zcraft.block;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.entity.item.EntityXPOrb;
import net.minecraft.world.World;
import net.shadowfacts.zcraft.item.ZItems;
public class BlockOre extends Block {
public BlockOre(int par1) {
super(par1, Material.rock);
}
@Override
public int idDropped(int par1, Random par2Random, int par3) {
if (this.blockID == ZBlocks.greenZinchoriumGemOre.blockID) {
return ZItems.greenZinchoriumGem.itemID;
} else {
return this.blockID;
}
}
@Override
public int quantityDropped(Random par1Random) {
if (this.blockID == ZBlocks.greenZinchoriumGemOre.blockID) {
return 3;
} else {
return 1;
}
}
@Override
public void dropXpOnBlockBreak(World world, int par2, int par3, int par4, int par5) {
if (!world.isRemote) {
int i1 = EntityXPOrb.getXPSplit(par5);
par5 -= i1;
world.spawnEntityInWorld(new EntityXPOrb(world, (double)par2 + 0.5d, (double)par3 + 0.5d, (double)par4 + 0.5d, 20));
}
}
}
| package net.shadowfacts.zcraft.block;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.shadowfacts.zcraft.item.ZItems;
public class BlockOre extends Block {
public BlockOre(int par1) {
super(par1, Material.rock);
}
public int idDropped(int par1, Random par2Random, int par3) {
if (this.blockID == ZBlocks.greenZinchoriumGemOre.blockID) {
return ZItems.greenZinchoriumGem.itemID;
} else {
return this.blockID;
}
}
public int quantityDropped(Random par1Random) {
if (this.blockID == ZBlocks.greenZinchoriumGemOre.blockID) {
return 3;
} else {
return 1;
}
}
}
|
Update the paranoid equal to the lastest version | 'use strict';
function isNothing(subject) {
return (undefined === subject) || (null === subject);
}
function isObject(subject) {
return ('object' === typeof subject) && (null !== subject);
}
function isNaNConstant(subject) {
if (undefined !== Number.isNaN) {
return Number.isNaN(subject);
} else {
// There is no Number.isNaN in Node 0.6.x
return ('number' === typeof subject) && isNaN(subject);
}
}
function isInstanceOf(constructor /*, subjects... */) {
var index,
length = arguments.length;
if (length < 2) {
return false;
}
for (index = 1; index < length; index += 1) {
if (!(arguments[index] instanceof constructor)) {
return false;
}
}
return true;
}
function collectKeys(subject, include, exclude) {
var result = Object.getOwnPropertyNames(subject);
if (!isNothing(include)) {
include.forEach(function (key) {
if (0 > result.indexOf(key)) {
result.push(key);
}
});
}
if (!isNothing(exclude)) {
result = result.filter(function (key) {
return 0 > exclude.indexOf(key);
});
}
return result;
}
module.exports.isNothing = isNothing;
module.exports.isObject = isObject;
module.exports.isNaNConstant = isNaNConstant;
module.exports.isInstanceOf = isInstanceOf;
module.exports.collectKeys = collectKeys;
| 'use strict';
function isNothing(subject) {
return (undefined === subject) || (null === subject);
}
function isObject(subject) {
return ('object' === typeof subject) && (null !== subject);
}
function isNaNConstant(subject) {
// There is not Number.isNaN in Node 0.6.x
return ('number' === typeof subject) && isNaN(subject);
}
function isInstanceOf(constructor /*, subjects... */) {
var index,
length = arguments.length;
if (length < 2) {
return false;
}
for (index = 1; index < length; index += 1) {
if (!(arguments[index] instanceof constructor)) {
return false;
}
}
return true;
}
function collectKeys(subject, include, exclude) {
var result = Object.getOwnPropertyNames(subject);
if (!isNothing(include)) {
include.forEach(function (key) {
if (0 > result.indexOf(key)) {
result.push(key);
}
});
}
if (!isNothing(exclude)) {
result = result.filter(function (key) {
return 0 > exclude.indexOf(key);
});
}
return result;
}
module.exports.isNothing = isNothing;
module.exports.isObject = isObject;
module.exports.isNaNConstant = isNaNConstant;
module.exports.isInstanceOf = isInstanceOf;
module.exports.collectKeys = collectKeys;
|
Throw error on missing parameter | <?php
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
namespace App\Libraries\Score;
use App\Exceptions\InvariantException;
use App\Libraries\Search\ScoreSearch;
use App\Libraries\Search\ScoreSearchParams;
class UserRank
{
public static function getRank(ScoreSearchParams $params): int
{
if ($params->beforeTotalScore === null && $params->beforeScore === null) {
throw new InvariantException('beforeScore or beforeTotalScore must be specified');
}
$search = new ScoreSearch($params);
$search->size(0);
static $aggName = 'by_user';
$search->setAggregations([$aggName => ['cardinality' => [
'field' => 'user_id',
]]]);
$response = $search->response();
$search->assertNoError();
return 1 + $response->aggregations($aggName)['value'];
}
}
| <?php
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
namespace App\Libraries\Score;
use App\Libraries\Search\ScoreSearch;
use App\Libraries\Search\ScoreSearchParams;
class UserRank
{
public static function getRank(ScoreSearchParams $params): ?int
{
if ($params->beforeTotalScore === null && $params->beforeScore === null) {
return null;
}
$search = new ScoreSearch($params);
$search->size(0);
static $aggName = 'by_user';
$search->setAggregations([$aggName => ['cardinality' => [
'field' => 'user_id',
]]]);
$response = $search->response();
$search->assertNoError();
return 1 + $response->aggregations($aggName)['value'];
}
}
|
Enable to use env variable.
Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com> | <?php
return [
/*
|----------------------------------------------------------------------
| Default Driver
|----------------------------------------------------------------------
|
| Set default driver for Orchestra\Memory.
|
*/
'driver' => env('MEMORY_DRIVER', 'fluent.default'),
/*
|----------------------------------------------------------------------
| Cache configuration
|----------------------------------------------------------------------
*/
'cache' => [],
/*
|----------------------------------------------------------------------
| Eloquent configuration
|----------------------------------------------------------------------
*/
'eloquent' => [
'default' => [
'model' => '\Orchestra\Memory\Model',
'cache' => false,
],
],
/*
|----------------------------------------------------------------------
| Fluent configuration
|----------------------------------------------------------------------
*/
'fluent' => [
'default' => [
'table' => 'orchestra_options',
'cache' => false,
],
],
/*
|----------------------------------------------------------------------
| Runtime configuration
|----------------------------------------------------------------------
*/
'runtime' => [],
];
| <?php
return [
/*
|----------------------------------------------------------------------
| Default Driver
|----------------------------------------------------------------------
|
| Set default driver for Orchestra\Memory.
|
*/
'driver' => 'fluent.default',
/*
|----------------------------------------------------------------------
| Cache configuration
|----------------------------------------------------------------------
*/
'cache' => [],
/*
|----------------------------------------------------------------------
| Eloquent configuration
|----------------------------------------------------------------------
*/
'eloquent' => [
'default' => [
'model' => '\Orchestra\Memory\Model',
'cache' => false,
],
],
/*
|----------------------------------------------------------------------
| Fluent configuration
|----------------------------------------------------------------------
*/
'fluent' => [
'default' => [
'table' => 'orchestra_options',
'cache' => false,
],
],
/*
|----------------------------------------------------------------------
| Runtime configuration
|----------------------------------------------------------------------
*/
'runtime' => [],
];
|
ENH: Use emailadministrator in createpublicdashboard test
git-svn-id: 496ab2bd9c9a782235c11388890d59de1024c1f0@2575 91079597-3006-4846-9bd3-4f3fb3d139a7 | <?php
// kwtest library
require_once('kwtest/kw_web_tester.php');
require_once('kwtest/kw_db.php');
class CreatePublicDashboardTestCase extends KWWebTestCase
{
var $url = null;
var $db = null;
function __construct()
{
parent::__construct();
require('config.test.php');
$this->url = $configure['urlwebsite'];
$this->db =& new database($db['type']);
$this->db->setDb($db['name']);
$this->db->setHost($db['host']);
$this->db->setUser($db['login']);
$this->db->setPassword($db['pwd']);
}
function testCreatePublicDashboard()
{
$content = $this->connect($this->url);
if(!$content)
{
return;
}
$this->login();
if(!$this->analyse($this->clickLink('[Create new project]')))
{
return;
}
$this->setField('name', 'PublicDashboard');
$this->setField('description', 'This project is for CMake dashboards run on this machine to submit to from their test suites... CMake dashboards on this machine should set CMAKE_TESTS_CDASH_SERVER to "'.$this->url.'"');
$this->setField('public', '1');
$this->setField('emailAdministrator','1');
$this->clickSubmitByName('Submit');
$this->checkErrors();
$this->assertText('The project PublicDashboard has been created successfully.');
}
}
?>
| <?php
// kwtest library
require_once('kwtest/kw_web_tester.php');
require_once('kwtest/kw_db.php');
class CreatePublicDashboardTestCase extends KWWebTestCase
{
var $url = null;
var $db = null;
function __construct()
{
parent::__construct();
require('config.test.php');
$this->url = $configure['urlwebsite'];
$this->db =& new database($db['type']);
$this->db->setDb($db['name']);
$this->db->setHost($db['host']);
$this->db->setUser($db['login']);
$this->db->setPassword($db['pwd']);
}
function testCreatePublicDashboard()
{
$content = $this->connect($this->url);
if(!$content)
{
return;
}
$this->login();
if(!$this->analyse($this->clickLink('[Create new project]')))
{
return;
}
$this->setField('name', 'PublicDashboard');
$this->setField('description', 'This project is for CMake dashboards run on this machine to submit to from their test suites... CMake dashboards on this machine should set CMAKE_TESTS_CDASH_SERVER to "'.$this->url.'"');
$this->setField('public', '1');
$this->clickSubmitByName('Submit');
$this->checkErrors();
$this->assertText('The project PublicDashboard has been created successfully.');
}
}
?>
|
Fix library import on webpack | var webpack = require('webpack');
var config = {
context: __dirname + '/src',
entry: {
'rails-ranger': './rails-ranger.js',
'rails-ranger.min': './rails-ranger.js'
},
devtool: 'source-map',
output: {
path: __dirname + '/dist',
filename: '[name].js',
library: '',
libraryTarget: 'commonjs-module'
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
query: { presets: ['babel-preset-es2015'].map(require.resolve) }
}
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
include: /\.min\.js$/,
minimize: true
})
]
}
module.exports = config;
| var webpack = require('webpack');
var config = {
context: __dirname + '/src',
entry: {
'rails-ranger': './rails-ranger.js',
'rails-ranger.min': './rails-ranger.js'
},
devtool: 'source-map',
output: {
path: __dirname + '/dist',
filename: '[name].js'
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
query: { presets: ['babel-preset-es2015'].map(require.resolve) }
}
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
include: /\.min\.js$/,
minimize: true
})
]
}
module.exports = config;
|
Use 'with' instead of lock.acquire/release() | #!/usr/bin/env python
# vim:fileencoding=utf-8:noet
from powerline import Powerline
from powerline.lib.monotonic import monotonic
import sys
import time
import i3
from threading import Lock
name = 'wm'
if len( sys.argv ) > 1:
name = sys.argv[1]
powerline = Powerline(name, renderer_module='i3bgbar')
powerline.update_renderer()
interval = 0.5
print '{"version": 1, "custom_workspace": true}'
print '['
print ' [[],[]]'
lock = Lock()
def render( event=None, data=None, sub=None ):
global lock
with lock:
s = '[\n' + powerline.render(side='right')[:-2] + '\n]\n'
s += ',[\n' + powerline.render(side='left' )[:-2] + '\n]'
print ',[\n' + s + '\n]'
sys.stdout.flush()
sub = i3.Subscription( render, 'workspace' )
while True:
start_time = monotonic()
render()
time.sleep(max(interval - (monotonic() - start_time), 0.1))
| #!/usr/bin/env python
# vim:fileencoding=utf-8:noet
from powerline import Powerline
from powerline.lib.monotonic import monotonic
import sys
import time
import i3
from threading import Lock
name = 'wm'
if len( sys.argv ) > 1:
name = sys.argv[1]
powerline = Powerline(name, renderer_module='i3bgbar')
powerline.update_renderer()
interval = 0.5
print '{"version": 1, "custom_workspace": true}'
print '['
print ' [[],[]]'
lock = Lock()
def render( event=None, data=None, sub=None ):
global lock
lock.acquire()
s = '[\n' + powerline.render(side='right')[:-2] + '\n]\n'
s += ',[\n' + powerline.render(side='left' )[:-2] + '\n]'
print ',[\n' + s + '\n]'
sys.stdout.flush()
lock.release()
sub = i3.Subscription( render, 'workspace' )
while True:
start_time = monotonic()
render()
time.sleep(max(interval - (monotonic() - start_time), 0.1))
|
Change allowedBiomes from BiomeGenBase[] to Biome[] | package com.slugterra.biomes;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.gen.layer.GenLayer;
import net.minecraft.world.gen.layer.IntCache;
public class SlugterraGenLayerBiome extends GenLayer {
protected Biome[] allowedBiomes = {BiomeRegistry.undertowCavern, BiomeRegistry.snowdanceCavern, BiomeRegistry.deadWeed, BiomeRegistry.bullseyeCavern, BiomeRegistry.quietlawnCavern, BiomeRegistry.hideoutCavern};
public SlugterraGenLayerBiome(long seed, GenLayer genlayer) {
super(seed);
this.parent = genlayer;
}
public SlugterraGenLayerBiome(long seed) {
super(seed);
}
@Override
public int[] getInts(int x, int z, int width, int depth)
{
int[] dest = IntCache.getIntCache(width*depth);
for (int dz=0; dz<depth; dz++)
{
for (int dx=0; dx<width; dx++)
{
this.initChunkSeed(dx+x, dz+z);
dest[(dx+dz*width)] = Biome.getIdForBiome(this.allowedBiomes[nextInt(this.allowedBiomes.length)]);
}
}
return dest;
}
} | package com.slugterra.biomes;
import com.slugterra.biomes.BiomeRegistry;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraft.world.gen.layer.GenLayer;
import net.minecraft.world.gen.layer.IntCache;
public class SlugterraGenLayerBiome extends GenLayer {
protected BiomeGenBase[] allowedBiomes = {BiomeRegistry.undertowCavern, BiomeRegistry.snowdanceCavern, BiomeRegistry.deadWeed, BiomeRegistry.bullseyeCavern, BiomeRegistry.quietlawnCavern, BiomeRegistry.hideoutCavern};
public SlugterraGenLayerBiome(long seed, GenLayer genlayer) {
super(seed);
this.parent = genlayer;
}
public SlugterraGenLayerBiome(long seed) {
super(seed);
}
@Override
public int[] getInts(int x, int z, int width, int depth)
{
int[] dest = IntCache.getIntCache(width*depth);
for (int dz=0; dz<depth; dz++)
{
for (int dx=0; dx<width; dx++)
{
this.initChunkSeed(dx+x, dz+z);
dest[(dx+dz*width)] = this.allowedBiomes[nextInt(this.allowedBiomes.length)].biomeID;
}
}
return dest;
}
} |
Bring back source maps in tests | var _ = require('lodash')
var webpackConfig = require('./webpack.config')
var config = {
frameworks: ['mocha', 'effroi'],
preprocessors: {
'tests/index.js': ['webpack', 'sourcemap']
},
files: [
'tests/index.js'
],
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters: ['progress', 'coverage'],
// this watcher watches when bundled files are updated
autoWatch: true,
webpack: _.extend(webpackConfig, {
entry: undefined,
// this watcher watches when source files are updated
watch: true,
devtool: 'inline-source-map',
module: _.extend(webpackConfig.module, {
postLoaders: [{
test: /\.js/,
exclude: /(test|node_modules)/,
loader: 'istanbul-instrumenter'
}]
})
}),
webpackServer: {
noInfo: true
},
client: {
useIframe: true,
captureConsole: true,
mocha: {
ui: 'qunit'
}
},
browsers: [process.env.TRAVIS ? 'Firefox' : 'Chrome'],
browserNoActivityTimeout: 30000,
coverageReporter: {
reporters: [
{type: 'html', dir: 'coverage/'},
{type: 'text-summary'}
]
}
}
module.exports = function (c) {
c.set(config)
}
module.exports.config = config
| var _ = require('lodash')
var webpackConfig = require('./webpack.config')
var config = {
frameworks: ['mocha', 'effroi'],
preprocessors: {
'tests/index.js': ['webpack', 'sourcemap']
},
files: [
'tests/index.js'
],
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters: ['progress', 'coverage'],
// this watcher watches when bundled files are updated
autoWatch: true,
webpack: _.extend(webpackConfig, {
entry: undefined,
// this watcher watches when source files are updated
watch: true,
module: _.extend(webpackConfig.module, {
postLoaders: [{
test: /\.js/,
exclude: /(test|node_modules)/,
loader: 'istanbul-instrumenter'
}]
})
}),
webpackServer: {
noInfo: true
},
client: {
useIframe: true,
captureConsole: true,
mocha: {
ui: 'qunit'
}
},
browsers: [process.env.TRAVIS ? 'Firefox' : 'Chrome'],
browserNoActivityTimeout: 30000,
coverageReporter: {
reporters: [
{type: 'html', dir: 'coverage/'},
{type: 'text-summary'}
]
}
}
module.exports = function (c) {
c.set(config)
}
module.exports.config = config
|
Fix @Override method deprecated in RN 0.47 | package com.packetzoom.RNPacketzoom;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.bridge.JavaScriptModule;
public class RNPacketzoom implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(
ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new RNPacketzoomModule(reactContext));
return modules;
}
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(
ReactApplicationContext reactContext) {
return Collections.emptyList();
}
} | package com.packetzoom.RNPacketzoom;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.bridge.JavaScriptModule;
public class RNPacketzoom implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(
ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new RNPacketzoomModule(reactContext));
return modules;
}
@Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(
ReactApplicationContext reactContext) {
return Collections.emptyList();
}
} |
Fix error catching in thumbnail generation | <?php
namespace App\Jobs;
use App\Post;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue;
use Image;
use Intervention\Image\Exception\NotReadableException;
class GenerateThumbnail extends Job implements SelfHandling, ShouldQueue
{
use InteractsWithQueue, SerializesModels;
private $post;
private $imageUrl;
public function __construct(Post $post, $imageUrl)
{
$this->post = $post;
$this->imageUrl = $imageUrl;
}
public function handle()
{
try {
$thumbnailUrl = 'img/thumbs/' . $this->post->id . '.jpg';
$thumbnail = Image::make($this->imageUrl);
$thumbnail->fit(140);
$thumbnail->save(public_path($thumbnailUrl));
} catch (NotReadableException $e) {
$thumbnailUrl = null;
}
$this->post->thumbnail_url = $thumbnailUrl;
$this->post->save();
}
}
| <?php
namespace App\Jobs;
use App\Post;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue;
use Image;
class GenerateThumbnail extends Job implements SelfHandling, ShouldQueue
{
use InteractsWithQueue, SerializesModels;
private $post;
private $imageUrl;
public function __construct(Post $post, $imageUrl)
{
$this->post = $post;
$this->imageUrl = $imageUrl;
}
public function handle()
{
try {
$thumbnailUrl = 'img/thumbs/' . $this->post->id . '.jpg';
$thumbnail = Image::make($this->imageUrl);
$thumbnail->fit(140);
$thumbnail->save(public_path($thumbnailUrl));
} catch (NotReadableException $e) {
$thumbnailUrl = null;
}
$this->post->thumbnail_url = $thumbnailUrl;
$this->post->save();
}
}
|
Make POST request to /metadata/** return the new metadata instead of giving empty response | package me.izstas.rfs.server.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import me.izstas.rfs.server.config.web.PathWithinPattern;
import me.izstas.rfs.server.model.Metadata;
import me.izstas.rfs.server.service.MetadataService;
@RestController
@RequestMapping("/metadata/**")
public class MetadataController {
@Autowired
private MetadataService metadataService;
@RequestMapping(method = RequestMethod.GET)
public Metadata getMetadata(@PathWithinPattern String path) {
return metadataService.getMetadataFromUserPath(path);
}
@RequestMapping(method = RequestMethod.POST)
public Metadata applyMetadata(@PathWithinPattern String path, @RequestBody Metadata metadata) {
metadataService.applyMetadataToUserPath(path, metadata);
return metadataService.getMetadataFromUserPath(path);
}
}
| package me.izstas.rfs.server.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import me.izstas.rfs.server.config.web.PathWithinPattern;
import me.izstas.rfs.server.model.Metadata;
import me.izstas.rfs.server.service.MetadataService;
@RestController
@RequestMapping("/metadata/**")
public class MetadataController {
@Autowired
private MetadataService metadataService;
@RequestMapping(method = RequestMethod.GET)
public Metadata getMetadata(@PathWithinPattern String path) {
return metadataService.getMetadataFromUserPath(path);
}
@RequestMapping(method = RequestMethod.POST)
public void applyMetadata(@PathWithinPattern String path, @RequestBody Metadata metadata) {
metadataService.applyMetadataToUserPath(path, metadata);
}
}
|
Modify the query to search for movie theaters only | require('isomorphic-fetch')
const qs = require('querystring')
let [client_id, client_secret] = process.env.FOURSQUARE_PARAMS.split(';')
let params = {
client_id,
client_secret,
v: '20161230',
sortByDistance: 1,
query: 'movie theater',
ll: '41.967985,-87.688307',
}
let url = 'https://api.foursquare.com/v2/venues/search?' + qs.stringify(params)
// console.log(url)
fetch(url)
.then(res => res.json())
.then(data => {
let venues = data.response.venues
// printVenue(venues[0])
for (let venue of venues) {
printVenue(venue)
console.log('===============')
}
})
function printVenue(v) {
console.log(v.name)
console.log(v.location.address)
let categories = v.categories.map(c => c.name)
console.log(categories.join(','))
}
| require('isomorphic-fetch')
const qs = require('querystring')
let [client_id, client_secret] = process.env.FOURSQUARE_PARAMS.split(';')
let params = {
client_id,
client_secret,
v: '20161230',
ll: '41.967985,-87.688307',
}
let url = 'https://api.foursquare.com/v2/venues/search?' + qs.stringify(params)
// console.log(url)
fetch(url)
.then(res => res.json())
.then(data => {
let venues = data.response.venues
// printVenue(venues[0])
for (let venue of venues) {
printVenue(venue)
console.log('===============')
}
})
function printVenue(v) {
console.log(v.name)
console.log(v.location.address)
let categories = v.categories.map(c => c.name)
console.log(categories.join(','))
}
|
Order feedback items by their timestamp. | from django.conf import settings
from django.db import models
class FeedbackItem(models.Model):
timestamp = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(settings.AUTH_USER_MODEL)
resolved = models.BooleanField(default=False)
content = models.TextField()
screenshot = models.FileField(blank=True, null=True, upload_to="feedback/screenshots")
# Request Data
view = models.CharField(max_length=255)
request_path = models.CharField(max_length=255)
# The longest methods should be 7 chars, but we'll allow custom methods up
# to 20 chars just in case.
request_method = models.CharField(max_length=20, blank=True, null=True)
# How long is the longest encoding name?
request_encoding = models.CharField(max_length=20, blank=True, null=True)
request_meta = models.TextField(blank=True, null=True)
request_get = models.TextField(blank=True, null=True)
request_post = models.TextField(blank=True, null=True)
request_files = models.TextField(blank=True, null=True)
def __unicode__(self):
return "{username} at {path}".format(
username=self.user.get_full_name(),
path = self.request_path
)
class Meta:
ordering = ["-timestamp"]
| from django.conf import settings
from django.db import models
class FeedbackItem(models.Model):
timestamp = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(settings.AUTH_USER_MODEL)
resolved = models.BooleanField(default=False)
content = models.TextField()
screenshot = models.FileField(blank=True, null=True, upload_to="feedback/screenshots")
# Request Data
view = models.CharField(max_length=255)
request_path = models.CharField(max_length=255)
# The longest methods should be 7 chars, but we'll allow custom methods up
# to 20 chars just in case.
request_method = models.CharField(max_length=20, blank=True, null=True)
# How long is the longest encoding name?
request_encoding = models.CharField(max_length=20, blank=True, null=True)
request_meta = models.TextField(blank=True, null=True)
request_get = models.TextField(blank=True, null=True)
request_post = models.TextField(blank=True, null=True)
request_files = models.TextField(blank=True, null=True)
def __unicode__(self):
return "{username} at {path}".format(
username=self.user.get_full_name(),
path = self.request_path
)
|
Use Stream instead of StringUtils | package org.kepennar.aproc.complicatebusiness;
import static java.util.Comparator.naturalOrder;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import java.util.List;
import java.util.stream.Stream;
import javax.inject.Inject;
import org.kepennar.aproc.tasks.Task;
import org.kepennar.aproc.tasks.TaskRepository;
import org.springframework.stereotype.Service;
@Service
public class ComplicateBusinessService {
private final TaskRepository taskRepository;
@Inject
public ComplicateBusinessService(TaskRepository taskRepository) {
this.taskRepository = taskRepository;
}
public List<Task> getAllTransformedTasks() {
return taskRepository.findAll().parallelStream()
.map(t -> {
return new Task(sort2(t.getName()), sort2(t.getDescription()));
})
.collect(toList());
}
private final static String sort2(String word) {
return Stream.of(word.split(""))
.sorted(naturalOrder())
.collect(joining());
}
}
| package org.kepennar.aproc.complicatebusiness;
import static java.util.stream.Collectors.toList;
import java.util.List;
import javax.inject.Inject;
import org.kepennar.aproc.tasks.Task;
import org.kepennar.aproc.tasks.TaskRepository;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
@Service
public class ComplicateBusinessService {
private final TaskRepository taskRepository;
@Inject
public ComplicateBusinessService(TaskRepository taskRepository) {
this.taskRepository = taskRepository;
}
public List<Task> getAllTransformedTasks() {
return taskRepository.findAll().parallelStream()
.map(t -> {
return new Task(sort(t.getName()), sort(t.getDescription()));
})
.collect(toList());
}
private final static String sort(String word) {
return String.join("",
StringUtils.sortStringArray(word.split(""))
);
}
}
|
Use Chrome as well as Firefox for the unit tests | module.exports = function(config) {
config.set({
frameworks: [
'jasmine',
'karma-typescript'
],
plugins: [
'karma-typescript',
'karma-jasmine',
'karma-edge-launcher',
'karma-firefox-launcher',
'karma-chrome-launcher'
],
files: [
'./src/*.ts',
'./test/*.ts'
],
exclude: [
"**/*.d.ts",
"**/*.js",
"./node_modules"
],
preprocessors: {
'**/*.ts': ['karma-typescript']
},
karmaTypescriptConfig: {
tsconfig: "./test/tsconfig.json",
},
reporters: [ 'progress', 'karma-typescript' ],
browsers: [
// 'Edge',
'Firefox',
'Chrome', ],
port: 9876,
singleRun: true,
logLevel: config.LOG_INFO,
})
}
| module.exports = function(config) {
config.set({
frameworks: [
'jasmine',
'karma-typescript'
],
plugins: [
'karma-typescript',
'karma-jasmine',
'karma-edge-launcher',
'karma-firefox-launcher',
'karma-chrome-launcher'
],
files: [
'./src/*.ts',
'./test/*.ts'
],
exclude: [
"**/*.d.ts",
"**/*.js",
"./node_modules"
],
preprocessors: {
'**/*.ts': ['karma-typescript']
},
karmaTypescriptConfig: {
tsconfig: "./test/tsconfig.json",
},
reporters: [ 'progress', 'karma-typescript' ],
browsers: [
// 'Edge',
'Firefox' ],
port: 9876,
singleRun: true,
})
}
|
Remove string from a copy and paste fail. | """Setup script to generate an stand-alone executable.
Author-email: "Dietmar Winkler" <dietmar.winkler@dwe.no>
License: See UNLICENSE file
Usage: Run the build process by running the command 'python setup.py build'
If everything works well you should find a subdirectory in the build
subdirectory that contains the files needed to run the script
without Python
"""
from setuptools import setup, find_packages
CLASSIFIERS = """
Environment :: Console
Intended Audience :: Developers
Operating System :: OS Independent
Programming Language :: Python :: 2
""".strip().splitlines()
META = {
'name': 'ttws',
'url': 'https://github.com/dietmarw/trimtrailingwhitespaces',
'version': '0.3',
'description': 'Script to remove trailing whitespaces from textfiles.',
'classifiers': CLASSIFIERS,
'license': 'UNLICENSE',
'author': 'Dietmar Winkler',
'author_email': 'http://claimid/dietmarw',
'packages': find_packages(exclude=['test']),
'entry_points': {
'console_scripts': 'ttws = ttws.cli:main'
},
'platforms': 'Posix; MacOS X; Windows',
'include_package_data': False,
'zip_safe': False,
'install_requires': ['pyparsing'],
'extras_require': {
'testing': ['pytest']
}
}
if __name__ == '__main__':
setup(**META)
| """Setup script to generate an stand-alone executable.
Author-email: "Dietmar Winkler" <dietmar.winkler@dwe.no>
License: See UNLICENSE file
Usage: Run the build process by running the command 'python setup.py build'
If everything works well you should find a subdirectory in the build
subdirectory that contains the files needed to run the script
without Python
"""
from setuptools import setup, find_packages
CLASSIFIERS = """
Environment :: Console
Intended Audience :: Developers
Operating System :: OS Independent
Programming Language :: Python :: 2
""".strip().splitlines()
META = {
'name': 'ttws',
'url': 'https://github.com/dietmarw/trimtrailingwhitespaces',
'version': '0.3',
'description': 'WSGI middleware to handle HTTP responses using exceptions',
'description': 'Script to remove trailing whitespaces from textfiles.',
'classifiers': CLASSIFIERS,
'license': 'UNLICENSE',
'author': 'Dietmar Winkler',
'author_email': 'http://claimid/dietmarw',
'packages': find_packages(exclude=['test']),
'entry_points': {
'console_scripts': 'ttws = ttws.cli:main'
},
'platforms': 'Posix; MacOS X; Windows',
'include_package_data': False,
'zip_safe': False,
'install_requires': ['pyparsing'],
'extras_require': {
'testing': ['pytest']
}
}
if __name__ == '__main__':
setup(**META)
|
Use an ordereddict for sorting revisions | from collections import OrderedDict
import json
from .load_data_from_file import load_data_from_file
from .get_old_dict_values import get_old_dict_values
from .log import log
from .paths import make_course_path
def load_previous(course_path):
try:
prior_data = load_data_from_file(course_path)
prior = json.loads(prior_data)
except FileNotFoundError:
prior = None
revisions = []
# print(course_path, revisions)
if prior and ('revisions' in prior):
revisions = prior['revisions']
del prior['revisions']
return (prior, revisions or [])
def check_for_revisions(course):
prior, revisions = load_previous(make_course_path(course['clbid']))
if not prior:
return None
diff = get_old_dict_values(prior, course)
ordered_diff = OrderedDict()
for key in sorted(diff.keys()):
ordered_diff[key] = diff[key]
if ordered_diff:
revisions.append(ordered_diff)
log('revision in %d:' % (course['clbid']), ordered_diff)
if revisions and (('revisions' not in course) or (revisions != course.get('revisions'))):
return revisions
return None
| import json
from .load_data_from_file import load_data_from_file
from .get_old_dict_values import get_old_dict_values
from .log import log
from .paths import make_course_path
def load_previous(course_path):
try:
prior_data = load_data_from_file(course_path)
prior = json.loads(prior_data)
except FileNotFoundError:
prior = None
revisions = []
# print(course_path, revisions)
if prior and ('revisions' in prior):
revisions = prior['revisions']
del prior['revisions']
return (prior, revisions or [])
def check_for_revisions(course):
prior, revisions = load_previous(make_course_path(course['clbid']))
if not prior:
return None
diff = get_old_dict_values(prior, course)
if diff:
revisions.append(diff)
log('revision in %d:' % (course['clbid']), diff)
if revisions and (('revisions' not in course) or (revisions != course.get('revisions'))):
return revisions
return None
|
Include author email since it's required info
Same as maintainer email, because the author email is unknown | import os
from setuptools import setup
longDesc = ""
if os.path.exists("README.rst"):
longDesc = open("README.rst").read().strip()
setup(
name = "pytesseract",
version = "0.1.6",
author = "Samuel Hoffstaetter",
author_email="pytesseract@madmaze.net",
maintainer = "Matthias Lee",
maintainer_email = "pytesseract@madmaze.net",
description = ("Python-tesseract is a python wrapper for google's Tesseract-OCR"),
long_description = longDesc,
license = "GPLv3",
keywords = "python-tesseract OCR Python",
url = "https://github.com/madmaze/python-tesseract",
packages=['pytesseract'],
package_dir={'pytesseract': 'src'},
package_data = {'pytesseract': ['*.png','*.jpg']},
entry_points = {'console_scripts': ['pytesseract = pytesseract.pytesseract:main']},
classifiers = [
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
]
)
| import os
from setuptools import setup
longDesc = ""
if os.path.exists("README.rst"):
longDesc = open("README.rst").read().strip()
setup(
name = "pytesseract",
version = "0.1.6",
author = "Samuel Hoffstaetter",
author_email="",
maintainer = "Matthias Lee",
maintainer_email = "pytesseract@madmaze.net",
description = ("Python-tesseract is a python wrapper for google's Tesseract-OCR"),
long_description = longDesc,
license = "GPLv3",
keywords = "python-tesseract OCR Python",
url = "https://github.com/madmaze/python-tesseract",
packages=['pytesseract'],
package_dir={'pytesseract': 'src'},
package_data = {'pytesseract': ['*.png','*.jpg']},
entry_points = {'console_scripts': ['pytesseract = pytesseract.pytesseract:main']},
classifiers = [
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
]
)
|
OAK-5793: Improve coverage for security code in oak-core
Missing license header
git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1784852 13f79535-47bb-0310-9956-ffa450edef68 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.oak.spi.security.authentication;
import java.io.IOException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
/**
* Created by angela on 28/02/17.
*/
class ThrowingCallbackHandler implements CallbackHandler {
private boolean throwIOException;
ThrowingCallbackHandler(boolean throwIOException) {
this.throwIOException = throwIOException;
}
@Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
if (throwIOException) {
throw new IOException();
} else {
throw new UnsupportedCallbackException(new Callback() {
});
}
}
}
| package org.apache.jackrabbit.oak.spi.security.authentication;
import java.io.IOException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
/**
* Created by angela on 28/02/17.
*/
class ThrowingCallbackHandler implements CallbackHandler {
private boolean throwIOException;
ThrowingCallbackHandler(boolean throwIOException) {
this.throwIOException = throwIOException;
}
@Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
if (throwIOException) {
throw new IOException();
} else {
throw new UnsupportedCallbackException(new Callback() {
});
}
}
}
|
Use test_client() as context manager | import pytest
from tests.conftest import set_config_values
@pytest.mark.parametrize('check_proxy_header,header_value,expected_code', [
(True, 'key_1', 200),
(True, 'wrong_key', 403),
(False, 'wrong_key', 200),
(False, 'key_1', 200),
])
def test_route_correct_secret_key(app_, check_proxy_header, header_value, expected_code):
with set_config_values(app_, {
'ROUTE_SECRET_KEY_1': 'key_1',
'ROUTE_SECRET_KEY_2': '',
'CHECK_PROXY_HEADER': check_proxy_header,
}):
with app_.test_client() as client:
response = client.get(
path='/_status?elb=True',
headers=[
('X-Custom-forwarder', header_value),
]
)
assert response.status_code == expected_code
| import pytest
from tests.conftest import set_config_values
@pytest.mark.parametrize('check_proxy_header,header_value,expected_code', [
(True, 'key_1', 200),
(True, 'wrong_key', 403),
(False, 'wrong_key', 200),
(False, 'key_1', 200),
])
def test_route_correct_secret_key(app_, check_proxy_header, header_value, expected_code):
with set_config_values(app_, {
'ROUTE_SECRET_KEY_1': 'key_1',
'ROUTE_SECRET_KEY_2': '',
'CHECK_PROXY_HEADER': check_proxy_header,
}):
client = app_.test_client()
response = client.get(
path='/_status?elb=True',
headers=[
('X-Custom-forwarder', header_value),
]
)
assert response.status_code == expected_code
|
Add { after 'if' condition
Fixes #5 | import {createFilter} from 'rollup-pluginutils'
import Compiler from './compiler'
import objectAssign from 'object-assign'
import path from 'path'
export default function plugin (options = {}) {
options = objectAssign({}, options, {extensions: ['.vue'] })
let filter = createFilter(options.include, options.exclude)
const extensions = options.extensions
delete options.extensions
delete options.include
delete options.exclude
const compiler = new Compiler(options)
return {
transform (code, id) {
if (!filter(id)) { return null }
if (extensions.indexOf(path.extname(id)) === -1) { return null }
return new Promise((resolve) => {
compiler
.compile(code, id)
.then((compiled) => resolve(compiled))
})
}
}
}
| import {createFilter} from 'rollup-pluginutils'
import Compiler from './compiler'
import objectAssign from 'object-assign'
import path from 'path'
export default function plugin (options = {}) {
options = objectAssign({}, options, {extensions: ['.vue'] })
let filter = createFilter(options.include, options.exclude)
const extensions = options.extensions
delete options.extensions
delete options.include
delete options.exclude
const compiler = new Compiler(options)
return {
transform (code, id) {
if (!filter(id)) return null
if (extensions.indexOf(path.extname(id)) === -1) return null
return new Promise((resolve) => {
compiler
.compile(code, id)
.then((compiled) => resolve(compiled))
})
}
}
}
|
Remove useless header setting, since it is already set by express. | 'use strict';
var express = require('express');
var app = express();
var stationsRoutes = require('./src/routes/stations');
if (!process.env['BIKE_API_KEY']) {
console.warn('WARNING : The environment variable $BIKE_API_KEY is not configured.');
} else {
console.log('The $BIKE_API_KEY is ' + process.env['BIKE_API_KEY']);
}
app.use('/api', function (req, res, next) {
// Allow CORS.
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
app.use('/api', stationsRoutes);
app.use('/', express.static('public'));
app.listen(8080, function () {
console.info('Server running on port 8080.');
});
| 'use strict';
var express = require('express');
var app = express();
var stationsRoutes = require('./src/routes/stations');
if (!process.env['BIKE_API_KEY']) {
console.warn('WARNING : The environment variable $BIKE_API_KEY is not configured.');
} else {
console.log('The $BIKE_API_KEY is ' + process.env['BIKE_API_KEY']);
}
app.use('/api', function (req, res, next) {
// Allow CORS and set the proper content-type header.
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.header('Content-Type', 'application/json; charset=utf-8');
next();
});
app.use('/api', stationsRoutes);
app.use('/', express.static('public'));
app.listen(8080, function () {
console.info('Server running on port 8080.');
});
|
Fix country ISO code (2) validation rule to match exactly 2 chars long | <?php namespace App\Http\Requests;
use App\Http\Requests\Request;
use App\Contact;
use App\Business;
use Session;
use Input;
class ContactFormRequest extends Request {
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
if (! \Auth::user()->isOwner($this->business) ) return false;
return $this->contact === null || $this->contact->isSuscribedTo($this->business);
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
$rules = [ 'firstname' => 'required|min:3',
'lastname' => 'required|min:3',
'gender' => 'required|max:1',
'mobile' => 'phone',
'mobile_country' => 'required_with:mobile|size:2' /* FIXME: LENGHT MUST BE EXACT 2 */
];
switch ($this->method())
{
case 'PATCH':
case 'PUT':
case 'POST':
return $rules;
break;
default:
return [];
break;
}
}
}
| <?php namespace App\Http\Requests;
use App\Http\Requests\Request;
use App\Contact;
use App\Business;
use Session;
use Input;
class ContactFormRequest extends Request {
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
# $business = Business::findOrFail( $this->business );
if (! \Auth::user()->isOwner($this->business) ) return false;
return $this->contact === null || $this->contact->isSuscribedTo($this->business);
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
$rules = [ 'firstname' => 'required|min:3',
'lastname' => 'required|min:3',
'gender' => 'required|max:1',
'mobile' => 'phone',
'mobile_country' => 'required_with:mobile|max:2' /* FIXME: LENGHT MUST BE EXACT 2 */
];
switch ($this->method())
{
case 'PATCH':
case 'PUT':
case 'POST':
return $rules;
break;
default:
return [];
break;
}
}
}
|
Fix broken search for blame- class | $(function(){
$(".blame").hover(function() {
if (!$(this).hasClass("load"))
return;
var classList = $(this).prop('classList');
var blameSha1 = null;
var sha1 = null;
$.each(classList, function(i, v) {
if (v.startsWith("blame-")) {
blameSha1 = v;
sha1 = v.substring(6);
return false;
}
});
$.getJSON("/commitHeader/" + sha1, function (commitHeader) {
var title = commitHeader.date + "\n";
title += commitHeader.author + "\n\n";
title += commitHeader.message.trim();
var blameSha1Class = "." + blameSha1;
var withBlameSha1 = $(blameSha1Class);
withBlameSha1.attr("title", title).removeClass("load");
});
}, function() {
// unhover
});
});
| $(function(){
$(".blame").hover(function() {
if (!$(this).hasClass("load"))
return;
var classList = $(this).prop('classList');
var blameSha1 = null;
var sha1 = null;
$.each(classList, function(i, v) {
if (v.startsWith("blame-"))
blameSha1 = v;
sha1 = v.substring(6);
});
$.getJSON("/commitHeader/" + sha1, function (commitHeader) {
var title = commitHeader.date + "\n";
title += commitHeader.author + "\n\n";
title += commitHeader.message.trim();
var blameSha1Class = "." + blameSha1;
var withBlameSha1 = $(blameSha1Class);
withBlameSha1.attr("title", title).removeClass("load");
});
}, function() {
// unhover
});
});
|
Rename plugin id as well | package org.monospark.actioncontrol;
import java.nio.file.Path;
import org.monospark.actioncontrol.config.ConfigParseException;
import org.monospark.actioncontrol.group.Group;
import org.monospark.actioncontrol.handler.ActionHandler;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.config.ConfigDir;
import org.spongepowered.api.event.Event;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.game.state.GameInitializationEvent;
import org.spongepowered.api.plugin.Plugin;
import com.google.inject.Inject;
@Plugin(id = "actioncontrol", name = "ActionControl", version = "1.0")
public class ActionControl {
@Inject
@ConfigDir(sharedRoot = false)
private Path privateConfigDir;
@Listener
public void onServerInit(GameInitializationEvent event) {
for(ActionHandler<?, ?> handler : ActionHandler.ALL) {
registerActionHandler(handler);
}
try {
Group.getRegistry().loadGroups(privateConfigDir);
} catch (ConfigParseException e) {
e.printStackTrace();
}
}
private <E extends Event> void registerActionHandler(ActionHandler<E, ?> handler) {
Sponge.getGame().getEventManager().registerListener(this, handler.getEventClass(), handler);
}
}
| package org.monospark.actioncontrol;
import java.nio.file.Path;
import org.monospark.actioncontrol.config.ConfigParseException;
import org.monospark.actioncontrol.group.Group;
import org.monospark.actioncontrol.handler.ActionHandler;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.config.ConfigDir;
import org.spongepowered.api.event.Event;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.game.state.GameInitializationEvent;
import org.spongepowered.api.plugin.Plugin;
import com.google.inject.Inject;
@Plugin(id = "actionpermissions", name = "ActionPermissions", version = "1.0")
public class ActionControl {
@Inject
@ConfigDir(sharedRoot = false)
private Path privateConfigDir;
@Listener
public void onServerInit(GameInitializationEvent event) {
for(ActionHandler<?, ?> handler : ActionHandler.ALL) {
registerActionHandler(handler);
}
try {
Group.getRegistry().loadGroups(privateConfigDir);
} catch (ConfigParseException e) {
e.printStackTrace();
}
}
private <E extends Event> void registerActionHandler(ActionHandler<E, ?> handler) {
Sponge.getGame().getEventManager().registerListener(this, handler.getEventClass(), handler);
}
}
|
Modify generated category form field instead of reinitialize it
The category fields had not been translated as the field had been
reinitialized instead of modified. With this PR the auto generated field
(with its localized verbose_name) will be kept and adapted to the
filtered queryset.
Furthermore the required parameter is set to true if there are any
categories for the module. | from adhocracy4.categories import models as category_models
class CategorizableFieldMixin:
category_field_name = 'category'
def __init__(self, *args, **kwargs):
module = kwargs.pop('module')
super().__init__(*args, **kwargs)
field = self.fields[self.category_field_name]
field.queryset = category_models.Category.objects.filter(module=module)
required = field.queryset.exists()
field.empty_label = None
field.required = required
field.widget.is_required = required
def show_categories(self):
field = self.fields[self.category_field_name]
module_has_categories = field.queryset.exists()
return module_has_categories
| from django import forms
from adhocracy4.categories import models as category_models
class CategorizableFieldMixin:
category_field_name = 'category'
def __init__(self, *args, **kwargs):
module = kwargs.pop('module')
super().__init__(*args, **kwargs)
queryset = category_models.Category.objects.filter(module=module)
self.fields[self.category_field_name] = forms.ModelChoiceField(
queryset=queryset,
empty_label=None,
required=False,
)
def show_categories(self):
module_has_categories = len(self.fields['category'].queryset) > 0
return module_has_categories
|
Fix the “Line too long” warning | import gulp from 'gulp';
import requireDir from 'require-dir';
requireDir('./gulp/tasks');
gulp.task('default',
['replace-webpack-code', 'webpack-dev-server', 'views:dev',
'copy:dev', 'views:watch', 'copy:watch']);
gulp.task('build:web', ['webpack:build:web', 'views:build:web', 'copy:build:web']);
gulp.task('build:cordova', ['webpack:build:cordova', 'views:build:cordova', 'copy:build:cordova']);
gulp.task('build:electron',
['webpack:build:electron', 'views:build:electron', 'copy:build:electron']);
gulp.task('build:extension',
['webpack:build:extension', 'views:build:extension', 'copy:build:extension']);
gulp.task('build:app', ['webpack:build:app', 'views:build:app', 'copy:build:app']);
gulp.task('build:firefox', ['copy:build:firefox']);
gulp.task('test-chrome', ['chrome:test']);
| import gulp from 'gulp';
import requireDir from 'require-dir';
requireDir('./gulp/tasks');
gulp.task('default', ['replace-webpack-code', 'webpack-dev-server', 'views:dev', 'copy:dev', 'views:watch', 'copy:watch']);
gulp.task('build:web', ['webpack:build:web', 'views:build:web', 'copy:build:web']);
gulp.task('build:cordova', ['webpack:build:cordova', 'views:build:cordova', 'copy:build:cordova']);
gulp.task('build:electron',
['webpack:build:electron', 'views:build:electron', 'copy:build:electron']);
gulp.task('build:extension',
['webpack:build:extension', 'views:build:extension', 'copy:build:extension']);
gulp.task('build:app', ['webpack:build:app', 'views:build:app', 'copy:build:app']);
gulp.task('build:firefox', ['copy:build:firefox']);
gulp.task('test-chrome', ['chrome:test']);
|
Change pip name to okpy, since ok is taken | from setuptools import setup, find_packages
setup(
name='okpy',
version='1.0.6',
description=('ok.py supports programming projects by running tests, '
'tracking progress, and assisting in debugging.'),
# long_description=long_description,
url='https://github.com/Cal-CS-61A-Staff/ok',
author='John Denero, Soumya Basu, Stephen Martinis, Sharad Vikram, Albert Wu',
# author_email='',
license='Apache License, Version 2.0',
keywords=['education', 'autograding'],
packages=find_packages('client',
exclude=['*.tests', '*.tests.*',
'*demo_assignments*']),
package_dir={'': 'client'},
# install_requires=[],
entry_points={
'console_scripts': [
'ok=client.__main__:main',
# 'ok-publish=client.publish:main',
],
},
classifiers=[
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
| from setuptools import setup, find_packages
setup(
name='ok',
version='1.0.6',
description=('ok.py supports programming projects by running tests, '
'tracking progress, and assisting in debugging.'),
# long_description=long_description,
url='https://github.com/Cal-CS-61A-Staff/ok',
author='John Denero, Soumya Basu, Stephen Martinis, Sharad Vikram, Albert Wu',
# author_email='',
license='Apache License, Version 2.0',
keywords=['education', 'autograding'],
packages=find_packages('client',
exclude=['*.tests', '*.tests.*',
'*demo_assignments*']),
package_dir={'': 'client'},
# install_requires=[],
entry_points={
'console_scripts': [
'ok=client.__main__:main',
# 'ok-publish=client.publish:main',
],
},
classifiers=[
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
|
Use link as real component | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React, { PropTypes } from 'react';
import styles from './PostPage.css';
import withStyles from '../../decorators/withStyles';
import Link from '../Link';
import marked from 'marked';
@withStyles(styles)
class PostPage {
static propTypes = {
post: PropTypes.object.isRequired
};
static contextTypes = {
onSetTitle: PropTypes.func.isRequired
};
render() {
this.context.onSetTitle(this.props.post.title);
const nextPost = this.props.post.id % 2 + 1;
return (
<div className="PostPage">
<div className="PostPage-container">
<h1>{this.props.post.title}</h1>
<div dangerouslySetInnerHTML={{__html: marked(this.props.post.body)}} />
<a href={nextPost} onClick={Link.handleClick}>post {nextPost}</a>
</div>
</div>
);
}
}
export default PostPage;
| /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React, { PropTypes } from 'react';
import styles from './PostPage.css';
import withStyles from '../../decorators/withStyles';
import Link from '../../utils/Link';
import marked from 'marked';
@withStyles(styles)
class PostPage {
static propTypes = {
post: PropTypes.object.isRequired
};
static contextTypes = {
onSetTitle: PropTypes.func.isRequired
};
render() {
this.context.onSetTitle(this.props.post.title);
const nextPost = this.props.post.id % 2 + 1;
return (
<div className="PostPage">
<div className="PostPage-container">
<h1>{this.props.post.title}</h1>
<div dangerouslySetInnerHTML={{__html: marked(this.props.post.body)}} />
<a href={nextPost} onClick={Link.handleClick}>post {nextPost}</a>
</div>
</div>
);
}
}
export default PostPage;
|
[STORM-1499] Fix Kafka spout to maintain backward compatibility
STORM-1220 introduced some changes where in one place it passes ByteBuffer as is instead of byte[].
Existing bolts (0.10.0) expects a byte[] and fails with
"java.lang.RuntimeException: java.lang.ClassCastException: java.nio.HeapByteBuffer cannot be cast to [B "
This patch addresses the issue by emiting byte[] instead of ByteBuffer. | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package backtype.storm.spout;
import java.nio.ByteBuffer;
import java.util.List;
import backtype.storm.tuple.Fields;
import backtype.storm.utils.Utils;
import static backtype.storm.utils.Utils.tuple;
import static java.util.Arrays.asList;
public class RawMultiScheme implements MultiScheme {
@Override
public Iterable<List<Object>> deserialize(ByteBuffer ser) {
return asList(tuple(Utils.toByteArray(ser)));
}
@Override
public Fields getOutputFields() {
return new Fields("bytes");
}
}
| /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package backtype.storm.spout;
import java.nio.ByteBuffer;
import java.util.List;
import backtype.storm.tuple.Fields;
import static backtype.storm.utils.Utils.tuple;
import static java.util.Arrays.asList;
public class RawMultiScheme implements MultiScheme {
@Override
public Iterable<List<Object>> deserialize(ByteBuffer ser) {
return asList(tuple(ser));
}
@Override
public Fields getOutputFields() {
return new Fields("bytes");
}
}
|
Enable all the browsers, but only one Firefox. | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
define([
'./intern'
], function (intern) {
intern.proxyPort = 9090;
intern.proxyUrl = 'http://localhost:9090/';
intern.useSauceConnect = true;
intern.maxConcurrency = 3;
intern.webdriver = {
host: 'localhost',
port: 4445
};
intern.capabilities = {
'build': '1',
'selenium-version': '2.39.0'
};
intern.environments = [
{ browserName: 'firefox', version: '18' },
{ browserName: 'internet explorer', version: ['9', '10'], platform: [ 'Windows 7' ] },
{ browserName: 'chrome' },
{ browserName: 'safari' }
];
console.log("SAUCE", intern.proxyUrl);
return intern;
});
| /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
define([
'./intern'
], function (intern) {
intern.proxyPort = 9090;
intern.proxyUrl = 'http://localhost:9090/';
intern.useSauceConnect = true;
intern.maxConcurrency = 3;
intern.webdriver = {
host: 'localhost',
port: 4445
};
intern.capabilities = {
'build': '1',
'selenium-version': '2.39.0'
};
intern.environments = [
{ browserName: 'firefox', version: '18' },
/*
{ browserName: 'internet explorer', version: ['9', '10'], platform: [ 'Windows 7' ] },
{ browserName: 'chrome' },
{ browserName: 'safari' }*/
];
console.log("SAUCE", intern.proxyUrl);
return intern;
});
|
Fix logoBig drawing over nav overlay | !function(){var n=document.querySelector.bind(document),t=document.querySelectorAll.bind(document);window.onscroll=function(){(window.pageYOffset||document.documentElement.scrollTop)>(window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight)-n("nav").clientHeight?(n("nav").classList.add("nav-fixed"),t("nav > .logo, nav > .nav-toggle").forEach(function(n){n.style.visibility="visible",n.classList.add("show"),n.classList.remove("hide")})):(n("nav").classList.remove("nav-fixed"),t("nav > .logo, nav > .nav-toggle").forEach(function(n){n.style.visibility="hidden",n.classList.add("hide"),n.classList.remove("show")}))},n(".nav-icon").addEventListener("click",function(){t(".nav-full, main").forEach(function(n){n.classList.toggle("active")}),this.querySelector("img").classList.toggle("img")}),t(".nav-full a").forEach(function(n){n.addEventListener("click",function(){t(".nav-full, main").forEach(function(n){n.classList.toggle("active")})})}),n(".logo").addEventListener("click",function(){n(".nav-full").classList.contains("active")&&t(".nav-full, main").forEach(function(n){n.classList.toggle("active")})}),n("body").addEventListener("click",function(){n(".nav-full").classList.contains("active")?n("html").style.overflowY="hidden":n("html").style.overflowY="scroll"}),t("header").forEach(function(){})}();
| !function(){var n=document.querySelector.bind(document),e=document.querySelectorAll.bind(document);window.onscroll=function(){(window.pageYOffset||document.documentElement.scrollTop)>(window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight)-n("nav").clientHeight?(n("nav").classList.add("nav-fixed"),e("nav > .logo, nav > .nav-toggle").forEach(function(n){n.style.visibility="visible",n.classList.add("show"),n.classList.remove("hide")})):(n("nav").classList.remove("nav-fixed"),e("nav > .logo, nav > .nav-toggle").forEach(function(n){n.style.visibility="hidden",n.classList.add("hide"),n.classList.remove("show")}))},n(".nav-icon").addEventListener("click",function(){e(".nav-full, main").forEach(function(n){n.classList.toggle("active")}),this.querySelector("img").classList.toggle("img")}),e(".nav-full a").forEach(function(n){n.addEventListener("click",function(){e(".nav-full, main").forEach(function(n){n.classList.toggle("active")}),this.querySelector("nav-icon").classList.toggle("nav-icon")})}),n("body").addEventListener("click",function(){n(".nav-full").classList.contains("active")?n("html").style.overflowY="hidden":n("html").style.overflowY="scroll"}),e("header").forEach(function(){})}(); |
Use the new auth keyword set by Ligonier. We're working now. | import unittest
from bluefin.dataretrieval.clients import V1Client
from bluefin.dataretrieval.exceptions import V1ClientInputException, V1ClientProcessingException
from tests.api_details import API_DETAILS, TEST_CARD
class TransactionReportingTest(unittest.TestCase):
"""
Tests for transaction reporting API calls.
"""
def test_basic(self):
"""
Test a basic successful API call.
"""
api = V1Client()
result = api.send_request({
'transactions_after': '2006-12-30',
'account_id': API_DETAILS['account_id'],
'authorization': 'LIGONIER_DOT_ORG',
})
print result
def test_no_input(self):
api = V1Client()
self.assertRaises(V1ClientInputException, api.send_request, {})
| import unittest
from bluefin.dataretrieval.clients import V1Client
from bluefin.dataretrieval.exceptions import V1ClientInputException, V1ClientProcessingException
from tests.api_details import API_DETAILS, TEST_CARD
class TransactionReportingTest(unittest.TestCase):
"""
Tests for transaction reporting API calls.
"""
def test_basic(self):
"""
Test a basic successful API call.
"""
api = V1Client()
api.send_request({
'transactions_after': '2006-12-30',
'account_id': API_DETAILS['account_id'],
'authorization': 'qRdNQK0lkc7vwHP2h6mm',
})
def test_no_input(self):
api = V1Client()
self.assertRaises(V1ClientInputException, api.send_request, {})
|
Setup.py: Use zip_safe = false to make sure that python module is extracted and later the settingsFile can be changed | #!/usr/bin/env python3
from setuptools import setup, find_packages
install_requires = (
'html2text',
'matterhook',
'exchangelib',
)
setup(name='calendarBot',
version='0.1.1',
description='Mattermost calendar Bot',
long_description=open('README.md').read(),
url='https://github.com/mharrend',
author='Marco A. Harrendorf',
author_email='marco.harrendorf@cern.ch',
license='MIT',
keywords='chat bot calendar mattermost',
platforms=['Any'],
zip_safe = False,
packages = find_packages(),
install_requires=install_requires,
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
| #!/usr/bin/env python3
from setuptools import setup, find_packages
install_requires = (
'html2text',
'matterhook',
'exchangelib',
)
setup(name='calendarBot',
version='0.1',
description='Mattermost calendar Bot',
long_description=open('README.md').read(),
url='https://github.com/mharrend',
author='Marco A. Harrendorf',
author_email='marco.harrendorf@cern.ch',
license='MIT',
keywords='chat bot calendar mattermost',
platforms=['Any'],
packages = find_packages(),
install_requires=install_requires,
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
|
Update to use session storage | import React from 'react';
import { IntlProvider } from 'react-intl';
import { persistStore, autoRehydrate } from 'redux-persist';
import { asyncSessionStorage } from "redux-persist/storages"
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducer from '../reducers';
var createElement = React.createClass({
propTypes: {
locale: React.PropTypes.string.isRequired,
messages: React.PropTypes.object.isRequired
},
render: function() {
const store = createStore(reducer, {
donateForm: {
currency: this.props.currency,
frequency: this.props.frequency,
presets: this.props.presets,
amount: this.props.amount
}
}, autoRehydrate());
persistStore(store, {
storage: asyncSessionStorage
});
return (
<Provider store={store}>
<IntlProvider locale={this.props.locale} messages={this.props.messages}>
{this.props.children}
</IntlProvider>
</Provider>
);
}
});
module.exports = createElement;
| import React from 'react';
import { IntlProvider } from 'react-intl';
import { persistStore, autoRehydrate } from 'redux-persist';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducer from '../reducers';
var createElement = React.createClass({
propTypes: {
locale: React.PropTypes.string.isRequired,
messages: React.PropTypes.object.isRequired
},
render: function() {
const store = createStore(reducer, {
donateForm: {
currency: this.props.currency,
frequency: this.props.frequency,
presets: this.props.presets,
amount: this.props.amount
}
}, autoRehydrate());
persistStore(store);
return (
<Provider store={store}>
<IntlProvider locale={this.props.locale} messages={this.props.messages}>
{this.props.children}
</IntlProvider>
</Provider>
);
}
});
module.exports = createElement;
|
Add description to hash function | package login;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.xml.bind.DatatypeConverter;
public class PasswordHelper
{
private static String hashAlgorithm = "MD5";
private static String stringEncodingFormat = "UTF-8";
/**Returns the hash for a given password string, in hex string format*/
public static String generatePasswordHash(String password)
{
//Create instances of digest and password char array
MessageDigest passDigest;
byte[] passArray;
try
{
//Create instance of MessageDigest we can use to
passDigest = MessageDigest.getInstance(hashAlgorithm);
//Convert password to byte array
passArray = password.getBytes(stringEncodingFormat);
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
return "";
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
return "";
}
//Use digest to get hash as an array of chars and return it as a hex string
byte[] hashArray = passDigest.digest(passArray);
return DatatypeConverter.printHexBinary(hashArray);
}
}
| package login;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.xml.bind.DatatypeConverter;
public class PasswordHelper
{
private static String hashAlgorithm = "MD5";
private static String stringEncodingFormat = "UTF-8";
public static String generatePasswordHash(String password)
{
//Create instances of digest and password char array
MessageDigest passDigest;
byte[] passArray;
try
{
//Create instance of MessageDigest we can use to
passDigest = MessageDigest.getInstance(hashAlgorithm);
//Convert password to byte array
passArray = password.getBytes(stringEncodingFormat);
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
return "";
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
return "";
}
//Use digest to get hash as an array of chars and return it as a hex string
byte[] hashArray = passDigest.digest(passArray);
return DatatypeConverter.printHexBinary(hashArray);
}
}
|
Fix typo in server form. | import bridge from '../common/bridge';
import React from 'react';
export default class ServerForm extends React.Component {
render() {
return (
<form onSubmit={this.connect.bind(this)}>
<p>server: <input type='text' name='server' defaultValue='irc.freenode.net' /></p>
<p>port: <input type='text' name='port' defaultValue='6667' /></p>
<p>encoding: <input type='text' name='encoding' defaultValue='UTF-8' /></p>
<p>nickname: <input type='text' name='nick' defaultValue='noraesae' /></p>
<p>user name: <input type='text' name='username' defaultValue='noraesae' /></p>
<p>real name: <input type='text' name='realname' defaultValue='noraesae' /></p>
<p><button>connect</button></p>
</form>
);
}
formToJSON() {
let form = React.findDOMNode(this);
let inputs = form.querySelectorAll('input[type="text"]');
return Array.prototype.reduce.call(inputs, function (obj, input) {
obj[input.name] = input.value;
return obj;
}, {});
}
connect(e) {
e.preventDefault();
let data = this.formToJSON();
this.props.connect(data);
bridge.send('connect', data);
}
}
| import bridge from '../common/bridge';
import React from 'react';
export default class ServerForm extends React.Component {
render() {
return (
<form onSubmit={this.connect.bind(this)}>
<p>server: <input type='text' name='server' defaultValue='irc.freenode.net' /></p>
<p>port: <input type='text' name='port' defaultValue='6667' /></p>
<p>encoding: <input type='text' name='encoding' defaultValue='UTF-8' /></p>
<p>nickname: <input type='text' name='nick' defaultValue='noraesae' /></p>
<p>login name: <input type='text' name='loginName' defaultValue='noraesae' /></p>
<p>real name: <input type='text' name='realName' defaultValue='noraesae' /></p>
<p><button>connect</button></p>
</form>
);
}
formToJSON() {
let form = React.findDOMNode(this);
let inputs = form.querySelectorAll('input[type="text"]');
return Array.prototype.reduce.call(inputs, function (obj, input) {
obj[input.name] = input.value;
return obj;
}, {});
}
connect(e) {
e.preventDefault();
let data = this.formToJSON();
this.props.connect(data);
bridge.send('connect', data);
}
}
|
Fix lp:1302500 by evaluating an empty context to avoid error | openerp.web_context_tunnel = function(instance) {
instance.web.form.FormWidget.prototype.build_context = function() {
var v_context = false;
var fields_values = false;
// instead of using just the attr context, we merge any attr starting with context
for (var key in this.node.attrs) {
if (key.substring(0, 7) === "context") {
if (!v_context) {
fields_values = this.field_manager.build_eval_context();
v_context = new instance.web.CompoundContext(this.node.attrs[key]).set_eval_context(fields_values);
} else {
v_context = new instance.web.CompoundContext(this.node.attrs[key], v_context).set_eval_context(fields_values);
}
}
}
if (!v_context) {
v_context = (this.field || {}).context || {};
v_context = new instance.web.CompoundContext(v_context);
}
return v_context;
};
};
// vim:et fdc=0 fdl=0:
| openerp.web_context_tunnel = function(instance) {
instance.web.form.FormWidget.prototype.build_context = function() {
var v_context = false;
var fields_values = false;
// instead of using just the attr context, we merge any attr starting with context
for (var key in this.node.attrs) {
if (key.substring(0, 7) === "context") {
if (!v_context) {
fields_values = this.field_manager.build_eval_context();
v_context = new instance.web.CompoundContext(this.node.attrs[key]).set_eval_context(fields_values);
} else {
v_context = new instance.web.CompoundContext(this.node.attrs[key], v_context).set_eval_context(fields_values);
}
}
}
if (!v_context) {
v_context = (this.field || {}).context || {};
}
return v_context;
};
};
// vim:et fdc=0 fdl=0:
|
Remove check if int in setId
Led to id not being set from HTML forms. Will leave without checking ID for now. | <?php
class LogsheetComponent {
protected $db;
protected $id;
public function __construct($db, $component_id) {
$this->db = $db;
$this->setId($component_id);
}
public function setId($component_id) {
$this->id = $component_id;
}
public function getId() {
return $this->id;
}
//Make sure an Id has been set for an Object
protected function checkForId() {
if(!empty($this->id)) {
$result = TRUE;
} else {
throw new Exception("Error: No ID assigned to object");
}
return $result;
}
}
?> | <?php
class LogsheetComponent {
protected $db;
protected $id;
public function __construct($db, $component_id) {
$this->db = $db;
$this->setId($component_id);
}
public function setId($component_id) {
if (is_int($component_id)) {
$this->id = $component_id;
}
}
public function getId() {
return $this->id;
}
//Make sure an Id has been set for an Object
protected function checkForId() {
if(!empty($this->id)) {
$result = TRUE;
} else {
throw new Exception("Error: No ID assigned to object");
}
return $result;
}
}
?> |
Fix error when empty string | $(document).ready(function() {
$("#search-lots").autocomplete({
minLength: 2,
source: "/lots/search-ajax/",
focus: function( event, ui ) {
$("#search-lots").val( ui.item.name );
return false;
},
select: function( event, ui ) {
window.location.href = "/revenue/receipt/add/" + ui.item.name;
return false;
}
}).autocomplete("instance")._renderItem = function(ul, item) {
return $( "<li>" )
.append( "<div>" + item.name + " <small>" + item.address + "</small><br>" + item.owner__name + "</div>" )
.appendTo( ul );
};
});
function parse_decimal(str) {
return str !== '' ? new BigNumber(str.replace(/[^0-9\.]+/g,"")) : new BigNumber('0.00');
}
| $(document).ready(function() {
$("#search-lots").autocomplete({
minLength: 2,
source: "/lots/search-ajax/",
focus: function( event, ui ) {
$("#search-lots").val( ui.item.name );
return false;
},
select: function( event, ui ) {
window.location.href = "/revenue/receipt/add/" + ui.item.name;
return false;
}
}).autocomplete("instance")._renderItem = function(ul, item) {
return $( "<li>" )
.append( "<div>" + item.name + " <small>" + item.address + "</small><br>" + item.owner__name + "</div>" )
.appendTo( ul );
};
});
function parse_decimal(str) {
return new BigNumber(str.replace(/[^0-9\.]+/g,""))
}
|
Return to page fixed on block deletion | <?php
/**
* Block delete handler.
*/
$this->require_acl ('admin', 'admin/delete', 'blocks');
$page->layout = 'admin';
if (! isset ($_POST['id'])) {
$this->redirect ('/blocks/admin');
}
$lock = new Lock ('Block', $_POST['id']);
if ($lock->exists ()) {
$page->title = __ ('Editing Locked');
echo $tpl->render ('admin/locked', $lock->info ());
return;
}
$b = new Block ($_POST['id']);
$_POST = array_merge ($_POST, (array) $b->orig ());
if (! $b->remove ()) {
$page->title = __ ('An Error Occurred');
echo __ ('Error Message') . ': ' . $b->error;
return;
}
$this->hook ('blocks/delete', $_POST);
$this->add_notification (__ ('Block deleted.'));
if (isset ($_POST['return'])) {
$_POST['return'] = filter_var ($_POST['return'], FILTER_SANITIZE_URL);
if (Validator::validate ($_POST['return'], 'localpath')) {
$this->redirect ($_POST['return']);
}
$this->redirect ('/blocks/admin');
}
| <?php
/**
* Block delete handler.
*/
$this->require_acl ('admin', 'admin/delete', 'blocks');
$page->layout = 'admin';
if (! isset ($_POST['id'])) {
$this->redirect ('/blocks/admin');
}
$lock = new Lock ('Block', $_POST['id']);
if ($lock->exists ()) {
$page->title = __ ('Editing Locked');
echo $tpl->render ('admin/locked', $lock->info ());
return;
}
$b = new Block ($_POST['id']);
$_POST = array_merge ($_POST, (array) $b->orig ());
if (! $b->remove ()) {
$page->title = __ ('An Error Occurred');
echo __ ('Error Message') . ': ' . $b->error;
return;
}
$this->hook ('blocks/delete', $_POST);
$this->add_notification (__ ('Block deleted.'));
if (isset ($_POST['return'])) {
$_POST['return'] = filter_var ($_POST['return'], FILTER_SANITIZE_URL);
if (Validator::validate ($_POST['return'], 'localpath')) {
$_POST['return'] = $_POST['return'];
}
$this->redirect ('/blocks/admin');
}
|
Stop patcher in tear down
- itacloud-7198 | import mock
from rest_framework import test
class MockedSession(mock.MagicMock):
auth_ref = 'AUTH_REF'
class BaseBackendTestCase(test.APITransactionTestCase):
def setUp(self):
self.session_patcher = mock.patch('keystoneauth1.session.Session', MockedSession)
self.session_patcher.start()
self.session_recover_patcher = mock.patch('nodeconductor_openstack.backend.OpenStackSession.recover')
self.session_recover_patcher.start()
self.keystone_patcher = mock.patch('keystoneclient.v2_0.client.Client')
self.mocked_keystone = self.keystone_patcher.start()
self.nova_patcher = mock.patch('novaclient.v2.client.Client')
self.mocked_nova = self.nova_patcher.start()
self.cinder_patcher = mock.patch('cinderclient.v1.client.Client')
self.mocked_cinder = self.cinder_patcher.start()
def tearDown(self):
super(BaseBackendTestCase, self).tearDown()
self.session_patcher.stop()
self.session_recover_patcher.stop()
self.keystone_patcher.stop()
self.nova_patcher.stop()
self.cinder_patcher.stop()
| import mock
from rest_framework import test
class MockedSession(mock.MagicMock):
auth_ref = 'AUTH_REF'
class BaseBackendTestCase(test.APITransactionTestCase):
def setUp(self):
self.session_patcher = mock.patch('keystoneauth1.session.Session', MockedSession)
self.session_patcher.start()
self.session_recover_patcher = mock.patch('nodeconductor_openstack.backend.OpenStackSession.recover')
self.session_recover_patcher.start()
self.keystone_patcher = mock.patch('keystoneclient.v2_0.client.Client')
self.mocked_keystone = self.keystone_patcher.start()
self.nova_patcher = mock.patch('novaclient.v2.client.Client')
self.mocked_nova = self.nova_patcher.start()
self.cinder_patcher = mock.patch('cinderclient.v1.client.Client')
self.mocked_cinder = self.cinder_patcher.start()
def tearDown(self):
super(BaseBackendTestCase, self).tearDown()
self.session_patcher.stop()
self.keystone_patcher.stop()
self.nova_patcher.stop()
self.cinder_patcher.stop()
|
Add Content-Type handling for charset | 'use strict';
const { parse: parseContentType } = require('content-type');
const { findFormat } = require('../../../formats');
const { parsePreferHeader } = require('./headers');
// Using `Prefer: return=minimal` request header results in `args.silent` true.
const silent = function ({ specific: { req: { headers: requestheaders } } }) {
const preferHeader = parsePreferHeader({ requestheaders });
const hasMinimalPreference = preferHeader.return === 'minimal';
if (hasMinimalPreference) { return true; }
};
// Using `Content-Type` or `Accept-Encoding` results in `args.format`
// Note that since `args.format` is for both input and output, any of the
// two headers can be used. `Content-Type` has priority.
const format = function ({ specific }) {
const { type: contentType } = getContentType({ specific });
const { name } = findFormat({ type: 'payload', mime: contentType });
return name;
};
const getContentType = function ({ specific: { req: { headers } } }) {
const contentType = headers['content-type'];
if (!contentType) { return; }
return parseContentType(contentType);
};
// Use similar logic as `args.format`, but for `args.charset`
const charset = function ({ specific }) {
const { parameters: { charset: name } } = getContentType({ specific });
return name;
};
// HTTP-specific ways to set arguments
const args = {
silent,
format,
charset,
};
module.exports = {
args,
};
| 'use strict';
const { parse: parseContentType } = require('content-type');
const { findFormat } = require('../../../formats');
const { parsePreferHeader } = require('./headers');
// Using `Prefer: return=minimal` request header results in `args.silent` true.
const silent = function ({ specific: { req: { headers: requestheaders } } }) {
const preferHeader = parsePreferHeader({ requestheaders });
const hasMinimalPreference = preferHeader.return === 'minimal';
if (hasMinimalPreference) { return true; }
};
// Using `Content-Type` or `Accept-Encoding` results in `args.format`
// Note that since `args.format` is for both input and output, any of the
// two headers can be used. `Content-Type` has priority.
const format = function ({ specific }) {
const contentType = getContentType({ specific });
const { name } = findFormat({ type: 'payload', mime: contentType });
return name;
};
const getContentType = function ({ specific: { req: { headers } } }) {
const contentType = headers['content-type'];
if (!contentType) { return; }
const { type } = parseContentType(contentType);
return type;
};
// HTTP-specific ways to set arguments
const args = {
silent,
format,
};
module.exports = {
args,
};
|
Use clearer function name in is_lychrel | """
problem55.py
If we take 47, reverse and add, 47 + 74 = 121, which is palindromic. A number
that never forms a palindrome through the reverse and add process is called a
Lychrel number. How many Lychrel numbers are there below ten-thousand? (Only
consider fifty iterations)
"""
from toolset import iterate, quantify, take
def to_digits(num):
# to_digits(1234) --> [1, 2, 3, 4]
return list(map(int, str(num)))
def to_num(digits):
# to_num([1, 2, 3, 4]) --> 1234
return int(''.join(map(str, digits)))
def is_palindromic(num):
return to_digits(num) == list(reversed(to_digits(num)))
def is_lychrel(num):
rev = lambda x: to_num(reversed(to_digits(x)))
start = num + rev(num)
iterations = iterate(lambda x: x + rev(x), start)
return not any(is_palindromic(n) for n in take(50, iterations))
def problem55():
return quantify(range(1, 10000), pred=is_lychrel)
| """
problem55.py
If we take 47, reverse and add, 47 + 74 = 121, which is palindromic. A number
that never forms a palindrome through the reverse and add process is called a
Lychrel number. How many Lychrel numbers are there below ten-thousand? (Only
consider fifty iterations)
"""
from toolset import iterate, quantify, take
def to_digits(num):
# to_digits(1234) --> [1, 2, 3, 4]
return list(map(int, str(num)))
def to_num(digits):
# to_num([1, 2, 3, 4]) --> 1234
return int(''.join(map(str, digits)))
def is_palindromic(num):
return to_digits(num) == list(reversed(to_digits(num)))
def is_lychrel(num):
rev = lambda x: to_num(to_digits(x)[::-1])
start = num + rev(num)
iterations = iterate(lambda x: x + rev(x), start)
return not any(is_palindromic(n) for n in take(50, iterations))
def problem55():
return quantify(range(1, 10000), pred=is_lychrel)
|
Use f-string when calling method inside string | import os.path
from tempfile import gettempdir
from urllib.request import urlretrieve
from zipfile import ZipFile
from .reimbursements_cleaner import ReimbursementsCleaner
URL = 'https://www.camara.leg.br/cotas/Ano-{}.csv.zip'
def extract_zip(zip_path, destination_path):
zip_file = ZipFile(zip_path, 'r')
zip_file.extractall(destination_path)
zip_file.close()
class Reimbursements:
"""
Get an updated version of the reimbursements dataset for a given year.
"""
def __init__(self, year, path=None):
self.year = year
self.path = path or gettempdir()
def __call__(self):
self.fetch()
self.clean()
file_path = os.path.join(self.path, f'reimbursements-{self.year}.csv')
return file_path
def fetch(self):
file_path = os.path.join(self.path, f'Ano-{self.year}.zip')
urlretrieve(URL.format(self.year), file_path)
extract_zip(file_path, self.path)
def clean(self):
ReimbursementsCleaner(self.year, self.path)()
| import os.path
from tempfile import gettempdir
from urllib.request import urlretrieve
from zipfile import ZipFile
from .reimbursements_cleaner import ReimbursementsCleaner
URL = 'https://www.camara.leg.br/cotas/Ano-{}.csv.zip'
def extract_zip(zip_path, destination_path):
zip_file = ZipFile(zip_path, 'r')
zip_file.extractall(destination_path)
zip_file.close()
class Reimbursements:
"""
Get an updated version of the reimbursements dataset for a given year.
"""
def __init__(self, year, path=None):
self.year = year
self.path = path or gettempdir()
def __call__(self):
self.fetch()
self.clean()
file_path = os.path.join(self.path, f'reimbursements-{self.year}.csv')
return file_path
def fetch(self):
file_path = os.path.join(self.path, 'Ano-{self.year}.zip')
urlretrieve(URL.format(self.year), file_path)
extract_zip(file_path, self.path)
def clean(self):
ReimbursementsCleaner(self.year, self.path)()
|
Fix shulker box inventory remap. | package protocolsupport.protocol.typeremapper.basic;
import protocolsupport.protocol.typeremapper.utils.RemappingRegistry.EnumRemappingRegistry;
import protocolsupport.protocol.typeremapper.utils.RemappingTable.EnumRemappingTable;
import protocolsupport.protocol.types.WindowType;
import protocolsupport.protocol.utils.ProtocolVersionsHelper;
import protocolsupportbuildprocessor.Preload;
@Preload
public class GenericIdRemapper {
public static final EnumRemappingRegistry<WindowType, EnumRemappingTable<WindowType>> INVENTORY = new EnumRemappingRegistry<WindowType, EnumRemappingTable<WindowType>>() {
{
registerRemapEntry(WindowType.BLAST_FURNACE, WindowType.FURNACE, ProtocolVersionsHelper.BEFORE_1_14);
registerRemapEntry(WindowType.SMOKER, WindowType.FURNACE, ProtocolVersionsHelper.BEFORE_1_14);
registerRemapEntry(WindowType.SHULKER_BOX, WindowType.GENERIC_9X3, ProtocolVersionsHelper.BEFORE_1_11);
}
@Override
protected EnumRemappingTable<WindowType> createTable() {
return new EnumRemappingTable<>(WindowType.class);
}
};
}
| package protocolsupport.protocol.typeremapper.basic;
import protocolsupport.protocol.typeremapper.utils.RemappingRegistry.EnumRemappingRegistry;
import protocolsupport.protocol.typeremapper.utils.RemappingTable.EnumRemappingTable;
import protocolsupport.protocol.types.WindowType;
import protocolsupport.protocol.utils.ProtocolVersionsHelper;
import protocolsupportbuildprocessor.Preload;
@Preload
public class GenericIdRemapper {
public static final EnumRemappingRegistry<WindowType, EnumRemappingTable<WindowType>> INVENTORY = new EnumRemappingRegistry<WindowType, EnumRemappingTable<WindowType>>() {
{
registerRemapEntry(WindowType.BLAST_FURNACE, WindowType.FURNACE, ProtocolVersionsHelper.BEFORE_1_14);
registerRemapEntry(WindowType.SMOKER, WindowType.FURNACE, ProtocolVersionsHelper.BEFORE_1_14);
registerRemapEntry(WindowType.SHULKER_BOX, WindowType.GENERIC_9X4, ProtocolVersionsHelper.BEFORE_1_11);
}
@Override
protected EnumRemappingTable<WindowType> createTable() {
return new EnumRemappingTable<>(WindowType.class);
}
};
}
|
Add test for animation file. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
from arc_test import ArcTest
from incar_test import InCarTest
from oszicar_test import OsziCarTest
from outcar_test import OutCarTest
from xsd_test import XsdTest
from xtd_test import XtdTest
from poscar_test import PosCarTest
from xyzfile_test import XyzFileTest
from cif_test import CifFileTest
from ani_test import AniFileTest
def suite():
suite = unittest.TestSuite([
unittest.TestLoader().loadTestsFromTestCase(ArcTest),
unittest.TestLoader().loadTestsFromTestCase(InCarTest),
unittest.TestLoader().loadTestsFromTestCase(OsziCarTest),
unittest.TestLoader().loadTestsFromTestCase(OutCarTest),
unittest.TestLoader().loadTestsFromTestCase(XsdTest),
unittest.TestLoader().loadTestsFromTestCase(XtdTest),
unittest.TestLoader().loadTestsFromTestCase(PosCarTest),
unittest.TestLoader().loadTestsFromTestCase(XyzFileTest),
unittest.TestLoader().loadTestsFromTestCase(CifFileTest),
unittest.TestLoader().loadTestsFromTestCase(AniFileTest),
])
return suite
if "__main__" == __name__:
result = unittest.TextTestRunner(verbosity=2).run(suite())
if result.errors or result.failures:
raise ValueError("Get errors and failures.")
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
from arc_test import ArcTest
from incar_test import InCarTest
from oszicar_test import OsziCarTest
from outcar_test import OutCarTest
from xsd_test import XsdTest
from xtd_test import XtdTest
from poscar_test import PosCarTest
from xyzfile_test import XyzFileTest
from cif_test import CifFileTest
def suite():
suite = unittest.TestSuite([
unittest.TestLoader().loadTestsFromTestCase(ArcTest),
unittest.TestLoader().loadTestsFromTestCase(InCarTest),
unittest.TestLoader().loadTestsFromTestCase(OsziCarTest),
unittest.TestLoader().loadTestsFromTestCase(OutCarTest),
unittest.TestLoader().loadTestsFromTestCase(XsdTest),
unittest.TestLoader().loadTestsFromTestCase(XtdTest),
unittest.TestLoader().loadTestsFromTestCase(PosCarTest),
unittest.TestLoader().loadTestsFromTestCase(XyzFileTest),
unittest.TestLoader().loadTestsFromTestCase(CifFileTest),
])
return suite
if "__main__" == __name__:
result = unittest.TextTestRunner(verbosity=2).run(suite())
if result.errors or result.failures:
raise ValueError("Get errors and failures.")
|
Add shadow to non-feature project container | import React from 'react'
import { Project } from './Project'
const Projects = ({ projects = [], feature }) => {
if (!projects.length) return null
const featuredProjects = projects.filter((project) => project.feature)
const nonFeaturedProjects = projects.filter((project) => !project.feature)
return (
<>
{feature ? (
<ul className="divide-y divide-gray-200">
{featuredProjects.map((project) => (
<li key={project.id} className="flex py-12 space-x-6">
<Project project={project} />
</li>
))}
</ul>
) : (
<ul className="grid grid-cols-1 sm:grid-cols-2 gap-4 mt-12">
{nonFeaturedProjects.map((project) => (
<li key={project.id} className="p-4 border rounded-lg shadow-md">
<Project project={{ ...project, image: undefined }} />
</li>
))}
</ul>
)}
</>
)
}
export { Projects }
| import React from 'react'
import { Project } from './Project'
const Projects = ({ projects = [], feature }) => {
if (!projects.length) return null
const featuredProjects = projects.filter((project) => project.feature)
const nonFeaturedProjects = projects.filter((project) => !project.feature)
return (
<>
{feature ? (
<ul className="divide-y divide-gray-200">
{featuredProjects.map((project) => (
<li key={project.id} className="flex py-12 space-x-6">
<Project project={project} />
</li>
))}
</ul>
) : (
<ul className="grid grid-cols-1 sm:grid-cols-2 gap-4 mt-12">
{nonFeaturedProjects.map((project) => (
<li key={project.id} className="p-4 border rounded-sm">
<Project project={{ ...project, image: undefined }} />
</li>
))}
</ul>
)}
</>
)
}
export { Projects }
|
Allow staff access to Publisher APIs
A few Publisher APIs were marked as only allowing publisher users.
We should also let staff in.
DISCO-1365 | from rest_framework.permissions import BasePermission
from course_discovery.apps.publisher.mixins import check_course_organization_permission, check_roles_access
from course_discovery.apps.publisher.models import OrganizationExtension
from course_discovery.apps.publisher.utils import is_internal_user, is_publisher_user
class CanViewAssociatedCourse(BasePermission):
""" Permission class to check user can view a publisher course or also if
user has view permission on organization.
"""
def has_object_permission(self, request, view, obj):
user = request.user
return (
check_roles_access(user) or
check_course_organization_permission(user, obj.course, OrganizationExtension.VIEW_COURSE)
)
class InternalUserPermission(BasePermission):
""" Permission class to check user is an internal user. """
def has_object_permission(self, request, view, obj):
return request.user.is_staff or is_internal_user(request.user)
class PublisherUserPermission(BasePermission):
""" Permission class to check user is a publisher user. """
def has_object_permission(self, request, view, obj):
return request.user.is_staff or is_publisher_user(request.user)
def has_permission(self, request, view):
return request.user.is_staff or is_publisher_user(request.user)
| from rest_framework.permissions import BasePermission
from course_discovery.apps.publisher.mixins import check_course_organization_permission, check_roles_access
from course_discovery.apps.publisher.models import OrganizationExtension
from course_discovery.apps.publisher.utils import is_internal_user, is_publisher_user
class CanViewAssociatedCourse(BasePermission):
""" Permission class to check user can view a publisher course or also if
user has view permission on organization.
"""
def has_object_permission(self, request, view, obj):
user = request.user
return (
check_roles_access(user) or
check_course_organization_permission(user, obj.course, OrganizationExtension.VIEW_COURSE)
)
class InternalUserPermission(BasePermission):
""" Permission class to check user is an internal user. """
def has_object_permission(self, request, view, obj):
return is_internal_user(request.user)
class PublisherUserPermission(BasePermission):
""" Permission class to check user is a publisher user. """
def has_object_permission(self, request, view, obj):
return is_publisher_user(request.user)
def has_permission(self, request, view):
return is_publisher_user(request.user)
|
Include the_content in teaser template. | <?php
/**
* Template Name: Teasers
*/
?>
<h1 class="media-zen">
<?php echo get_bloginfo ( 'description' ); ?>
</h1>
<div class="row-fluid">
<?php while (have_posts()) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; ?>
</div>
<div class="home_container">
<?php
// The Query
$teaser_query = new WP_Query( 'post_type=teasers' );
?>
<?php while ($teaser_query->have_posts()) : $teaser_query->the_post(); ?>
<div id="bp_foundation" class="container-fluid bp_foundation current">
<div class="row-fluid heading_stripe">
<?php the_title( '<h2>', '</h2>' ); ?>
</div>
<p><?php get_template_part('templates/content', 'page'); ?></p>
<a name="next" class="btn round pink pull-right" href="#">See how it works >></a>
</div>
<?php endwhile; ?>
<?php
/* Restore original Post Data */
wp_reset_postdata();
?>
</div>
| <?php
/**
* Template Name: Teasers
*/
?>
<h1 class="media-zen">
<?php echo get_bloginfo ( 'description' ); ?>
</h1>
<div class="home_container">
<?php
// The Query
$teaser_query = new WP_Query( 'post_type=teasers' );
?>
<?php while ($teaser_query->have_posts()) : $teaser_query->the_post(); ?>
<div id="bp_foundation" class="container-fluid bp_foundation current">
<div class="row-fluid heading_stripe">
<?php the_title( '<h2>', '</h2>' ); ?>
</div>
<p><?php get_template_part('templates/content', 'page'); ?></p>
<a name="next" class="btn round pink pull-right" href="#">See how it works >></a>
</div>
<?php endwhile; ?>
<?php
/* Restore original Post Data */
wp_reset_postdata();
?>
</div>
|
Copy enumeration literals when pasting an Enumeration
Signed-off-by: Dan Yeaw <2591e5f46f28d303f9dc027d475a5c60d8dea17a@yeaw.me> | import itertools
from gaphor.diagram.copypaste import copy, copy_named_element
from gaphor.UML import Association, Class, Enumeration, Interface, Operation
@copy.register(Class)
@copy.register(Interface)
def copy_class(element):
yield element.id, copy_named_element(element)
for feature in itertools.chain(
element.ownedAttribute,
element.ownedOperation,
):
yield from copy(feature)
@copy.register
def copy_enumeration(element: Enumeration):
yield element.id, copy_named_element(element)
for literal in element.ownedLiteral:
yield from copy(literal)
@copy.register
def copy_operation(element: Operation):
yield element.id, copy_named_element(element)
for feature in element.ownedParameter:
yield from copy(feature)
@copy.register
def copy_association(element: Association):
yield element.id, copy_named_element(element)
for end in element.memberEnd:
yield from copy(end)
| import itertools
from gaphor.diagram.copypaste import copy, copy_named_element
from gaphor.UML import Association, Class, Interface, Operation
@copy.register(Class)
@copy.register(Interface)
def copy_class(element):
yield element.id, copy_named_element(element)
for feature in itertools.chain(
element.ownedAttribute,
element.ownedOperation,
):
yield from copy(feature)
@copy.register
def copy_operation(element: Operation):
yield element.id, copy_named_element(element)
for feature in element.ownedParameter:
yield from copy(feature)
@copy.register
def copy_association(element: Association):
yield element.id, copy_named_element(element)
for end in element.memberEnd:
yield from copy(end)
|
Add a test for json retrieval. | import unittest
from flask import Flask
from flask.ext.autodoc import Autodoc
class TestAutodocWithFlask(unittest.TestCase):
def setUp(self):
self.app = Flask(__name__)
self.autodoc = Autodoc(self.app)
@self.app.route('/')
@self.autodoc.doc()
def index():
"""Returns a hello world message"""
return 'Hello World!'
self.client = self.app.test_client()
def test_html(self):
@self.app.route('/docs')
def html_docs():
return self.autodoc.html()
response = self.client.get('/docs')
self.assertEqual(response.status_code, 200)
def test_json(self):
@self.app.route('/docs')
def json_docs():
return self.autodoc.json()
response = self.client.get('/docs')
self.assertEqual(response.status_code, 200)
| import unittest
from flask import Flask
from flask.ext.autodoc import Autodoc
class TestAutodocWithFlask(unittest.TestCase):
def setUp(self):
self.app = Flask(__name__)
self.autodoc = Autodoc(self.app)
@self.app.route('/')
@self.autodoc.doc()
def index():
"""Returns a hello world message"""
return 'Hello World!'
self.client = self.app.test_client()
def test_html(self):
@self.app.route('/docs')
def html_docs():
return self.autodoc.html()
response = self.client.get('/docs')
self.assertEqual(response.status_code, 200)
|
Check for clone options before continuing. | // ==UserScript==
// @name GitHubSourceTree
// @namespace http://really-serious.biz/
// @version 1.0.1
// @description Adds a "Clone in SourceTree" button to github pages
// @respository https://github.com/jamesgarfield/GitHubSourceTree
// @match https://*github.com/*
// @copyright 2014+, James Garfield
// ==/UserScript==
(function(){
const $ = document.querySelectorAll.bind(document);
const gitHubNode = $(".clone-options + a")[0]
if (!gitHubNode) {
return;
}
const parentNode = gitHubNode.parentNode;
const insertBeforeNode = gitHubNode.nextSibling;
const gitURL = $(".clone-url-box .js-url-field")[0].value
var sourceTreeNode = gitHubNode.cloneNode();
sourceTreeNode.href = 'sourcetree://cloneRepo/' + gitURL;
sourceTreeNode.innerHTML = '<span class="octicon octicon-device-desktop"></span>Clone in SourceTree';
parentNode.insertBefore(sourceTreeNode, insertBeforeNode);
})()
| // ==UserScript==
// @name GitHubSourceTree
// @namespace http://really-serious.biz/
// @version 1.0
// @description Adds a "Clone in SourceTree" button to github pages
// @respository https://github.com/jamesgarfield/GitHubSourceTree
// @match https://*github.com/*
// @copyright 2014+, James Garfield
// ==/UserScript==
(function(){
const $ = document.querySelectorAll.bind(document);
const gitHubNode = $(".clone-options + a")[0]
const parentNode = gitHubNode.parentNode;
const insertBeforeNode = gitHubNode.nextSibling;
const gitURL = $(".clone-url-box .js-url-field")[0].value
var sourceTreeNode = gitHubNode.cloneNode();
sourceTreeNode.href = 'sourcetree://cloneRepo/' + gitURL;
sourceTreeNode.innerHTML = '<span class="octicon octicon-device-desktop"></span>Clone in SourceTree';
parentNode.insertBefore(sourceTreeNode, insertBeforeNode);
})()
|
[fix] Fix a typo in an import | import { expect } from 'chai'
import { h, render, rerender } from 'preact'
import App from '../app/components/App'
// describe('App', () => {
// let scratch
// before( () => {
// scratch = document.createElement('div');
// (document.body || document.documentElement).appendChild(scratch)
// })
// beforeEach( () => {
// scratch.innerHTML = ''
// })
// after( () => {
// scratch.parentNode.removeChild(scratch)
// scratch = null
// })
// describe('routing', () => {
// it('should render the discovery page', () => {
// render(<App konnectors={[]}/>, scratch)
// route('/')
// expect(scratch.querySelector('main').innerHTML).to.contain('Discovery')
// })
// it('should render /category', () => {
// render(<App konnectors={[]}/>, scratch)
// route('/category')
// //rerender()
// expect(scratch.querySelector('main').innerHTML).to.contain('All accounts')
// })
// })
// })
| import { expect } from 'chai'
import { h, render, rerender } from 'preact'
import App from '../app/components/app'
// describe('App', () => {
// let scratch
// before( () => {
// scratch = document.createElement('div');
// (document.body || document.documentElement).appendChild(scratch)
// })
// beforeEach( () => {
// scratch.innerHTML = ''
// })
// after( () => {
// scratch.parentNode.removeChild(scratch)
// scratch = null
// })
// describe('routing', () => {
// it('should render the discovery page', () => {
// render(<App konnectors={[]}/>, scratch)
// route('/')
// expect(scratch.querySelector('main').innerHTML).to.contain('Discovery')
// })
// it('should render /category', () => {
// render(<App konnectors={[]}/>, scratch)
// route('/category')
// //rerender()
// expect(scratch.querySelector('main').innerHTML).to.contain('All accounts')
// })
// })
// }) |
Add notes on Pelco P serial port baud rate | /*
*
* Read and decode Pelco D and Pelco P CCTV commands from a Serial Port / COM Port (using node-serialport)
* Copyright 2016 Roger Hardiman
*
* You will need to set the SERIAL_PORT and the BAUD_RATE
* Note that the Serial Port varies between operating systems
* E.g. COM1 on Windows
* E.g. /dev/ttyUSB0 on Linux
* E.g. /dev/cu.usbserial-141 on Mac
*
* The Baud Rate for Pelco D is often 2400 8-N-1
* The Baud Rate for Pelco P is often 4800 8-N-1
*/
// External Dependencies
var SerialPort = require('serialport').SerialPort;
var PelcoD_Decoder = require('./pelcod_decoder');
// User Settings
var SERIAL_PORT = '/dev/ttyUSB0';
var BAUD_RATE = 2400;
// Globals
var pelco_d_decoder = new PelcoD_Decoder();
var port = new SerialPort(SERIAL_PORT, {
baudrate: BAUD_RATE,
parity: 'none',
dataBits: 8,
stopBits: 1,
});
// Callback - Open
port.on('open', function(err) {
if (err) {
console.log('Serial Port Error : ' + err);
} else {
console.log('Serial Port ' + SERIAL_PORT + ' open');
}
});
// Callback - Data
port.on('data', function(buffer) {
pelco_d_decoder.processBuffer(buffer);
});
| /*
*
* Read and decode Pelco D CCTV commands from a Serial Port / COM Port (using node-serialport)
* Copyright 2016 Roger Hardiman
*
*/
// External Dependencies
var SerialPort = require('serialport').SerialPort;
var PelcoD_Decoder = require('./pelcod_decoder');
// User Settings
var SERIAL_PORT = 'COM2'; // or /dev/ttyUSB0 on Linux
var BAUD_RATE = 2400;
// Globals
var pelco_d_decoder = new PelcoD_Decoder();
var port = new SerialPort(SERIAL_PORT, {
baudrate: BAUD_RATE,
parity: 'none',
dataBits: 8,
stopBits: 1,
});
// Callback - Open
port.on('open', function(err) {
if (err) {
console.log('Serial Port Error : ' + err);
} else {
console.log('Serial Port ' + SERIAL_PORT + ' open');
}
});
// Callback - Data
port.on('data', function(buffer) {
pelco_d_decoder.processBuffer(buffer);
}); |
Mark rcm test as fast so it executes during build and test | from __future__ import division
import numpy as np
import climlab
import pytest
@pytest.fixture()
def rcm():
# initial state (temperatures)
state = climlab.column_state(num_lev=num_lev, num_lat=1, water_depth=5.)
## Create individual physical process models:
# fixed relative humidity
h2o = climlab.radiation.ManabeWaterVapor(state=state, name='H2O')
# Hard convective adjustment
convadj = climlab.convection.ConvectiveAdjustment(state=state, name='ConvectiveAdjustment',
adj_lapse_rate=6.5)
# CAM3 radiation with default parameters and interactive water vapor
rad = climlab.radiation.RRTMG(state=state, albedo=alb, specific_humidity=h2o.q, name='Radiation')
# Couple the models
rcm = climlab.couple([h2o,convadj,rad], name='RCM')
return rcm
@pytest.mark.fast
def test_convective_adjustment(rcm):
rcm.step_forward()
# test non-scalar critical lapse rate
num_lev = rcm.lev.size
rcm.subprocess['ConvectiveAdjustment'].adj_lapse_rate = np.linspace(5., 8., num_lev)
rcm.step_forward()
# test pseudoadiabatic critical lapse rate
rcm.subprocess['ConvectiveAdjustment'].adj_lapse_rate = 'pseudoadiabat'
rcm.step_forward()
| from __future__ import division
import numpy as np
import climlab
import pytest
@pytest.fixture()
def rcm():
# initial state (temperatures)
state = climlab.column_state(num_lev=num_lev, num_lat=1, water_depth=5.)
## Create individual physical process models:
# fixed relative humidity
h2o = climlab.radiation.ManabeWaterVapor(state=state, name='H2O')
# Hard convective adjustment
convadj = climlab.convection.ConvectiveAdjustment(state=state, name='ConvectiveAdjustment',
adj_lapse_rate=6.5)
# CAM3 radiation with default parameters and interactive water vapor
rad = climlab.radiation.RRTMG(state=state, albedo=alb, specific_humidity=h2o.q, name='Radiation')
# Couple the models
rcm = climlab.couple([h2o,convadj,rad], name='RCM')
return rcm
def test_convective_adjustment(rcm):
rcm.step_forward()
# test non-scalar critical lapse rate
num_lev = rcm.lev.size
rcm.subprocess['ConvectiveAdjustment'].adj_lapse_rate = np.linspace(5., 8., num_lev)
rcm.step_forward()
# test pseudoadiabatic critical lapse rate
rcm.subprocess['ConvectiveAdjustment'].adj_lapse_rate = 'pseudoadiabat'
rcm.step_forward()
|
Correct coding error - need to return coding from property function or it'll cache None. | from .coding import Coding
from .lazy import lazyprop
from ..system_uri import IETF_LANGUAGE_TAG
class LocaleConstants(object):
"""Attributes for built in locales
Additions may be defined in persistence files, base values defined
within for easy access and testing
"""
def __iter__(self):
for attr in dir(self):
if attr.startswith('_'):
continue
yield getattr(self, attr)
@lazyprop
def AmericanEnglish(self):
return Coding(
system=IETF_LANGUAGE_TAG, code='en_US',
display='American English').add_if_not_found(True)
@lazyprop
def AustralianEnglish(self):
return Coding(
system=IETF_LANGUAGE_TAG, code='en_AU',
display='Australian English').add_if_not_found(True)
| from .coding import Coding
from .lazy import lazyprop
from ..system_uri import IETF_LANGUAGE_TAG
class LocaleConstants(object):
"""Attributes for built in locales
Additions may be defined in persistence files, base values defined
within for easy access and testing
"""
def __iter__(self):
for attr in dir(self):
if attr.startswith('_'):
continue
yield getattr(self, attr)
@lazyprop
def AmericanEnglish(self):
Coding(
system=IETF_LANGUAGE_TAG, code='en_US',
display='American English').add_if_not_found(True)
@lazyprop
def AustralianEnglish(self):
Coding(
system=IETF_LANGUAGE_TAG, code='en_AU',
display='Australian English').add_if_not_found(True)
|
Fix mypy import errors due to removed services
Signed-off-by: Dan Yeaw <2591e5f46f28d303f9dc027d475a5c60d8dea17a@yeaw.me> | if __name__ == "__main__":
import gaphor
from gaphor import core
from gaphor.services.componentregistry import ComponentRegistry
from gaphor.ui.consolewindow import ConsoleWindow
from gaphor.services.copyservice import CopyService
from gaphor.plugins.diagramlayout import DiagramLayout
from gaphor.ui.mainwindow import Diagrams
from gaphor.UML.elementfactory import ElementFactory
from gaphor.ui.elementeditor import ElementEditor
from gaphor.services.eventmanager import EventManager
from gaphor.services.helpservice import HelpService
from gaphor.ui.mainwindow import MainWindow
from gaphor.services.properties import Properties
from gaphor.plugins.pynsource import PyNSource
from gaphor.services.sanitizerservice import SanitizerService
from gaphor.services.undomanager import UndoManager
from gaphor.plugins.xmiexport import XMIExport
gaphor.main()
| if __name__ == "__main__":
import gaphor
from gaphor import core
from gaphor.services.actionmanager import ActionManager
from gaphor.plugins.alignment import Alignment
from gaphor.services.componentregistry import ComponentRegistry
from gaphor.ui.consolewindow import ConsoleWindow
from gaphor.services.copyservice import CopyService
from gaphor.services.diagramexportmanager import DiagramExportManager
from gaphor.plugins.diagramlayout import DiagramLayout
from gaphor.ui.mainwindow import Diagrams
from gaphor.UML.elementfactory import ElementFactory
from gaphor.ui.elementeditor import ElementEditor
from gaphor.services.eventmanager import EventManager
from gaphor.services.filemanager import FileManager
from gaphor.services.helpservice import HelpService
from gaphor.ui.mainwindow import MainWindow
from gaphor.ui.mainwindow import Namespace
from gaphor.services.properties import Properties
from gaphor.plugins.pynsource import PyNSource
from gaphor.services.sanitizerservice import SanitizerService
from gaphor.ui.mainwindow import Toolbox
from gaphor.services.undomanager import UndoManager
from gaphor.plugins.xmiexport import XMIExport
gaphor.main()
|
Use xml.sax.saxutils.escape in place of xmlrpclib.escape
The latter is not available in python 3 | # vim:fileencoding=utf-8:noet
from powerline.renderer import Renderer
from powerline.colorscheme import ATTR_BOLD, ATTR_ITALIC, ATTR_UNDERLINE
from xml.sax.saxutils import escape as _escape
class PangoMarkupRenderer(Renderer):
'''Powerline Pango markup segment renderer.'''
@staticmethod
def hlstyle(*args, **kwargs):
# We don't need to explicitly reset attributes, so skip those calls
return ''
def hl(self, contents, fg=None, bg=None, attr=None):
'''Highlight a segment.'''
awesome_attr = []
if fg is not None:
if fg is not False and fg[1] is not False:
awesome_attr += ['foreground="#{0:06x}"'.format(fg[1])]
if bg is not None:
if bg is not False and bg[1] is not False:
awesome_attr += ['background="#{0:06x}"'.format(bg[1])]
if attr is not None and attr is not False:
if attr & ATTR_BOLD:
awesome_attr += ['font_weight="bold"']
if attr & ATTR_ITALIC:
awesome_attr += ['font_style="italic"']
if attr & ATTR_UNDERLINE:
awesome_attr += ['underline="single"']
return '<span ' + ' '.join(awesome_attr) + '>' + contents + '</span>'
escape = staticmethod(_escape)
renderer = PangoMarkupRenderer
| # vim:fileencoding=utf-8:noet
from powerline.renderer import Renderer
from powerline.colorscheme import ATTR_BOLD, ATTR_ITALIC, ATTR_UNDERLINE
from xmlrpclib import escape as _escape
class PangoMarkupRenderer(Renderer):
'''Powerline Pango markup segment renderer.'''
@staticmethod
def hlstyle(*args, **kwargs):
# We don't need to explicitly reset attributes, so skip those calls
return ''
def hl(self, contents, fg=None, bg=None, attr=None):
'''Highlight a segment.'''
awesome_attr = []
if fg is not None:
if fg is not False and fg[1] is not False:
awesome_attr += ['foreground="#{0:06x}"'.format(fg[1])]
if bg is not None:
if bg is not False and bg[1] is not False:
awesome_attr += ['background="#{0:06x}"'.format(bg[1])]
if attr is not None and attr is not False:
if attr & ATTR_BOLD:
awesome_attr += ['font_weight="bold"']
if attr & ATTR_ITALIC:
awesome_attr += ['font_style="italic"']
if attr & ATTR_UNDERLINE:
awesome_attr += ['underline="single"']
return '<span ' + ' '.join(awesome_attr) + '>' + contents + '</span>'
escape = staticmethod(_escape)
renderer = PangoMarkupRenderer
|
Remove resource leak in Texture
This commit adds code to Texture to delete allocated textures when
they are garbage collected. Comments in Texture are also updated. | """
A OpenGL texture class
"""
from OpenGL.GL import *
import pygame
class Texture(object):
"""An OpenGL texture"""
def __init__(self, file_):
"""Allocate and load the texture"""
self.surface = pygame.image.load(file_).convert_alpha()
self.__texture = glGenTextures(1)
self.reload()
def __del__(self):
"""Release the texture"""
glDeleteTextures([self.__texture])
def reload(self):
"""Load the texture"""
glBindTexture(GL_TEXTURE_2D, self.__texture)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, self.w, self.h, 0, GL_RGBA,
GL_UNSIGNED_BYTE, pygame.image.tostring(self.surface, "RGBA", True))
def bind(self):
"""Make the texture active in the current OpenGL context"""
glBindTexture(GL_TEXTURE_2D, self.__texture)
w = property(lambda self: self.surface.get_width())
h = property(lambda self: self.surface.get_height())
| """
A OpenGL texture class
"""
from OpenGL.GL import *
import pygame
class Texture(object):
"""An OpenGL texture"""
def __init__(self, file_):
# Load and allocate the texture
self.surface = pygame.image.load(file_).convert_alpha()
self.__texture = glGenTextures(1)
self.reload()
def reload(self):
# Set up the texture
glEnable(GL_TEXTURE_2D)
glBindTexture(GL_TEXTURE_2D, self.__texture)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, self.w, self.h, 0, GL_RGBA,
GL_UNSIGNED_BYTE, pygame.image.tostring(self.surface, "RGBA", True))
def bind(self):
glBindTexture(GL_TEXTURE_2D, self.__texture)
w = property(lambda self: self.surface.get_width())
h = property(lambda self: self.surface.get_height())
|
Add sleeping spin-wait to listener script
This will prevent the script from exiting, thus defeating the entire purpose of
using a separate GPIO button to shutdown | #!/usr/bin/env python3
import RPIO
import subprocess
import time
PIN_MODE = RPIO.BCM
SHUTDOWN_BTN_PIN = 4
PIN_PULL = RPIO.PUD_DOWN
EDGE_DETECT = 'rising'
def main():
RPIO.setmode(PIN_MODE)
RPIO.setup(SHUTDOWN_BTN_PIN, RPIO.IN, pull_up_down=PIN_PULL)
RPIO.add_interrupt_callback(SHUTDOWN_BTN_PIN,
shutdown_callback,
edge=EDGE_DETECT,
pull_up_down=PIN_PULL,
debounce_timeout_ms=33)
def shutdown_callback(gpio_id, value):
subprocess.call('shutdown now')
if __name__ == '__main__':
main()
# do an efficient spin-lock here so that we can continue waiting for an
# interrupt
while True:
# this sleep() is an attempt to prevent the CPU from staying at 100%
time.sleep(10)
| #!/usr/bin/env python3
import RPIO
import subprocess
PIN_MODE = RPIO.BCM
SHUTDOWN_BTN_PIN = 4
PIN_PULL = RPIO.PUD_DOWN
EDGE_DETECT = 'rising'
def main():
RPIO.setmode(PIN_MODE)
RPIO.setup(SHUTDOWN_BTN_PIN, RPIO.IN, pull_up_down=PIN_PULL)
RPIO.add_interrupt_callback(SHUTDOWN_BTN_PIN,
shutdown_callback,
edge=EDGE_DETECT,
pull_up_down=PIN_PULL,
debounce_timeout_ms=33)
def shutdown_callback(gpio_id, value):
subprocess.call('shutdown now')
if __name__ == '__main__':
main()
|
Use LocalStore to have a fallback when localStorage is not avail. | const moment = require('moment');
const urlForStatic = require('./url').urlForStatic;
const getStaticHash = require('./utility').getStaticHash;
const LocalStore = require('../_common/storage').LocalStore;
// only reload if it's more than 10 minutes since the last reload
const shouldForceReload = last_reload => !last_reload || +last_reload + (10 * 60 * 1000) < moment().valueOf();
// calling this method is handled by GTM tags
const checkNewRelease = () => {
const last_reload = LocalStore.getItem('new_release_reload_time');
if (!shouldForceReload(last_reload)) return false;
LocalStore.setItem('new_release_reload_time', moment().valueOf());
const current_hash = getStaticHash();
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = () => {
if (+xhttp.readyState === 4 && +xhttp.status === 200) {
const latest_hash = xhttp.responseText;
if (latest_hash && current_hash && latest_hash !== current_hash) {
window.location.reload(true);
}
}
};
xhttp.open('GET', urlForStatic(`version?${Math.random().toString(36).slice(2)}`), true);
xhttp.send();
return true;
};
module.exports = {
shouldForceReload,
checkNewRelease,
};
| const moment = require('moment');
const urlForStatic = require('./url').urlForStatic;
const getStaticHash = require('./utility').getStaticHash;
// only reload if it's more than 10 minutes since the last reload
const shouldForceReload = last_reload => !last_reload || +last_reload + (10 * 60 * 1000) < moment().valueOf();
// calling this method is handled by GTM tags
const checkNewRelease = () => {
const last_reload = localStorage.getItem('new_release_reload_time');
if (!shouldForceReload(last_reload)) return false;
localStorage.setItem('new_release_reload_time', moment().valueOf());
const current_hash = getStaticHash();
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = () => {
if (+xhttp.readyState === 4 && +xhttp.status === 200) {
const latest_hash = xhttp.responseText;
if (latest_hash && current_hash && latest_hash !== current_hash) {
window.location.reload(true);
}
}
};
xhttp.open('GET', urlForStatic(`version?${Math.random().toString(36).slice(2)}`), true);
xhttp.send();
return true;
};
module.exports = {
shouldForceReload,
checkNewRelease,
};
|
Revert "TimeAndPlace no longer refers to realtime data"
This reverts commit cf92e191e3748c67102f142b411937517c5051f4. | #!/usr/bin/env python3
from .base import Serializable
from .locations import Platform
from .realtime import RealtimeTime
class TimeAndPlace(Serializable):
def __init__(self, platform=None, arrival=None, departure=None):
super().__init__()
self.platform = platform
self.arrival = arrival
self.departure = departure
self.passthrough = False
@classmethod
def _validate(cls):
return {
'platform': (None, Platform),
'arrival': (None, RealtimeTime),
'departure': (None, RealtimeTime),
'passthrough': bool
}
@property
def stop(self):
return self.platform.stop
def __eq__(self, other):
assert isinstance(other, TimeAndPlace)
return (self.platform == other.platform and
self.arrival == other.arrival and
self.departure == other.departure)
def __repr__(self):
return ('<TimeAndPlace %s %s %s>' % (self.arrival, self.departure, self.platform))
| #!/usr/bin/env python3
from .base import Serializable
from .locations import Platform
from datetime import datetime
class TimeAndPlace(Serializable):
def __init__(self, platform=None, arrival=None, departure=None):
super().__init__()
self.platform = platform
self.arrival = arrival
self.departure = departure
self.passthrough = False
@classmethod
def _validate(cls):
return {
'platform': (None, Platform),
'arrival': (None, datetime),
'departure': (None, datetime),
'passthrough': bool
}
@property
def stop(self):
return self.platform.stop
def __eq__(self, other):
assert isinstance(other, TimeAndPlace)
return (self.platform == other.platform and
self.arrival == other.arrival and
self.departure == other.departure)
def __repr__(self):
return ('<TimeAndPlace %s %s %s>' % (self.arrival, self.departure, self.platform))
|
Make sure list of domains is initialized | module.exports = function(slackapp, config) {
/*
As of Botkit 0.7.0, we can't guarantee that our OAuth callback will have the last write on the team
and set the businessUnitId. Because of callback hell in the /oauth handler, the following line might
have the last say and blow away our changes (depending on storage engine used, but that's a detail)
https://github.com/howdyai/botkit/blob/c21ec51cff18aa3b8617d4225de48e806ecf3c72/lib/SlackBot.js#L734
So we use the create/update_team handlers to dirtily mutate the team object before that last write.
*/
function dirtilyUpdateTeamWithBusinessUnitId(team) {
const setOfUnits = new Set(team.businessUnits);
setOfUnits.add(config.BUSINESS_UNIT_ID);
team.businessUnits = [...setOfUnits.values()];
}
slackapp.on('create_team', (bot, team) => dirtilyUpdateTeamWithBusinessUnitId(team));
slackapp.on('update_team', (bot, team) => dirtilyUpdateTeamWithBusinessUnitId(team));
};
| module.exports = function(slackapp, config) {
/*
As of Botkit 0.6.8, we can't guarantee that our OAuth callback will have the last write on the team
and set the businessUnitId. Because of callback hell in the /oauth handler, the following line might
have the last say and blow away our changes (depending on storage engine used, but that's a detail)
https://github.com/howdyai/botkit/blob/c21ec51cff18aa3b8617d4225de48e806ecf3c72/lib/SlackBot.js#L734
So we use the create/update_team handlers to dirtily mutate the team object before that last write.
*/
function dirtilyUpdateTeamWithBusinessUnitId(team) {
team.businessUnitId = config.BUSINESS_UNIT_ID;
}
slackapp.on('create_team', (bot, team) => dirtilyUpdateTeamWithBusinessUnitId(team));
slackapp.on('update_team', (bot, team) => dirtilyUpdateTeamWithBusinessUnitId(team));
};
|
Update the example proxy list | """
Proxy Server "Phone Book".
Simplify running browser tests through a proxy server
by adding your frequently-used proxies here.
Now you can do something like this on the command line:
"pytest SOME_TEST.py --proxy=proxy1"
Format of PROXY_LIST server entries:
* "ip_address:port" OR "username:password@ip_address:port"
* "server:port" OR "username:password@server:port"
(Do NOT include the http:// or https:// in your proxy string!)
Example proxies in PROXY_LIST below are not guaranteed to be active or secure.
If you don't already have a proxy server to connect to,
you can try finding one from one of following sites:
* https://bit.ly/36GtZa1
* https://www.us-proxy.org/
* https://hidemy.name/en/proxy-list/
* http://free-proxy.cz/en/proxylist/country/all/https/ping/all
"""
PROXY_LIST = {
"example1": "152.179.12.86:3128", # (Example) - set your own proxy here
"example2": "176.9.79.126:3128", # (Example) - set your own proxy here
"proxy1": None,
"proxy2": None,
"proxy3": None,
"proxy4": None,
"proxy5": None,
}
| """
Proxy Server "Phone Book".
Simplify running browser tests through a proxy server
by adding your frequently-used proxies here.
Now you can do something like this on the command line:
"pytest SOME_TEST.py --proxy=proxy1"
Format of PROXY_LIST server entries:
* "ip_address:port" OR "username:password@ip_address:port"
* "server:port" OR "username:password@server:port"
(Do NOT include the http:// or https:// in your proxy string!)
Example proxies in PROXY_LIST below are not guaranteed to be active or secure.
If you don't already have a proxy server to connect to,
you can try finding one from one of following sites:
* https://bit.ly/36GtZa1
* https://www.us-proxy.org/
* https://hidemy.name/en/proxy-list/
* http://free-proxy.cz/en/proxylist/country/all/https/ping/all
"""
PROXY_LIST = {
"example1": "152.26.66.140:3128", # (Example) - set your own proxy here
"example2": "64.235.204.107:8080", # (Example) - set your own proxy here
"proxy1": None,
"proxy2": None,
"proxy3": None,
"proxy4": None,
"proxy5": None,
}
|
Use better convention for the version file. | var assign = require('object-assign');
var cwd = process.cwd();
var fs = require('fs');
var gat = require('gulp-auto-task');
var path = require('path');
var pkg = require(path.join(cwd, '/package.json'));
var semver = require('semver');
var sh = require('shelljs');
function replace (file, pattern, replacement) {
var str = fs.readFileSync(file).toString();
str = str.replace(pattern, replacement);
fs.writeFileSync(file, str);
};
module.exports = function (done) {
var opts = assign({
type: 'patch'
}, gat.opts());
var currentVersion = pkg.version;
var nextVersion = opts.semver || semver.inc(
currentVersion,
opts.type
);
sh.exec('npm run lint');
sh.exec('npm run test');
replace('src/version.js', currentVersion, nextVersion);
replace('bower.json', currentVersion, nextVersion);
replace('package.json', currentVersion, nextVersion);
sh.exec('npm run build');
sh.exec('git commit -am "' + currentVersion + ' -> ' + nextVersion + '"');
sh.exec('git tag -a ' + nextVersion + ' -m ' + nextVersion);
sh.exec('git push');
sh.exec('git push --tags');
sh.exec('npm publish');
done();
};
| var assign = require('object-assign');
var cwd = process.cwd();
var fs = require('fs');
var gat = require('gulp-auto-task');
var path = require('path');
var pkg = require(path.join(cwd, '/package.json'));
var semver = require('semver');
var sh = require('shelljs');
function replace (file, pattern, replacement) {
var str = fs.readFileSync(file).toString();
str = str.replace(pattern, replacement);
fs.writeFileSync(file, str);
};
module.exports = function (done) {
var opts = assign({
type: 'patch'
}, gat.opts());
var currentVersion = pkg.version;
var nextVersion = opts.semver || semver.inc(
currentVersion,
opts.type
);
sh.exec('npm run lint');
sh.exec('npm run test');
replace('src/api/version.js', currentVersion, nextVersion);
replace('bower.json', currentVersion, nextVersion);
replace('package.json', currentVersion, nextVersion);
sh.exec('npm run build');
sh.exec('git commit -am "' + currentVersion + ' -> ' + nextVersion + '"');
sh.exec('git tag -a ' + nextVersion + ' -m ' + nextVersion);
sh.exec('git push');
sh.exec('git push --tags');
sh.exec('npm publish');
done();
};
|
Use v-cloak until page is ready.
Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com> | <div class="row">
<div class="columns twelve-xs">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="collapse navbar-collapse" id="navbar_main">
<offcanvas element=".wrapper"></offcanvas>
<a class="navbar-brand navbar-left" href="{{ handles('orchestra::/') }}">
{{ memorize('site.name', 'Orchestra Platform') }}
</a>
<div class="navbar-form navbar-left hidden-xs">
@yield('navbar-left')
</div>
@section('navbar-right')
<a href="{{ handles('orchestra::logout', ['csrf' => true]) }}" class="btn btn-primary navbar-btn navbar-right v-cloak--hidden" v-if="user">
{{ trans('orchestra/foundation::title.logout') }}
</a>
@show
</div>
</div>
</nav>
</div>
</div>
| <div class="row">
<div class="columns twelve-xs">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="collapse navbar-collapse" id="navbar_main">
<offcanvas element=".wrapper"></offcanvas>
<a class="navbar-brand navbar-left" href="{{ handles('orchestra::/') }}">
{{ memorize('site.name', 'Orchestra Platform') }}
</a>
<div class="navbar-form navbar-left hidden-xs">
@yield('navbar-left')
</div>
@section('navbar-right')
<a href="{{ handles('orchestra::logout', ['csrf' => true]) }}" class="btn btn-primary navbar-btn navbar-right" v-if="user">
{{ trans('orchestra/foundation::title.logout') }}
</a>
@show
</div>
</div>
</nav>
</div>
</div>
|
Refactor test harness file discovery | import unittest
import glob
import os
import mmstats
class MmstatsTestCase(unittest.TestCase):
@property
def files(self):
return glob.glob(os.path.join(self.path, 'test*.mmstats'))
def setUp(self):
super(MmstatsTestCase, self).setUp()
self.path = mmstats.DEFAULT_PATH
# Clean out stale mmstats files
for fn in self.files:
try:
os.remove(fn)
pass
except OSError:
print 'Could not remove: %s' % fn
def tearDown(self):
# clean the dir after tests
for fn in self.files:
try:
os.remove(fn)
pass
except OSError:
continue
| import unittest
import glob
import os
import mmstats
class MmstatsTestCase(unittest.TestCase):
def setUp(self):
super(MmstatsTestCase, self).setUp()
self.path = mmstats.DEFAULT_PATH
# Clean out stale mmstats files
for fn in glob.glob(os.path.join(self.path, 'test*.mmstats')):
try:
os.remove(fn)
pass
except OSError:
print 'Could not remove: %s' % fn
def tearDown(self):
# clean the dir after tests
for fn in glob.glob(os.path.join(self.path, 'test*.mmstats')):
try:
os.remove(fn)
pass
except OSError:
continue
|
Add sync trigger to latest migration | """empty message
Revision ID: 2f3192e76e5
Revises: 3dbc20af3c9
Create Date: 2015-11-24 15:28:41.695124
"""
# revision identifiers, used by Alembic.
revision = '2f3192e76e5'
down_revision = '3dbc20af3c9'
from alembic import op
import sqlalchemy as sa
import sqlalchemy_utils
from sqlalchemy_searchable import sync_trigger
def upgrade():
conn = op.get_bind()
sync_trigger(conn, 'word', 'search_vector', ["singular", "plural", "infinitive", "past_tense",
"present_perfect_tense", "positive", "comparative", "superlative",
"adverb", "conjunction", "preposition", "meaning", "examples"])
### commands auto generated by Alembic - please adjust! ###
op.add_column('word', sa.Column('search_vector', sqlalchemy_utils.TSVectorType(), nullable=True))
op.create_index('ix_word_search_vector', 'word', ['search_vector'], unique=False, postgresql_using='gin')
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_index('ix_word_search_vector', table_name='word')
op.drop_column('word', 'search_vector')
### end Alembic commands ###
| """empty message
Revision ID: 2f3192e76e5
Revises: 3dbc20af3c9
Create Date: 2015-11-24 15:28:41.695124
"""
# revision identifiers, used by Alembic.
revision = '2f3192e76e5'
down_revision = '3dbc20af3c9'
from alembic import op
import sqlalchemy as sa
import sqlalchemy_utils
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('word', sa.Column('search_vector', sqlalchemy_utils.TSVectorType(), nullable=True))
op.create_index('ix_word_search_vector', 'word', ['search_vector'], unique=False, postgresql_using='gin')
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_index('ix_word_search_vector', table_name='word')
op.drop_column('word', 'search_vector')
### end Alembic commands ###
|
Remove describe.only as it blocks other tests to run
I used it to filter out other tests to speed up the development, but forgot to remove before i had sent previous PR to fix the issue with process.nextTick. My bad. | var assert = require("assert");
var schedule = require("../../js/debug/schedule");
var isNodeJS = typeof process !== "undefined" && typeof process.execPath === "string";
describe("schedule", function () {
if (isNodeJS) {
describe("for Node.js", function () {
it("should preserve the active domain", function (done) {
var domain = require("domain");
var activeDomain = domain.create();
activeDomain.run(function () {
schedule(function () {
assert(domain.active);
assert.equal(domain.active, activeDomain);
done();
});
});
});
});
}
});
| var assert = require("assert");
var schedule = require("../../js/debug/schedule");
var isNodeJS = typeof process !== "undefined" && typeof process.execPath === "string";
describe.only("schedule", function () {
if (isNodeJS) {
describe("for Node.js", function () {
it("should preserve the active domain", function (done) {
var domain = require("domain");
var activeDomain = domain.create();
activeDomain.run(function () {
schedule(function () {
assert(domain.active);
assert.equal(domain.active, activeDomain);
done();
});
});
});
});
}
});
|
Disable Django-CMS test on Django 1.10+
Someone with the time and inclination should set up the test to work with a Django-CMS version compatible with Django 1.10+, then try again | import django
from django.contrib.auth.models import AnonymousUser
from django.utils.crypto import get_random_string
import pytest
from cms import api
from cms.page_rendering import render_page
from form_designer.contrib.cms_plugins.form_designer_form.cms_plugins import FormDesignerPlugin
from form_designer.models import FormDefinition, FormDefinitionField
@pytest.mark.django_db
def test_cms_plugin_renders_in_cms_page(rf):
if django.VERSION >= (1, 10):
pytest.xfail('This test is broken in Django 1.10+')
fd = FormDefinition.objects.create(
mail_to='test@example.com',
mail_subject='Someone sent you a greeting: {{ test }}'
)
field = FormDefinitionField.objects.create(
form_definition=fd,
name='test',
label=get_random_string(),
field_class='django.forms.CharField',
)
page = api.create_page("test", "page.html", "en")
ph = page.get_placeholders()[0]
api.add_plugin(ph, FormDesignerPlugin, "en", form_definition=fd)
request = rf.get("/")
request.user = AnonymousUser()
request.current_page = page
response = render_page(request, page, "fi", "test")
response.render()
content = response.content.decode("utf8")
assert field.label in content
assert "<form" in content
| from django.contrib.auth.models import AnonymousUser
from django.utils.crypto import get_random_string
import pytest
from cms import api
from cms.page_rendering import render_page
from form_designer.contrib.cms_plugins.form_designer_form.cms_plugins import FormDesignerPlugin
from form_designer.models import FormDefinition, FormDefinitionField
@pytest.mark.django_db
def test_cms_plugin_renders_in_cms_page(rf):
fd = FormDefinition.objects.create(
mail_to='test@example.com',
mail_subject='Someone sent you a greeting: {{ test }}'
)
field = FormDefinitionField.objects.create(
form_definition=fd,
name='test',
label=get_random_string(),
field_class='django.forms.CharField',
)
page = api.create_page("test", "page.html", "en")
ph = page.get_placeholders()[0]
api.add_plugin(ph, FormDesignerPlugin, "en", form_definition=fd)
request = rf.get("/")
request.user = AnonymousUser()
request.current_page = page
response = render_page(request, page, "fi", "test")
response.render()
content = response.content.decode("utf8")
assert field.label in content
assert "<form" in content
|
Load user feed url from chrome storage | var githubFeed = ({
feedUrl: "",
loadFeedUrl: function() {
var self = this;
chrome.storage.local.get("current_user_url", function(data) {
self.feedUrl = data.current_user_url;
});
},
urlChanged: function() {
chrome.storage.onChanged.addListener(function(changes, namespace) {
for (var key in changes) {
if (key === "current_user_url") {
alert("!!!");
console.log(changes[key].newValue);
this.feedUrl = chages[key].newValue;
}
}
});
},
getUserFeed: function() {
$.ajax({
type: "GET",
url: this.feedUrl,
dataType: "application/atom+xml",
success: function (data) {
},
error: function (xhr, status, data) {
},
});
},
init: function() {
this.urlChanged();
return this;
},
}).init();
githubFeed.loadFeedUrl();
| ({
init: function() {
debugger;
this.urlChanged();
},
feedUrl: "",
urlChanged: function() {
chrome.storage.onChanged.addListener(function(changes, namespace) {
for (var key in changes) {
if (key === "current_user_url") {
alert("!!!");
console.log(changes[key].newValue);
this.feedUrl = chages[key].newValue;
}
}
});
},
getUserFeed: function() {
$.ajax({
type: "GET",
url: this.feedUrl,
dataType: "application/atom+xml",
success: function (data) {
},
error: function (xhr, status, data) {
},
});
}
}).init();
|
Install github verison of boto in aws cookbook (for now) |
import os
from kokki import *
# Package("python-boto")
Execute("pip install git+http://github.com/boto/boto.git#egg=boto",
not_if = 'python -c "import boto"')
Execute("mv /usr/lib/pymodules/python2.6/boto /tmp/boto.orig",
only_if = lambda:os.path.exists("/usr/lib/pymodules/python2.6/boto"))
# Mount volumes and format is necessary
for vol in env.config.aws.volumes:
env.cookbooks.aws.EBSVolume(vol['volume_id'],
availability_zone = env.config.aws.availability_zone,
device = vol['device'],
action = "attach")
if vol.get('fstype'):
if vol['fstype'] == "xfs":
Package("xfsprogs")
Execute("mkfs.%(fstype)s -f %(device)s" % vol,
not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % vol)
if vol.get('mount_point'):
Mount(vol['mount_point'],
device = vol['device'],
fstype = vol.get('fstype'),
options = vol.get('fsoptions', ["noatime"]),
action = ["mount", "enable"])
|
import os
from kokki import *
# Package("python-boto")
Execute("pip install git+http://github.com/boto/boto.git#egg=boto",
not_if = 'python -c "import boto"')
Execute("mv /usr/lib/pymodules/python2.6/boto /tmp/boto.orig",
only_if = os.path.exists("/usr/lib/pymodules/python2.6/boto"))
# Mount volumes and format is necessary
for vol in env.config.aws.volumes:
env.cookbooks.aws.EBSVolume(vol['volume_id'],
availability_zone = env.config.aws.availability_zone,
device = vol['device'],
action = "attach")
if vol.get('fstype'):
if vol['fstype'] == "xfs":
Package("xfsprogs")
Execute("mkfs.%(fstype)s -f %(device)s" % vol,
not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % vol)
if vol.get('mount_point'):
Mount(vol['mount_point'],
device = vol['device'],
fstype = vol.get('fstype'),
options = vol.get('fsoptions', ["noatime"]),
action = ["mount", "enable"])
|
Fix formatting of propertyless java.time.Instant | package com.querydsl.sql.types;
import java.sql.*;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import javax.annotation.Nullable;
import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement;
/**
* JSR310InstantType maps {@linkplain java.time.Instant} to
* {@linkplain java.sql.Timestamp} on the JDBC level
*
*/
@IgnoreJRERequirement //conditionally included
public class JSR310InstantType extends AbstractJSR310DateTimeType<Instant> {
public JSR310InstantType() {
super(Types.TIMESTAMP);
}
public JSR310InstantType(int type) {
super(type);
}
@Override
public String getLiteral(Instant value) {
return dateTimeFormatter.format(LocalDateTime.ofInstant(value, ZoneId.of("Z")));
}
@Override
public Class<Instant> getReturnedClass() {
return Instant.class;
}
@Nullable
@Override
public Instant getValue(ResultSet rs, int startIndex) throws SQLException {
Timestamp timestamp = rs.getTimestamp(startIndex, utc());
return timestamp != null ? timestamp.toInstant() : null;
}
@Override
public void setValue(PreparedStatement st, int startIndex, Instant value) throws SQLException {
st.setTimestamp(startIndex, Timestamp.from(value), utc());
}
}
| package com.querydsl.sql.types;
import java.sql.*;
import java.time.Instant;
import javax.annotation.Nullable;
import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement;
/**
* JSR310InstantType maps {@linkplain java.time.Instant} to
* {@linkplain java.sql.Timestamp} on the JDBC level
*
*/
@IgnoreJRERequirement //conditionally included
public class JSR310InstantType extends AbstractJSR310DateTimeType<Instant> {
public JSR310InstantType() {
super(Types.TIMESTAMP);
}
public JSR310InstantType(int type) {
super(type);
}
@Override
public String getLiteral(Instant value) {
return dateTimeFormatter.format(value);
}
@Override
public Class<Instant> getReturnedClass() {
return Instant.class;
}
@Nullable
@Override
public Instant getValue(ResultSet rs, int startIndex) throws SQLException {
Timestamp timestamp = rs.getTimestamp(startIndex, utc());
return timestamp != null ? timestamp.toInstant() : null;
}
@Override
public void setValue(PreparedStatement st, int startIndex, Instant value) throws SQLException {
st.setTimestamp(startIndex, Timestamp.from(value), utc());
}
}
|
Fix - key error on post | var React = require("react");
var { Link } = require("react-router");
class Post extends React.Component {
render () {
var {
post : {
title: title,
content: content,
tags: tags,
}, prev, next
} = this.props;
var prevLinkEl = prev === null ? null : <Link to={`/posts/${prev.slug}`}>prev</Link>;
var nextLinkEl = next === null ? null : <Link to={`/posts/${next.slug}`}>next</Link>;
var tagEls = tags.map(t => <span key={t}>{t}</span>);
return (
<div>
<h1>{title}</h1>
{ prevLinkEl }
{ nextLinkEl }
<div className="content" dangerouslySetInnerHTML={{ __html: content }}/>
<div className="tags">{ tagEls }</div>
</div>
);
}
}
export default Post;
| var React = require("react");
var { Link } = require("react-router");
class Post extends React.Component {
render () {
var {
post : {
title: title,
content: content,
tags: tags,
}, prev, next
} = this.props;
var prevLinkEl = prev === null ? null : <Link to={`/posts/${prev.slug}`}>prev</Link>;
var nextLinkEl = next === null ? null : <Link to={`/posts/${next.slug}`}>next</Link>;
var tagEls = tags.map(t => <span>{t}</span>);
return (
<div>
<h1>{title}</h1>
{ prevLinkEl }
{ nextLinkEl }
<div className="content" dangerouslySetInnerHTML={{ __html: content }}/>
<div className="tags">{ tagEls }</div>
</div>
);
}
}
export default Post;
|
Increment version number for the addition of latest client side js | Package.describe({
name: 'saucecode:rollbar',
version: '0.0.7',
summary: 'Rollbar error reporting integrations for Meteor',
documentation: 'README.md'
});
Package.onUse(function(api) {
api.versionsFrom('METEOR@1.0');
Npm.depends({
'rollbar': '0.5.4'
});
api.use('check', 'server');
api.addFiles('lib/server/rollbar-server.js', 'server');
api.addFiles('lib/client/rollbar-client.js', 'client');
api.addFiles('lib/private/client-head.html', 'server', { isAsset: true });
api.export([
'throwError',
'handleError'
], 'client');
api.export([
'rollbar',
'throwError',
'handleError'
], 'server');
});
| Package.describe({
name: 'saucecode:rollbar',
version: '0.0.6',
summary: 'Rollbar error reporting integrations for Meteor',
documentation: 'README.md'
});
Package.onUse(function(api) {
api.versionsFrom('METEOR@1.0');
Npm.depends({
'rollbar': '0.5.4'
});
api.use('check', 'server');
api.addFiles('lib/server/rollbar-server.js', 'server');
api.addFiles('lib/client/rollbar-client.js', 'client');
api.addFiles('lib/private/client-head.html', 'server', { isAsset: true });
api.export([
'throwError',
'handleError'
], 'client');
api.export([
'rollbar',
'throwError',
'handleError'
], 'server');
});
|
Fix typo in selection theorem
Change-Id: Ieff9fe7e5783e0d3b995fb0ddbfc11015ca9197a | #! /usr/bin/env python
# Copyright Lajos Katona
#
# 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.
def selection_brute(mlist, t):
for i, l in enumerate(mlist):
if t == l:
return i
return -1
def selection_pythonic(mlist, t):
return mlist.index(t)
if __name__ == '__main__':
mylist = [1, 2, 3, 4, 5]
print(selection_brute(mylist, 4))
print(selection_pythonic(mylist, 4))
| #! /usr/bin/env python
# Copyright Lajos Katona
#
# 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.
def selection_brute(mylist, t):
for i, l in enumerate(mylist):
if t == l:
return i
return 0
def selection_pythonic(mylist, t):
return mylist.index(t)
if __name__ == '__main__':
mylist = [1, 2, 3, 4, 5]
print(selection_brute(mylist, 4))
print(selection_pythonic(mylist, 4))
|
Update for Pomegranate > 4 | /**
* @file index
* @author Jim Bulkowski <jim.b@paperelectron.com>
* @project pomegranate-sequelize-core
* @license MIT {@link http://opensource.org/licenses/MIT}
*/
'use strict';
var Sequelize = require('sequelize')
/**
*
* @module index
*/
exports.metadata = {
name: 'Sequelize',
param: 'SQL',
type: 'merge'
}
exports.plugin = {
load: function(inject, loaded) {
loaded(null, {Sequelize: Sequelize})
},
start: function(done) {
done()
},
stop: function(done) {
done()
}
}
exports.errors = {
ValidationError: Sequelize.ValidationError,
UniqueConstraintError: Sequelize.UniqueConstraintError,
ExclusionConstraintError: Sequelize.ExclusionConstraintError,
ForeignKeyConstraintError: Sequelize.ForeignKeyConstraintError
} | /**
* @file index
* @author Jim Bulkowski <jim.b@paperelectron.com>
* @project pomegranate-sequelize-core
* @license MIT {@link http://opensource.org/licenses/MIT}
*/
'use strict';
var Sequelize = require('sequelize')
/**
*
* @module index
*/
exports.metadata = {
name: 'Sequelize',
layer: 'core',
param: 'SQL',
type: 'merge'
}
exports.plugin = {
load: function(inject, loaded) {
loaded(null, {Sequelize: Sequelize})
},
start: function(done) {
done()
},
stop: function(done) {
done()
}
}
exports.errors = {
ValidationError: Sequelize.ValidationError,
UniqueConstraintError: Sequelize.UniqueConstraintError,
ExclusionConstraintError: Sequelize.ExclusionConstraintError,
ForeignKeyConstraintError: Sequelize.ForeignKeyConstraintError
} |
Use https to fetch worker stats | import Promise from 'bluebird';
import request from 'superagent';
import camelcase from 'camelcase';
import snakecase from 'snake-case';
import _ from 'lodash';
Promise.promisifyAll(request);
export function transformForFrontend(payload) {
_.forOwn(payload, (value, key) => {
if (camelcase(key) !== key) {
delete payload[key];
payload[camelcase(key)] = value;
}
});
return payload;
}
export function transformForBackend(payload) {
_.forOwn(payload, (value, key) => {
if (snakecase(key) !== key) {
delete payload[key];
payload[snakecase(key)] = value;
}
});
return payload;
}
const http = {
get: url => {
if (!/\/$/.test(url)) {
url += '/';
}
return request
.get(url)
.endAsync()
.then(transformForFrontend);
},
};
export default http;
export function getUser() {
return http.get('/api/users/me');
}
export function getBuilds(slug) {
const url = '/api/builds/';
return http.get(slug ? url + slug : url);
}
export function getBuild(slug) {
return http.get('/api/builds/' + slug);
}
export function getWorkerStats() {
return http.get('https://jobs.frigg.io/stats');
}
| import Promise from 'bluebird';
import request from 'superagent';
import camelcase from 'camelcase';
import snakecase from 'snake-case';
import _ from 'lodash';
Promise.promisifyAll(request);
export function transformForFrontend(payload) {
_.forOwn(payload, (value, key) => {
if (camelcase(key) !== key) {
delete payload[key];
payload[camelcase(key)] = value;
}
});
return payload;
}
export function transformForBackend(payload) {
_.forOwn(payload, (value, key) => {
if (snakecase(key) !== key) {
delete payload[key];
payload[snakecase(key)] = value;
}
});
return payload;
}
const http = {
get: url => {
if (!/\/$/.test(url)) {
url += '/';
}
return request
.get(url)
.endAsync()
.then(transformForFrontend);
},
};
export default http;
export function getUser() {
return http.get('/api/users/me');
}
export function getBuilds(slug) {
const url = '/api/builds/';
return http.get(slug ? url + slug : url);
}
export function getBuild(slug) {
return http.get('/api/builds/' + slug);
}
export function getWorkerStats() {
return http.get('http://jobs.frigg.io/stats');
}
|
Handle when container is undefined. | (function() {
var clientid;
jive.tile.onOpen(function(config, options, other, container ) {
osapi.jive.corev3.systemExtProps.get({}).execute(function (resp) {
if( resp && resp.content ) {
clientid = resp.content.clientid;
}
});
gadgets.window.adjustHeight();
if ( typeof config === "string" ) {
config = JSON.parse(config);
}
var json = config || { };
json.project = json.project || (container && container.name) || "";
// prepopulate the sequence input dialog
$("#project").val( json.project);
$("#btn_submit").click( function() {
config.project = $("#project").val();
config.clientid = clientid;
jive.tile.close(config, {} );
gadgets.window.adjustHeight(300);
});
});
})();
| (function() {
var clientid;
jive.tile.onOpen(function(config, options, other, container ) {
osapi.jive.corev3.systemExtProps.get({}).execute(function (resp) {
if( resp && resp.content ) {
clientid = resp.content.clientid;
}
});
gadgets.window.adjustHeight();
if ( typeof config === "string" ) {
config = JSON.parse(config);
}
var json = config || { };
json.project = json.project || container.name;
// prepopulate the sequence input dialog
$("#project").val( json.project);
$("#btn_submit").click( function() {
config.project = $("#project").val();
config.clientid = clientid;
jive.tile.close(config, {} );
gadgets.window.adjustHeight(300);
});
});
})();
|
Add valid values for projectType option of create command | package blade.cli;
import blade.cli.cmds.Build;
import blade.cli.cmds.IDE;
import blade.cli.cmds.Type;
import java.io.File;
import org.osgi.framework.Version;
import aQute.lib.getopt.Arguments;
import aQute.lib.getopt.Description;
import aQute.lib.getopt.Options;
@Arguments(arg = {"name", "[service]"})
@Description("Creates a new Liferay module project.")
public interface CreateOptions extends Options {
@Description("If a class is generated in the project, " +
"provide the name of the class to be generated." +
" If not provided defaults to Project name.")
public String classname();
@Description("The build type of project to create. "
+ "Valid values are maven or gradle. Default: gradle")
public Build build();
@Description("The directory where to create the new project.")
public File dir();
@Description("The type of IDE metadata to create along side "
+ "the new project.")
public IDE ide();
@Description("The type of Liferay module to create. "
+ "Valid values are service, jspportlet, or portlet.")
public Type projectType();
@Description("The version of Liferay to create the module for, "
+ "by default its 7.0.0")
public Version version();
}
| package blade.cli;
import blade.cli.cmds.Build;
import blade.cli.cmds.IDE;
import blade.cli.cmds.Type;
import java.io.File;
import org.osgi.framework.Version;
import aQute.lib.getopt.Arguments;
import aQute.lib.getopt.Description;
import aQute.lib.getopt.Options;
@Arguments(arg = {"name", "[service]"})
@Description("Creates a new Liferay module project.")
public interface CreateOptions extends Options {
@Description("If a class is generated in the project, " +
"provide the name of the class to be generated." +
" If not provided defaults to Project name.")
public String classname();
@Description("The build type of project to create. "
+ "Valid values are maven or gradle. Default: gradle")
public Build build();
@Description("The directory where to create the new project.")
public File dir();
@Description("The type of IDE metadata to create along side "
+ "the new project.")
public IDE ide();
@Description("The type of Liferay module to create. ")
public Type projectType();
@Description("The version of Liferay to create the module for, "
+ "by default its 7.0.0")
public Version version();
} |
Disable adding registries for non-superusers | from django.contrib import admin
from models import *
from registry.groups.models import User
class SectionAdmin(admin.ModelAdmin):
list_display = ('code', 'display_name')
class RegistryFormAdmin(admin.ModelAdmin):
list_display = ('registry', 'name', 'sections')
class RegistryAdmin(admin.ModelAdmin):
def queryset(self, request):
if not request.user.is_superuser:
user = User.objects.get(user=request.user)
return Registry.objects.filter(registry__in=[reg.id for reg in user.registry.all()])
return Registry.objects.all()
def has_add_permission(self, request):
if request.user.is_superuser:
return True
return False
admin.site.register(CDEPermittedValue)
admin.site.register(CDEPermittedValueGroup)
admin.site.register(CommonDataElement)
admin.site.register(Wizard)
admin.site.register(RegistryForm, RegistryFormAdmin)
admin.site.register(Section, SectionAdmin)
admin.site.register(Registry, RegistryAdmin) | from django.contrib import admin
from models import *
from registry.groups.models import User
class SectionAdmin(admin.ModelAdmin):
list_display = ('code', 'display_name')
class RegistryFormAdmin(admin.ModelAdmin):
list_display = ('registry', 'name', 'sections')
class RegistryAdmin(admin.ModelAdmin):
def queryset(self, request):
if not request.user.is_superuser:
user = User.objects.get(user=request.user)
return Registry.objects.filter(registry__in=[reg.id for reg in user.registry.all()])
return Registry.objects.all()
admin.site.register(CDEPermittedValue)
admin.site.register(CDEPermittedValueGroup)
admin.site.register(CommonDataElement)
admin.site.register(Wizard)
admin.site.register(RegistryForm, RegistryFormAdmin)
admin.site.register(Section, SectionAdmin)
admin.site.register(Registry, RegistryAdmin) |
Fix a bug with the print_files output function | <!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Gificiency</title>
<link href="http://fonts.googleapis.com/css?family=Roboto:100" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="assets/stylesheets/gificiency.css">
</head>
<body class="cell">
<form class="form" action="">
<input type="text" name="search" placeholder="Search..." class="search" />
</form>
<ul class="links">
<? require_once 'lib/gificiency.php'; ?>
<? if ($env == 'development'): ?>
<? require_once 'lib/seeds.php'; ?>
<? else: ?>
<?= print_files($url, $dir); ?>
<? endif; ?>
</ul>
<script src="http://code.jquery.com/jquery-1.10.0.min.js" type="text/javascript"></script>
<script src="assets/javascripts/vendor/underscore.min.js" type="text/javascript"></script>
<script src="assets/javascripts/gificiency.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
new Gificiency({
searchField: $('.search'),
items: $('.links li'),
links: $('.link')
});
});
</script>
</body>
</html>
| <!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Gificiency</title>
<link href="http://fonts.googleapis.com/css?family=Roboto:100" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="assets/stylesheets/gificiency.css">
</head>
<body class="cell">
<form class="form" action="">
<input type="text" name="search" placeholder="Search..." class="search" />
</form>
<ul class="links">
<?php require_once 'lib/gificiency.php'; ?>
<?php if ($env == 'development'): ?>
<?php require_once 'lib/seeds.php'; ?>
<?php else: ?>
print_files($url, $dir);
<?php endif; ?>
</ul>
<script src="http://code.jquery.com/jquery-1.10.0.min.js" type="text/javascript"></script>
<script src="assets/javascripts/vendor/underscore.min.js" type="text/javascript"></script>
<script src="assets/javascripts/gificiency.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
new Gificiency({
searchField: $('.search'),
items: $('.links li'),
links: $('.link')
});
});
</script>
</body>
</html>
|
Add load command to help instructions | <?php
namespace PhunkieConsole\Command;
use Phunkie\Types\Pair;
use function PhunkieConsole\IO\Colours\colours;
use PhunkieConsole\Result\PrintableResult;
class HelpCommand
{
private $input;
public function __construct(string $input)
{
$this->input = $input;
}
public function run($state): Pair
{
return Pair($state, Nel(Success(new PrintableResult(Pair(None,
colours()['green'](" Commands available from the prompt\n").
" :import <module> loads module(s) and their dependents\n".
" :help, :h, :? displays this list of commands\n".
" :exit exits the application\n".
" :type <expr>, :t display the type of an expression\n".
" :kind <type>, :k display the kind of a type\n" .
" :load <file>, :l loads a php file\n")))));
}
} | <?php
namespace PhunkieConsole\Command;
use Phunkie\Types\Pair;
use function PhunkieConsole\IO\Colours\colours;
use PhunkieConsole\Result\PrintableResult;
class HelpCommand
{
private $input;
public function __construct(string $input)
{
$this->input = $input;
}
public function run($state): Pair
{
return Pair($state, Nel(Success(new PrintableResult(Pair(None,
colours()['green'](" Commands available from the prompt\n").
" :import <module> loads module(s) and their dependents\n".
" :help, :h, :? displays this list of commands\n".
" :exit exits the application\n".
" :type <expr>, :t display the type of an expression\n".
" :kind <type>, :k display the kind of a type\n")))));
}
} |
Add theme color meta tags for mobile browsers & IE9 | var webpack = require("webpack");
module.exports = {
resolve: true,
html: {
template: "./src/templates/index.html",
title: "Kakimasu",
baseURL: "https://kakimasu.rakujira.jp",
description: "Learn to write Japanese Hiragana and Katakana!",
creator: "@rakujira",
webfontFamilies: "Poppins:600:latin",
meta: {
"theme-color": "#88cdf1",
"msapplication-navbutton-color": "#88cdf1"
}
},
webpack(config) {
config.module.loaders = [({ test: /\.json$/, loader: "json-loader" })];
config.plugins.push(new webpack.BannerPlugin({
banner: [
"kakimasu.rakujira.jp",
"--------------------",
"Author: James Daniel (github.com/jaames | rakujira.jp | @rakujira)",
"Build hash: [hash]",
"Chunk hash: [chunkhash]",
"Last updated: " + new Date().toDateString(),
].join("\n")
}));
return config;
}
}
| var webpack = require("webpack");
module.exports = {
resolve: true,
html: {
template: "./src/templates/index.html",
title: "Kakimasu",
baseURL: "https://kakimasu.rakujira.jp",
description: "Learn to write Japanese Hiragana and Katakana!",
creator: "@rakujira",
webfontFamilies: "Poppins:600:latin"
},
webpack(config) {
config.module.loaders = [({ test: /\.json$/, loader: "json-loader" })];
config.plugins.push(new webpack.BannerPlugin({
banner: [
"kakimasu.rakujira.jp",
"--------------------",
"Author: James Daniel (github.com/jaames | rakujira.jp | @rakujira)",
"Build hash: [hash]",
"Chunk hash: [chunkhash]",
"Last updated: " + new Date().toDateString(),
].join("\n")
}));
return config;
}
}
|
Remove useless code from the home view | from django.db.models import Count
from django.shortcuts import render
from django.views.generic import TemplateView
from django.views.generic.base import ContextMixin
from meupet import models
def get_adoption_kinds():
return get_kind_list([models.Pet.FOR_ADOPTION, models.Pet.ADOPTED])
def get_lost_kinds():
return get_kind_list([models.Pet.MISSING, models.Pet.FOUND])
def get_kind_list(status):
return models.Kind.objects.filter(pet__status__in=status).annotate(num_pets=Count('pet')).order_by('kind')
class MeuPetEspecieMixin(ContextMixin):
def get_context_data(self, **kwargs):
context = super(MeuPetEspecieMixin, self).get_context_data(**kwargs)
context['kind_lost'] = get_lost_kinds()
context['kind_adoption'] = get_adoption_kinds()
return context
class AboutPageView(MeuPetEspecieMixin, TemplateView):
template_name = 'staticpages/about.html'
class AssociacoesView(MeuPetEspecieMixin, TemplateView):
template_name = 'staticpages/associacoes.html'
def not_found(request):
return render(request, 'staticpages/404.html')
def home(request):
return render(request, 'common/home.html')
| from django.db.models import Count
from django.shortcuts import render
from django.views.generic import TemplateView
from django.views.generic.base import ContextMixin
from meupet import models
def get_adoption_kinds():
return get_kind_list([models.Pet.FOR_ADOPTION, models.Pet.ADOPTED])
def get_lost_kinds():
return get_kind_list([models.Pet.MISSING, models.Pet.FOUND])
def get_kind_list(status):
return models.Kind.objects.filter(pet__status__in=status).annotate(num_pets=Count('pet')).order_by('kind')
class MeuPetEspecieMixin(ContextMixin):
def get_context_data(self, **kwargs):
context = super(MeuPetEspecieMixin, self).get_context_data(**kwargs)
context['kind_lost'] = get_lost_kinds()
context['kind_adoption'] = get_adoption_kinds()
return context
class AboutPageView(MeuPetEspecieMixin, TemplateView):
template_name = 'staticpages/about.html'
class AssociacoesView(MeuPetEspecieMixin, TemplateView):
template_name = 'staticpages/associacoes.html'
def not_found(request):
return render(request, 'staticpages/404.html')
def home(request):
pets = models.Pet.objects.select_related('city').order_by('-id')[:6]
return render(request, 'common/home.html', {'pets': pets})
|
Adjust displaying Dribbble on template | (function() {
if ($('body').hasClass('home-template')) {
var DRIBBBLE_API_TOKEN = '2982b6f5520299137430aac46d2532cc3b00583ff8c39378471b5e5cf6117c61';
$.get('https://api.dribbble.com/v1/users/tylerpearson/shots?access_token=' + DRIBBBLE_API_TOKEN)
.then(function(shots) {
var html = [];
for (var i=0; i<10; i++) {
var shot = shots[i];
html.push('<li class="shot-wrap" style="background-image: url(' + shot.images.normal + ');">');
html.push('<a href="' + shot.html_url + '">' + shot.title + '</a>');
html.push('</li>');
}
$('.js-dribbble-list').html(html.join(''));
});
}
}());
| (function() {
var DRIBBBLE_API_TOKEN = '2982b6f5520299137430aac46d2532cc3b00583ff8c39378471b5e5cf6117c61';
$.get('https://api.dribbble.com/v1/users/tylerpearson/shots?access_token=' + DRIBBBLE_API_TOKEN)
.then(function(shots) {
var html = [];
for (var i=0; i<10; i++) {
var shot = shots[i];
html.push('<li class="shot-wrap" style="background-image: url(' + shot.images.normal + ');">');
html.push('<a href="' + shot.html_url + '">' + shot.title + '</a>');
html.push('</li>');
}
console.log(shots.length);
$('.js-dribbble-list').html(html.join(''));
});
}());
|
Remove NA values from export. | from __future__ import print_function
class Exporter():
def __init__(self, plotinfo, viewbox):
self.plotinfo = plotinfo
self.viewbox = viewbox
def updaterange(self):
datalen = self.plotinfo.plotdata.shape[0]
vbrange = self.viewbox.viewRange()
xmin,xmax = vbrange[0]
if xmin <= 0: xmin = 0
if xmax >= datalen: xmax = datalen
self.xmax, self.xmin = int(xmax), int(xmin)
def tocsv(self, filename):
self.updaterange()
data = self.plotinfo.plotdata.iloc[self.xmin : self.xmax]
datanona = data.dropna(how = 'all', subset = self.plotinfo.yfields)
datanona.to_csv(filename, index = False)
| from __future__ import print_function
class Exporter():
def __init__(self, plotinfo, viewbox):
self.plotinfo = plotinfo
self.viewbox = viewbox
def updaterange(self):
datalen = self.plotinfo.plotdata.shape[0]
vbrange = self.viewbox.viewRange()
xmin,xmax = vbrange[0]
if xmin <= 0: xmin = 0
if xmax >= datalen: xmax = datalen
self.xmax, self.xmin = int(xmax), int(xmin)
def tocsv(self, filename):
self.updaterange()
data = self.plotinfo.plotdata.iloc[self.xmin : self.xmax]
data.to_csv(filename, index = False)
|
Add /h2-console to security ADMIN role
- /h2-console was inadvertently shut out when security was added | package io.github.jordao76.quotes.web;
import static org.springframework.http.HttpMethod.*;
import org.springframework.context.annotation.*;
import org.springframework.security.config.annotation.authentication.builders.*;
import org.springframework.security.config.annotation.web.builders.*;
import org.springframework.security.config.annotation.web.configuration.*;
@Configuration
@EnableWebSecurity
public class QuoteSecurity extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.headers().frameOptions().disable()
.and().httpBasic()
.and().authorizeRequests()
.antMatchers(GET, "/quotes/**").permitAll()
.antMatchers(DELETE, "/quotes/**").hasRole("MAINTAINER")
.antMatchers(POST, "/quotes").hasRole("MAINTAINER")
.antMatchers("/manage/**", "/h2-console/**").hasRole("ADMIN")
.antMatchers("/**").denyAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("admin")
.password("password")
.roles("MAINTAINER", "ADMIN");
}
}
| package io.github.jordao76.quotes.web;
import static org.springframework.http.HttpMethod.*;
import org.springframework.context.annotation.*;
import org.springframework.security.config.annotation.authentication.builders.*;
import org.springframework.security.config.annotation.web.builders.*;
import org.springframework.security.config.annotation.web.configuration.*;
@Configuration
@EnableWebSecurity
public class QuoteSecurity extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers(GET, "/quotes/**").permitAll()
.antMatchers(DELETE, "/quotes/**").hasRole("MAINTAINER")
.antMatchers(POST, "/quotes").hasRole("MAINTAINER")
.antMatchers("/manage/**").hasRole("ADMIN")
.antMatchers("/**").denyAll()
.and()
.httpBasic();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("admin")
.password("password")
.roles("MAINTAINER", "ADMIN");
}
}
|
[IMP] Move maintainer key out of the manifest | # -*- coding: utf-8 -*-
#
##############################################################################
#
# Authors: Adrien Peiffer
# Copyright (c) 2014 Acsone SA/NV (http://www.acsone.eu)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
"name": "Account Payment Draft Move",
"version": "1.0",
"author": "ACSONE SA/NV",
"website": "http://www.acsone.eu",
"images": [],
"category": "Accounting",
"depends": ["account_banking_payment_export"],
"data": [],
"demo": [],
"test": [],
"licence": "AGPL-3",
"installable": True,
"active": False,
}
| # -*- coding: utf-8 -*-
#
##############################################################################
#
# Authors: Adrien Peiffer
# Copyright (c) 2014 Acsone SA/NV (http://www.acsone.eu)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
"name": "Account Payment Draft Move",
"version": "1.0",
"author": "ACSONE SA/NV",
"maintainer": "ACSONE SA/NV",
"website": "http://www.acsone.eu",
"images": [],
"category": "Accounting",
"depends": ["account_banking_payment_export"],
"data": [],
"demo": [],
"test": [],
"licence": "AGPL-3",
"installable": True,
"active": False,
}
|
Add source map to get prettier stacktrace. | const path = require('path')
// eslint-disable-next-line import/no-unresolved
const slsw = require('serverless-webpack')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const addBabelPolyfill = (slsEntries) => {
return Object.keys(slsEntries)
.reduce((acc, key) => Object.assign(acc, {
[key]: ['babel-polyfill', 'source-map-support/register', slsEntries[key]]
}), {})
}
module.exports = {
entry: addBabelPolyfill(slsw.lib.entries),
target: 'node',
devtool: 'source-map',
module: {
loaders: [{
test: /\.js$/,
loaders: ['babel-loader'],
include: __dirname,
exclude: /node_modules/
}]
},
output: {
libraryTarget: 'commonjs',
path: path.join(__dirname, '.webpack'),
filename: '[name].js'
},
externals: [
'aws-sdk'
],
plugins: [
new CopyWebpackPlugin([
{ from: '.serverless-secret.json' }
])
]
}
| const path = require('path')
// eslint-disable-next-line import/no-unresolved
const slsw = require('serverless-webpack')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const addBabelPolyfill = (slsEntries) => {
return Object.keys(slsEntries)
.reduce((acc, key) => Object.assign(acc, {
[key]: ['babel-polyfill', slsEntries[key]]
}), {})
}
module.exports = {
entry: addBabelPolyfill(slsw.lib.entries),
target: 'node',
module: {
loaders: [{
test: /\.js$/,
loaders: ['babel-loader'],
include: __dirname,
exclude: /node_modules/
}]
},
output: {
libraryTarget: 'commonjs',
path: path.join(__dirname, '.webpack'),
filename: '[name].js'
},
externals: [
'aws-sdk'
],
plugins: [
new CopyWebpackPlugin([
{ from: '.serverless-secret.json' }
])
]
}
|
Rename service view in controller | <?php
namespace App\Core\Controller;
use App\Core\DependencyInjection\ContainerAware;
use App\Core\DependencyInjection\ContainerInterface;
use App\Libs\Redirection;
use App\Libs\Flash;
class Controller extends ContainerAware
{
protected $view;
protected $redirect;
/**
* In order to resolve Model
* @var ModelResolver
*/
protected $model;
protected $flash;
public function __construct(ContainerInterface $container)
{
$this->setContainer($container);
$this->view = $this->container->resolve('ViewInterface');
$this->redirect = $this->container->resolve('Redirection');
$this->view->setDirectoryPath('app/View/');
$this->model = $this->container->resolve('ModelResolver');
$this->flash = $this->container->resolve('Flash');
}
/**
* Check if the request is an AJAX request
* @return boolean [description]
*/
public function isAjax()
{
return strtolower(filter_input(INPUT_SERVER, 'HTTP_X_REQUESTED_WITH')) === 'xmlhttprequest';
}
}
| <?php
namespace App\Core\Controller;
use App\Core\DependencyInjection\ContainerAware;
use App\Core\DependencyInjection\ContainerInterface;
use App\Libs\Redirection;
use App\Libs\Flash;
class Controller extends ContainerAware
{
protected $view;
protected $redirect;
/**
* In order to resolve Model
* @var ModelResolver
*/
protected $model;
protected $flash;
public function __construct(ContainerInterface $container)
{
$this->setContainer($container);
$this->view = $this->container->resolve('View');
$this->redirect = $this->container->resolve('Redirection');
$this->view->setDirectoryPath('app/View/');
$this->model = $this->container->resolve('ModelResolver');
$this->flash = $this->container->resolve('Flash');
}
/**
* Check if the request is an AJAX request
* @return boolean [description]
*/
public function isAjax()
{
return strtolower(filter_input(INPUT_SERVER, 'HTTP_X_REQUESTED_WITH')) === 'xmlhttprequest';
}
}
|
Make sure to update the test script | import { terser } from 'rollup-plugin-terser'
import pkg from './package.json'
import { nodeResolve } from '@rollup/plugin-node-resolve'
import commonjs from '@rollup/plugin-commonjs'
const umd = { format: 'umd', name: 'A11yDialog', exports: 'default' }
const es = { format: 'es' }
const minify = {
plugins: [terser()],
banner: () => `/*! a11y-dialog ${pkg.version} — © Kitty Giraudel */`,
}
export default {
input: 'a11y-dialog.js',
output: [
// Main files
{ file: 'dist/a11y-dialog.js', ...umd },
{ file: 'dist/a11y-dialog.esm.js', ...es },
// Minified versions
{ file: 'dist/a11y-dialog.min.js', ...umd, ...minify },
{ file: 'dist/a11y-dialog.esm.min.js', ...es, ...minify },
// Test version
{ file: 'cypress/fixtures/a11y-dialog.js', ...umd },
],
plugins: [nodeResolve(), commonjs({ include: 'node_modules/**' })],
}
| import { terser } from 'rollup-plugin-terser'
import pkg from './package.json'
import { nodeResolve } from '@rollup/plugin-node-resolve'
import commonjs from '@rollup/plugin-commonjs'
const umd = { format: 'umd', name: 'A11yDialog', exports: 'default' }
const es = { format: 'es' }
const minify = {
plugins: [terser()],
banner: () => `/*! a11y-dialog ${pkg.version} — © Kitty Giraudel */`,
}
export default {
input: 'a11y-dialog.js',
output: [
// Main files
{ file: 'dist/a11y-dialog.js', ...umd },
{ file: 'dist/a11y-dialog.esm.js', ...es },
// Minified versions
{ file: 'dist/a11y-dialog.min.js', ...umd, ...minify },
{ file: 'dist/a11y-dialog.esm.min.js', ...es, ...minify },
],
plugins: [nodeResolve(), commonjs({ include: 'node_modules/**' })],
}
|
Throw exception if topic cannot be found. | <?php
namespace FluxBB\Controllers;
use FluxBB\Models\Post;
use FluxBB\Repositories\Topics;
use FluxBB\Services\CreateReply;
use FluxBB\Services\CreateReplyObserver;
use Illuminate\Support\MessageBag;
use Auth;
use Input;
use Redirect;
class PostsController extends BaseController implements
CreateReplyObserver
{
public function postReply($tid)
{
$topic = $this->topics->findOrFail($tid);
$service = new CreateReply($this, $this->topics);
return $service->createReply($topic, Auth::user(), Input::get('req_message'));
}
public function replyCreated(Post $post)
{
return Redirect::route('viewpost', array('id' => $post->id));
}
public function replyValidationFailed(Post $post, MessageBag $errors)
{
return Redirect::route('posting@reply', array($post->topic_id))
->withInput()
->withErrors($errors);
}
}
| <?php
namespace FluxBB\Controllers;
use FluxBB\Models\Post;
use FluxBB\Repositories\Topics;
use FluxBB\Services\CreateReply;
use FluxBB\Services\CreateReplyObserver;
use Illuminate\Support\MessageBag;
use Auth;
use Input;
use Redirect;
class PostsController extends BaseController implements
CreateReplyObserver
{
public function postReply($tid)
{
$topic = $this->topics->find($tid); // TODO: 404?
$service = new CreateReply($this, $this->topics);
return $service->createReply($topic, Auth::user(), Input::get('req_message'));
}
public function replyCreated(Post $post)
{
return Redirect::route('viewpost', array('id' => $post->id));
}
public function replyValidationFailed(Post $post, MessageBag $errors)
{
return Redirect::route('posting@reply', array($post->topic_id))
->withInput()
->withErrors($errors);
}
}
|
Abort logs screens when logs are disabled | <?php
namespace Sebastienheyd\Boilerplate\Controllers\Logs;
use Arcanedev\LogViewer\Contracts\LogViewer as LogViewerContract;
use Arcanedev\LogViewer\Http\Controllers\LogViewerController as ArcanedevController;
class LogViewerController extends ArcanedevController
{
/**
* LogViewerController constructor.
*
* @param LogViewerContract $logViewer
*/
public function __construct(LogViewerContract $logViewer)
{
$this->middleware('ability:admin,logs');
if (!config('boilerplate.app.logs')) {
abort('404');
}
parent::__construct($logViewer);
}
protected $showRoute = 'boilerplate.logs.show';
/**
* @param string $view
* @param array $data
* @param array $mergeData
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
protected function view($view, $data = [], $mergeData = [])
{
return view('boilerplate::logs.'.$view, $data, $mergeData);
}
}
| <?php
namespace Sebastienheyd\Boilerplate\Controllers\Logs;
use Arcanedev\LogViewer\Contracts\LogViewer as LogViewerContract;
use Arcanedev\LogViewer\Http\Controllers\LogViewerController as ArcanedevController;
class LogViewerController extends ArcanedevController
{
/**
* LogViewerController constructor.
*
* @param LogViewerContract $logViewer
*/
public function __construct(LogViewerContract $logViewer)
{
$this->middleware('ability:admin,logs');
parent::__construct($logViewer);
}
protected $showRoute = 'boilerplate.logs.show';
/**
* @param string $view
* @param array $data
* @param array $mergeData
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
protected function view($view, $data = [], $mergeData = [])
{
return view('boilerplate::logs.'.$view, $data, $mergeData);
}
}
|
Move logging above asset serving | var coffee = require('coffee-script/register'),
express = require('express'),
assets = require('connect-assets'),
logfmt = require('logfmt'),
app = express();
var port = Number(process.env.PORT || 1337);
app.use(logfmt.requestLogger());
app.set('views', 'src/views');
app.set('view engine', 'jade');
require('./routes')(app);
assets = assets({
paths: [
'src/scripts',
'src/images',
'src/stylesheets',
'src/views',
'bower_components'
],
buildDir: 'dist',
gzip: true
});
assets.mincer.MacroProcessor.configure(['.js']);
app.use(assets);
app.listen(port);
console.log('Listening on port: ' + port);
| var coffee = require('coffee-script/register'),
express = require('express'),
assets = require('connect-assets'),
logfmt = require('logfmt'),
app = express();
var port = Number(process.env.PORT || 1337);
app.set('views', 'src/views');
app.set('view engine', 'jade');
require('./routes')(app);
assets = assets({
paths: [
'src/scripts',
'src/images',
'src/stylesheets',
'src/views',
'bower_components'
],
buildDir: 'dist',
gzip: true
});
assets.mincer.MacroProcessor.configure(['.js']);
app.use(assets);
app.use(logfmt.requestLogger());
app.listen(port);
console.log('Listening on port: ' + port);
|
Return file with correct mimetype | from flask import Flask, request, send_file
import json
from src.generate import generate
app = Flask(__name__)
available_settings = ['grammarTitle', 'grammarSubtitle', 'author', 'format',
'theme']
@app.route('/', methods=['POST'])
def index():
# Get all available string settings from posted object
settings = {}
for key in available_settings:
settings[key] = request.form.get(key, None)
# Loop through the files posted to the endpoint, reading all
# files as strings.
markdown_file_strings = []
lexicon_file_string = None
for filename, blob in request.files.items():
if filename.endswith('.csv'):
lexicon_file_string = str(blob.read(), 'utf-8')
else:
markdown_file_strings.append(str(blob.read(), 'utf-8'))
print(markdown_file_strings)
filename = generate(markdown_file_strings, lexicon_file_string, settings)
return filename
@app.route('/download')
def download():
filename = request.args.get('filename')
print('Received request with filename {0}'.format(filename))
if filename.endswith('.md'):
mimetype = 'text/markdown'
return send_file(filename, mimetype=mimetype)
if __name__ == '__main__':
app.run(debug=True)
| from flask import Flask, request, send_file
import json
from src.generate import generate
app = Flask(__name__)
available_settings = ['grammarTitle', 'grammarSubtitle', 'author', 'format',
'theme']
@app.route('/', methods=['POST'])
def index():
# Get all available string settings from posted object
settings = {}
for key in available_settings:
settings[key] = request.form.get(key, None)
# Loop through the files posted to the endpoint, reading all
# files as strings.
markdown_file_strings = []
lexicon_file_string = None
for filename, blob in request.files.items():
if filename.endswith('.csv'):
lexicon_file_string = str(blob.read(), 'utf-8')
else:
markdown_file_strings.append(str(blob.read(), 'utf-8'))
print(markdown_file_strings)
filename = generate(markdown_file_strings, lexicon_file_string, settings)
return filename
@app.route('/download')
def download():
filename = request.args.get('filename')
return send_file(filename)
if __name__ == '__main__':
app.run(debug=True)
|
Tweak connection data for pgsql instead of mysql | <?php
use Illuminate\Database\Capsule\Manager as Capsule;
class Bootstrap {
function boot()
{
$capsule = new Capsule;
$capsule->addConnection(array(
'driver' => 'pgsql',
'host' => 'localhost',
'database' => 'liquid_feedback',
'username' => 'www-data',
'password' => '',
'charset' => 'utf8',
'prefix' => '',
'schema' => 'public'
));
$capsule->bootEloquent();
return null;
}
} | <?php
use Illuminate\Database\Capsule\Manager as Capsule;
class Bootstrap {
function boot()
{
$capsule = new Capsule;
$capsule->addConnection(array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'wordpress',
'username' => 'username',
'password' => 'password',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => ''
));
$capsule->bootEloquent();
return null;
}
} |
Remove config prefix as we are only using single file configuration
Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com> | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Config;
use Orchestra\Story\Model\Content;
class OrchestraStoryMakeContentsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
$format = Config::get('orchestra/story::default_format', 'markdown');
Schema::create('story_contents', function ($table) use ($format)
{
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('slug');
$table->string('title');
$table->text('content');
$table->string('format')->default($format);
$table->string('type')->default(Content::POST);
$table->string('status')->default(Content::STATUS_DRAFT);
$table->timestamps();
$table->datetime('published_at');
$table->softDeletes();
$table->index('user_id');
$table->index('slug');
$table->index('format');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('story_contents');
}
}
| <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Config;
use Orchestra\Story\Model\Content;
class OrchestraStoryMakeContentsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
$format = Config::get('orchestra/story::config.default_format', 'markdown');
Schema::create('story_contents', function ($table) use ($format)
{
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('slug');
$table->string('title');
$table->text('content');
$table->string('format')->default($format);
$table->string('type')->default(Content::POST);
$table->string('status')->default(Content::STATUS_DRAFT);
$table->timestamps();
$table->datetime('published_at');
$table->softDeletes();
$table->index('user_id');
$table->index('slug');
$table->index('format');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('story_contents');
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.