text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Integrate answers with Flask frontend | import random
import json
from flask import Flask, render_template, abort, redirect, request
app = Flask(__name__)
questions = [{
'question': 'How many shillings were there in a pre-decimalisation pound?',
'answer': '20',
'red_herrings': [
'5',
'10',
'12',
'25',
'50',
'120',
]
}] + json.load(open('disney_answers.json'))
@app.route('/')
def index():
q = random.randint(0, len(questions) - 1)
return redirect('/q/%d/' % q)
@app.route('/a/<int:id>/')
def answer(id):
try:
question = questions[id]
except IndexError:
abort(404)
answer = request.args['a']
return render_template(
'answer.html', question=question,
given=answer,
is_correct=(answer == question['answer'])
)
@app.route('/q/<int:id>/')
def question(id):
try:
question = questions[id]
except IndexError:
abort(404)
red_herrings = random.sample(question['red_herrings'], 3)
answers = red_herrings + [question['answer']]
random.shuffle(answers)
return render_template(
'question.html',
id=id,
question=question['question'],
answers=answers
)
if __name__ == '__main__':
app.run(debug=True)
| import random
from flask import Flask, render_template, abort, redirect, request
app = Flask(__name__)
questions = [{
'question': 'How many shillings were there in a pre-decimalisation pound?',
'answer': '20',
'red_herrings': [
'5',
'10',
'12',
'25',
'50',
'120',
]
}]
@app.route('/')
def index():
q = random.randint(0, len(questions) - 1)
return redirect('/q/%d/' % q)
@app.route('/a/<int:id>/')
def answer(id):
try:
question = questions[id]
except IndexError:
abort(404)
answer = request.args['a']
return render_template(
'answer.html', question=question,
given=answer,
is_correct=(answer == question['answer'])
)
@app.route('/q/<int:id>/')
def question(id):
try:
question = questions[id]
except IndexError:
abort(404)
red_herrings = random.sample(question['red_herrings'], 3)
answers = red_herrings + [question['answer']]
random.shuffle(answers)
return render_template(
'question.html',
id=id,
question=question['question'],
answers=answers
)
if __name__ == '__main__':
app.run(debug=True)
|
Fix an issue with the child-task selector. | import logging
from tukio import Workflow
from tukio.task import register
from tukio.task.holder import TaskHolder
from nyuki.utils.evaluate import ConditionBlock
from nyuki.workflow.tasks.utils import generate_schema
log = logging.getLogger(__name__)
class TaskConditionBlock(ConditionBlock):
"""
Overrides work on ConditionBlock from the factory task to
set next workflow tasks.
"""
def __init__(self, conditions, workflow):
super().__init__(conditions)
self._workflow = workflow
def condition_validated(self, condition, data):
"""
Set next workflow tasks upon validating a condition.
"""
if condition['rules']:
self._workflow.set_next_tasks(condition['rules'][0]['tasks'])
@register('task_selector', 'execute')
class TaskSelector(TaskHolder):
SCHEMA = generate_schema(tasks={
'type': 'object',
'properties': {
'type': {'type': 'string', 'enum': ['task-selector']},
'tasks': {
'type': 'array',
'items': {
'type': 'string',
'minLength': 1,
'uniqueItems': True
}
}
}
})
async def execute(self, event):
data = event.data
workflow = Workflow.current_workflow()
for block in self.config['rules']:
if block['type'] == 'task-selector':
workflow.set_next_tasks(block['tasks'])
elif block['type'] == 'condition-block':
TaskConditionBlock(block['conditions'], workflow).apply(data)
return data
| import logging
from tukio import Workflow
from tukio.task import register
from tukio.task.holder import TaskHolder
from nyuki.utils.evaluate import ConditionBlock
from nyuki.workflow.tasks.utils import generate_schema
log = logging.getLogger(__name__)
class TaskConditionBlock(ConditionBlock):
"""
Overrides work on ConditionBlock from the factory task to
set next workflow tasks.
"""
def __init__(self, conditions, workflow):
super().__init__(conditions)
self._workflow = workflow
def condition_validated(self, condition, data):
"""
Set next workflow tasks upon validating a condition.
"""
self._workflow.set_next_tasks(condition['tasks'])
@register('task_selector', 'execute')
class TaskSelector(TaskHolder):
SCHEMA = generate_schema(tasks={
'type': 'object',
'properties': {
'type': {'type': 'string', 'enum': ['task-selector']},
'tasks': {
'type': 'array',
'items': {
'type': 'string',
'minLength': 1,
'uniqueItems': True
}
}
}
})
async def execute(self, event):
data = event.data
workflow = Workflow.current_workflow()
for block in self.config['rules']:
if block['type'] == 'task-selector':
workflow.set_next_tasks(block['tasks'])
elif block['type'] == 'condition-block':
TaskConditionBlock(block['conditions'], workflow).apply(data)
return data
|
Use window.location.protocol instead of hardcoded one | $(function() {
/*
* Functions
**/
// Function to clear the table and insert a specific placeholder
var insertPlaceholder = function(msg) {
$('table.certificates tbody').html(
'<tr>' +
'<td colspan="6"><center>' + msg + '</center></td>' +
'</tr>'
);
};
// Reload certificates and populate table
var reloadCertificates = function() {
insertPlaceholder('loading ...');
$.ajax({
type: 'GET'
, url: window.location.protocol + '//' + window.location.host + '/api/certificates'
, cache: false
, success: function(data) {
// Clear placeholder
$('table.certificates tbody').html('');
// Populate <ul> with host <li>'s
data.data.hosts.forEach(function(certificate) {
$('table.certificates tbody').append(
'<tr>' +
'<th scope="row">' + certificate.id + '</th>' +
'<td>' + certificate.hostname + '</td>' +
'<td>' + certificate.expiration + '</td>' +
'<td>' + certificate.customer + ' (#300123)</td>' +
'<td>' + certificate.usage + '</td>' +
'<td><button disabled type="button" class="btn btn-xs btn-default"><span class="glyphicon glyphicon-pencil"></span></button> <button disabled type="button" class="btn btn-xs btn-danger"><span class="glyphicon glyphicon-minus"></span></button></td>' +
'</tr>'
);
});
}
});
};
/*
* Main
**/
// Call reloadCertificates()
reloadCertificates();
});
| $(function() {
/*
* Functions
**/
// Function to clear the table and insert a specific placeholder
var insertPlaceholder = function(msg) {
$('table.certificates tbody').html(
'<tr>' +
'<td colspan="6"><center>' + msg + '</center></td>' +
'</tr>'
);
};
// Reload certificates and populate table
var reloadCertificates = function() {
insertPlaceholder('loading ...');
$.ajax({
type: 'GET'
, url: 'http://' + window.location.host + '/api/certificates'
, cache: false
, success: function(data) {
// Clear placeholder
$('table.certificates tbody').html('');
// Populate <ul> with host <li>'s
data.data.hosts.forEach(function(certificate) {
$('table.certificates tbody').append(
'<tr>' +
'<th scope="row">' + certificate.id + '</th>' +
'<td>' + certificate.hostname + '</td>' +
'<td>' + certificate.expiration + '</td>' +
'<td>' + certificate.customer + ' (#300123)</td>' +
'<td>' + certificate.usage + '</td>' +
'<td><button disabled type="button" class="btn btn-xs btn-default"><span class="glyphicon glyphicon-pencil"></span></button> <button disabled type="button" class="btn btn-xs btn-danger"><span class="glyphicon glyphicon-minus"></span></button></td>' +
'</tr>'
);
});
}
});
};
/*
* Main
**/
// Call reloadCertificates()
reloadCertificates();
});
|
Fix error on starting sample site | package io.sitoolkit.wt.gui.domain.sample;
import java.io.File;
import io.sitoolkit.util.buidtoolhelper.maven.MavenProject;
import io.sitoolkit.util.buidtoolhelper.process.ProcessCommand;
import io.sitoolkit.util.buidtoolhelper.process.ProcessExitCallback;
import io.sitoolkit.wt.util.infra.concurrent.ExecutorContainer;
public class SampleProcessClient {
public SampleProcessClient() {
}
/**
* 次のコマンドを実行します。
*
* <pre>
* mvn
* </pre>
*
*/
public void start(File sampleDir, SampleStartedCallback callback) {
JettyMavenPluginStdoutListener listener = new JettyMavenPluginStdoutListener();
MavenProject.load(sampleDir.toPath()).mvnw().stdout(listener).executeAsync();
ExecutorContainer.get().execute(() -> {
callback.onStarted(listener.isSuccess());
});
}
/**
* 次のコマンドを実行します。
*
* <pre>
* mvn jetty:stop
* </pre>
*
*/
public void stop(File sampleDir, ProcessExitCallback callback) {
ProcessCommand cmd = MavenProject.load(sampleDir.toPath()).mvnw("jetty:stop");
if (callback != null)
cmd.getExitCallbacks().add(callback);
cmd.executeAsync();
}
}
| package io.sitoolkit.wt.gui.domain.sample;
import java.io.File;
import io.sitoolkit.util.buidtoolhelper.maven.MavenProject;
import io.sitoolkit.util.buidtoolhelper.process.ProcessCommand;
import io.sitoolkit.util.buidtoolhelper.process.ProcessExitCallback;
import io.sitoolkit.wt.util.infra.concurrent.ExecutorContainer;
public class SampleProcessClient {
public SampleProcessClient() {
}
/**
* 次のコマンドを実行します。
*
* <pre>
* mvn
* </pre>
*
*/
public void start(File sampleDir, SampleStartedCallback callback) {
JettyMavenPluginStdoutListener listener = new JettyMavenPluginStdoutListener();
MavenProject
.load(sampleDir.toPath())
.mvnw("")
.stdout(listener)
.executeAsync();
ExecutorContainer.get().execute(() -> {
callback.onStarted(listener.isSuccess());
});
}
/**
* 次のコマンドを実行します。
*
* <pre>
* mvn jetty:stop
* </pre>
*
*/
public void stop(File sampleDir, ProcessExitCallback callback) {
ProcessCommand cmd = MavenProject
.load(sampleDir.toPath())
.mvnw("jetty:stop");
if (callback != null)
cmd.getExitCallbacks().add(callback);
cmd.executeAsync();
}
}
|
Set `zip_safe` to false so that we can install pygrow from source. | from pip import req
import pip
from setuptools import find_packages
from setuptools import setup
_install_requirements = req.parse_requirements(
'requirements.txt', session=pip.download.PipSession())
setup(
name='grow',
version=open('grow/VERSION').read().strip(),
description=(
'Develop everywhere and deploy anywhere: a declarative '
'static site generator/CMS for building high-quality web sites.'
),
long_description=open('description.txt').read().strip(),
url='https://growsdk.org',
zip_safe=False,
license='MIT',
author='Grow SDK Authors',
author_email='[email protected]',
include_package_data=True,
install_requires=[str(ir.req) for ir in _install_requirements],
packages=find_packages(),
scripts=[
'bin/grow',
],
keywords=[
'grow',
'cms',
'static site generator',
's3',
'google cloud storage',
'content management'
],
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Software Development :: Libraries :: Python Modules',
])
| from pip import req
import pip
from setuptools import find_packages
from setuptools import setup
_install_requirements = req.parse_requirements(
'requirements.txt', session=pip.download.PipSession())
setup(
name='grow',
version=open('grow/VERSION').read().strip(),
description=(
'Develop everywhere and deploy anywhere: a declarative '
'static site generator/CMS for building high-quality web sites.'
),
long_description=open('description.txt').read().strip(),
url='https://growsdk.org',
license='MIT',
author='Grow SDK Authors',
author_email='[email protected]',
include_package_data=True,
install_requires=[str(ir.req) for ir in _install_requirements],
packages=find_packages(),
scripts=[
'bin/grow',
],
keywords=[
'grow',
'cms',
'static site generator',
's3',
'google cloud storage',
'content management'
],
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Software Development :: Libraries :: Python Modules',
])
|
Raise error if conditions attribute unimplemented. | from PyOpenWorm import *
class Experiment(DataObject):
"""
Generic class for storing information about experiments
Should be overridden by specific types of experiments
(example: see PatchClampExperiment in ChannelWorm.py).
Overriding classes should have a list called "conditions" that
contains the names of experimental conditions for that particular
type of experiment.
Each of the items in "conditions" should also be either a
DatatypeProperty or ObjectProperty for the experiment a well.
Parameters
----------
reference : Evidence
Supporting article for this experiment.
"""
def __init__(self, reference=False, **kwargs):
DataObject.__init__(self, **kwargs)
Experiment.ObjectProperty('reference', owner=self, value_type=Evidence, multiple=True)
if(isinstance(reference,Evidence)):
#TODO: make this so the reference asserts this Experiment when it is added
self.reference(reference)
self._condits = {}
def get_conditions(self):
"""Return conditions and their associated values in a dict."""
if not hasattr(self, 'conditions'):
raise NotImplementedError(
'"Conditions" attribute must be overridden'
)
for c in self.conditions:
value = getattr(self, c)
try:
value()
#property is callable
self._condits[c] = value()
except:
if value:
#if property is not empty
self._condits[c] = value
return self._condits
| from PyOpenWorm import *
class Experiment(DataObject):
"""
Generic class for storing information about experiments
Should be overridden by specific types of experiments
(example: see PatchClampExperiment in ChannelWorm.py).
Overriding classes should have a list called "conditions" that
contains the names of experimental conditions for that particular
type of experiment.
Each of the items in "conditions" should also be either a
DatatypeProperty or ObjectProperty for the experiment a well.
Parameters
----------
reference : Evidence
Supporting article for this experiment.
"""
def __init__(self, reference=False, **kwargs):
DataObject.__init__(self, **kwargs)
Experiment.ObjectProperty('reference', owner=self, value_type=Evidence, multiple=True)
if(isinstance(reference,Evidence)):
#TODO: make this so the reference asserts this Experiment when it is added
self.reference(reference)
self._condits = {}
def get_conditions(self):
"""Return conditions and their associated values in a dict."""
for c in self.conditions:
value = getattr(self, c)
try:
value()
#property is callable
self._condits[c] = value()
except:
if value:
#if property is not empty
self._condits[c] = value
return self._condits
|
Change baseAim to 0, since we're using the Y axis | package edu.stuy.starlorn.entities;
import edu.stuy.starlorn.upgrades.GunUpgrade;
import java.util.LinkedList;
public class Ship extends Entity {
protected LinkedList<GunUpgrade> _gunupgrades;
protected int _baseDamage, _baseShotSpeed, _health;
protected double _baseAim;
public Ship() {
super();
_gunupgrades = new LinkedList<GunUpgrade>();
_baseDamage = 1;
_baseShotSpeed = 1;
_health = 10;
_baseAim = 0; //Aim up by default
}
public void addUpgrade(GunUpgrade upgrade) {
_gunupgrades.add(upgrade);
}
/*
* Create the shots based on the available GunUpgrades
*/
public void shoot() {
GunUpgrade topShot = _gunupgrades.get(0);
int damage = _baseDamage;
int shotSpeed = _baseShotSpeed;
for (GunUpgrade up : _gunupgrades) {
if (up.getNumShots() > topShot.getNumShots())
topShot = up;
damage = up.getDamage(damage);
shotSpeed = up.getShotSpeed(shotSpeed);
}
// Create new shots, based on dem vars
int numShots = topShot.getNumShots();
for (int i = 0; i < numShots; i++) {
Bullet b = new Bullet(_baseAim + topShot.getAimAngle(), damage, shotSpeed);
b.setWorld(this.getWorld());
}
}
}
| package edu.stuy.starlorn.entities;
import edu.stuy.starlorn.upgrades.GunUpgrade;
import java.util.LinkedList;
public class Ship extends Entity {
protected LinkedList<GunUpgrade> _gunupgrades;
protected int _baseDamage, _baseShotSpeed, _health;
protected double _baseAim;
public Ship() {
super();
_gunupgrades = new LinkedList<GunUpgrade>();
_baseDamage = 1;
_baseShotSpeed = 1;
_health = 10;
_baseAim = Math.PI/2; //Aim up by default
}
public void addUpgrade(GunUpgrade upgrade) {
_gunupgrades.add(upgrade);
}
/*
* Create the shots based on the available GunUpgrades
*/
public void shoot() {
GunUpgrade topShot = _gunupgrades.get(0);
int damage = _baseDamage;
int shotSpeed = _baseShotSpeed;
for (GunUpgrade up : _gunupgrades) {
if (up.getNumShots() > topShot.getNumShots())
topShot = up;
damage = up.getDamage(damage);
shotSpeed = up.getShotSpeed(shotSpeed);
}
// Create new shots, based on dem vars
int numShots = topShot.getNumShots();
for (int i = 0; i < numShots; i++) {
Bullet b = new Bullet(_baseAim + topShot.getAimAngle(), damage, shotSpeed);
b.setWorld(this.getWorld());
}
}
}
|
Remove unnecessary output from curl when using pushover | <?php
namespace Spatie\Backup\Notifications\Senders;
use Illuminate\Contracts\Config\Repository;
use Spatie\Backup\Notifications\BaseSender;
class Pushover extends BaseSender
{
/** @var array */
protected $config;
/**
* @param Repository $config
*/
public function __construct(Repository $config)
{
$this->config = $config->get('laravel-backup.notifications.pushover');
}
/**
* Sends the message to the Pushover API
* @return void
*/
public function send()
{
curl_setopt_array($ch = curl_init(), [
CURLOPT_URL => 'https://api.pushover.net/1/messages.json',
CURLOPT_POSTFIELDS => [
'token' => $this->config['token'],
'user' => $this->config['user'],
'title' => $this->subject,
'message' => $this->message,
'sound' => $this->getSound(),
],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SAFE_UPLOAD => true,
]);
curl_exec($ch);
curl_close($ch);
}
/**
* @return string
*/
protected function getSound()
{
return $this->type === static::TYPE_SUCCESS
? $this->config['sounds']['success']
: $this->config['sounds']['error'];
}
}
| <?php
namespace Spatie\Backup\Notifications\Senders;
use Illuminate\Contracts\Config\Repository;
use Spatie\Backup\Notifications\BaseSender;
class Pushover extends BaseSender
{
/** @var array */
protected $config;
/**
* @param Repository $config
*/
public function __construct(Repository $config)
{
$this->config = $config->get('laravel-backup.notifications.pushover');
}
/**
* Sends the message to the Pushover API
* @return void
*/
public function send()
{
curl_setopt_array($ch = curl_init(), [
CURLOPT_URL => 'https://api.pushover.net/1/messages.json',
CURLOPT_POSTFIELDS => [
'token' => $this->config['token'],
'user' => $this->config['user'],
'title' => $this->subject,
'message' => $this->message,
'sound' => $this->getSound(),
],
CURLOPT_SAFE_UPLOAD => true,
]);
curl_exec($ch);
curl_close($ch);
}
/**
* @return string
*/
protected function getSound()
{
return $this->type === static::TYPE_SUCCESS
? $this->config['sounds']['success']
: $this->config['sounds']['error'];
}
}
|
Add an entry for deploying | <div class="box">
<div class="box-header">
<h3 class="box-title">{{ trans('releases.label') }}</h3>
</div>
<div class="box-body" id="no_releases">
<p>{{ trans('releases.none') }}</p>
</div>
<div class="box-body table-responsive">
<table class="table table-striped" id="release_list">
<thead>
<tr>
<th width="30%">{{ trans('releases.name') }}</th>
<th class="text-right">{{ trans('app.actions') }}</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
@push('templates')
<script type="text/template" id="release-template">
<td><a href="/task/<%- task_id %>"><%- name %></a></td>
<td>
<div class="btn-group pull-right">
@if($project->can('manage'))
<a href="{{ route('deployments', ['id' => $project->deployPlan->id, 'tab' => 'deploy']) }}?release_id=<%- id %>" class="btn btn-info"><i class="piplin piplin-deploy"></i></a>
<button type="button" class="btn btn-danger btn-delete" title="{{ trans('releases.delete') }}" data-toggle="modal" data-backdrop="static" data-target="#model-trash"><i class="piplin piplin-delete"></i></button>
@endif
</div>
</td>
</script>
@endpush
| <div class="box">
<div class="box-header">
<h3 class="box-title">{{ trans('releases.label') }}</h3>
</div>
<div class="box-body" id="no_releases">
<p>{{ trans('releases.none') }}</p>
</div>
<div class="box-body table-responsive">
<table class="table table-striped" id="release_list">
<thead>
<tr>
<th width="30%">{{ trans('releases.name') }}</th>
<th class="text-right">{{ trans('app.actions') }}</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
@push('templates')
<script type="text/template" id="release-template">
<td><a href="/task/<%- task_id %>"><%- name %></a></td>
<td>
<div class="btn-group pull-right">
@if($project->can('manage'))
<button type="button" class="btn btn-danger btn-delete" title="{{ trans('releases.delete') }}" data-toggle="modal" data-backdrop="static" data-target="#model-trash"><i class="piplin piplin-delete"></i></button>
@endif
</div>
</td>
</script>
@endpush
|
Reset the request instance after the tests complete
Former-commit-id: c62e9dd007e64fa3070aaee69a15b2ee9efa0f6d
Former-commit-id: 152cba49a9c4537146c25be919ed35acd8619871 | <?php
require_once __DIR__ . "/ResolverTestCase.php";
class CanonicalUrlResolverTest extends ResolverTestCase
{
protected function setUp()
{
$this->urlResolver = new \Concrete\Core\Url\Resolver\CanonicalUrlResolver();
}
public function testConfig()
{
$canonical = "http://example.com:1337";
$old_value = \Config::get('concrete.seo.canonical_url');
\Config::set('concrete.seo.canonical_url', $canonical);
$this->assertEquals(
(string) \Concrete\Core\Url\Url::createFromUrl($canonical)->setPath(\Core::getApplicationRelativePath()),
(string) $this->urlResolver->resolve(array()));
\Config::set('concrete.seo.canonical_url', $old_value);
}
public function testFromRequest()
{
$mock = $this->getMock('\Concrete\Core\Http\RequestBase');
$mock->expects($this->once())->method('getScheme')->willReturn('http');
$mock->expects($this->once())->method('getHost')->willReturn('somehost');
$old_instance = \Request::getInstance();
\Request::setInstance($mock);
$old_value = \Config::get('concrete.seo.canonical_url');
\Config::set('concrete.seo.canonical_url', null);
$this->assertEquals(
(string) \Concrete\Core\Url\Url::createFromUrl("http://somehost")->setPath(\Core::getApplicationRelativePath()),
(string) $this->urlResolver->resolve(array()));
\Config::set('concrete.seo.canonical_url', $old_value);
\Request::setInstance($old_instance);
}
}
| <?php
require_once __DIR__ . "/ResolverTestCase.php";
class CanonicalUrlResolverTest extends ResolverTestCase
{
protected function setUp()
{
$this->urlResolver = new \Concrete\Core\Url\Resolver\CanonicalUrlResolver();
}
public function testConfig()
{
$canonical = "http://example.com:1337";
$old_value = \Config::get('concrete.seo.canonical_url');
\Config::set('concrete.seo.canonical_url', $canonical);
$this->assertEquals(
(string) \Concrete\Core\Url\Url::createFromUrl($canonical)->setPath(\Core::getApplicationRelativePath()),
(string) $this->urlResolver->resolve(array()));
\Config::set('concrete.seo.canonical_url', $old_value);
}
public function testFromRequest()
{
$mock = $this->getMock('\Concrete\Core\Http\RequestBase');
$mock->expects($this->once())->method('getScheme')->willReturn('http');
$mock->expects($this->once())->method('getHost')->willReturn('somehost');
\Request::setInstance($mock);
$old_value = \Config::get('concrete.seo.canonical_url');
\Config::set('concrete.seo.canonical_url', null);
$this->assertEquals(
(string) \Concrete\Core\Url\Url::createFromUrl("http://somehost")->setPath(\Core::getApplicationRelativePath()),
(string) $this->urlResolver->resolve(array()));
\Config::set('concrete.seo.canonical_url', $old_value);
}
}
|
Fix issue with walking paths instead of watching them. (Thanks to @mbibee and @betaveros.) | var fs = require('fs');
var path = require('path');
var logger = require('./logger');
module.exports = watcher;
var dirsToIgnore = /^(?:(?:node_modules|AppData)$|\.)/;
function watcher(paths, extensions, callback) {
paths.forEach(function(path) {
watch(path, true);
});
function watch(path_, isParentDir) {
fs.stat(path_, function(err, stats) {
if (!err) {
if (stats.isDirectory()) {
if (!dirsToIgnore.test(path.basename(path_))) {
walk(path_);
} else if (isParentDir) {
walk(path_);
}
} else if (extensions.test(path.extname(path_))) {
try {
fs.watchFile(path_, { persistent: true, interval: 100 }, function(curr, prev) {
if (curr.nlink && (curr.mtime.getTime() != prev.mtime.getTime())) {
callback(path_);
}
});
logger.info('Watching ' + path_);
} catch (e) {
logger.error(e.message);
}
}
}
});
}
function walk(path_) {
fs.readdir(path_, function(err, files) {
if (!err) {
files.forEach(function(filename) {
watch(path_ + path.sep + filename, false);
});
}
});
}
}
| var fs = require('fs');
var path = require('path');
var logger = require('./logger');
module.exports = watcher;
var dirsToIgnore = /^(?:(?:node_modules|AppData)$|\.)/;
function watcher(paths, extensions, callback) {
paths.forEach(function(path) {
walk(path, true);
});
function watch(path_, isParentDir) {
fs.stat(path_, function(err, stats) {
if (!err) {
if (stats.isDirectory()) {
if (!dirsToIgnore.test(path.basename(path_))) {
walk(path_);
} else if (isParentDir) {
walk(path_);
}
} else if (extensions.test(path.extname(path_))) {
try {
fs.watchFile(path_, { persistent: true, interval: 100 }, function(curr, prev) {
if (curr.nlink && (curr.mtime.getTime() != prev.mtime.getTime())) {
callback(path_);
}
});
logger.info('Watching ' + path_);
} catch (e) {
logger.error(e.message);
}
}
}
});
}
function walk(path_) {
fs.readdir(path_, function(err, files) {
if (!err) {
files.forEach(function(filename) {
watch(path_ + path.sep + filename, false);
});
}
});
}
}
|
Use \Exception when in try-catch for pcre exceptions | <?php
namespace Stamp\Action;
use RuntimeException;
class ParseVariableAction extends BaseAction implements ActionInterface
{
private $text = '';
private $regex = '';
public function getActionName()
{
return 'parse_variable';
}
public function setParams($array)
{
$this->setText($array['text']);
$this->setRegex($array['regex']);
}
public function setText($text)
{
$this->text = $text;
}
public function setRegex($regex)
{
$this->regex = $regex;
}
public function exec()
{
try {
$resultOfMatching = preg_match($this->regex, $this->text, $matches);
} catch (\Exception $e) {
throw new RuntimeException(sprintf('Error during parsing regex [[%s]]', $this->regex));
}
if ($resultOfMatching) {
unset($matches[0]);
unset($matches[1]);
if ($this->verbose) {
$key = array_keys($matches)[0];
$this->setOutput(sprintf('parse_variable["%s"=>"%s"]', $key, $matches[$key]));
}
$this->setResult($matches);
return true;
}
return false;
}
}
| <?php
namespace Stamp\Action;
class ParseVariableAction extends BaseAction implements ActionInterface
{
private $text = '';
private $regex = '';
public function getActionName()
{
return 'parse_variable';
}
public function setParams($array)
{
$this->setText($array['text']);
$this->setRegex($array['regex']);
}
public function setText($text)
{
$this->text = $text;
}
public function setRegex($regex)
{
$this->regex = $regex;
}
public function exec()
{
try {
$resultOfMatching = preg_match($this->regex, $this->text, $matches);
} catch (\PhpSpec\Exception\Example\ErrorException $e) {
throw new \RuntimeException(sprintf('Error during parsing regex [[%s]]', $this->regex));
}
if ($resultOfMatching) {
unset($matches[0]);
unset($matches[1]);
if ($this->verbose) {
$key = array_keys($matches)[0];
$this->setOutput(sprintf('parse_variable["%s"=>"%s"]', $key, $matches[$key]));
}
$this->setResult($matches);
return true;
}
return false;
}
}
|
Fix missing new dependency in event tagger test | <?php
namespace CultuurNet\UDB3\Event;
use Broadway\CommandHandling\Testing\CommandHandlerScenarioTestCase;
use Broadway\EventStore\EventStoreInterface;
use Broadway\EventHandling\EventBusInterface;
class EventTaggerTest extends CommandHandlerScenarioTestCase
{
protected function createCommandHandler(
EventStoreInterface $eventStore,
EventBusInterface $eventBus
) {
$repository = new EventRepository(
$eventStore,
$eventBus,
$this->getMock('\\CultuurNet\\UDB3\\SearchAPI2\\SearchServiceInterface')
);
return new EventCommandHandler($repository);
}
/**
* @test
*/
public function it_can_tag_a_list_of_events_with_a_keyword()
{
$ids = ['eventId1', 'eventId2'];
$keyword = 'awesome';
$this->scenario
->withAggregateId($ids[0])
->given(
[
new EventCreated($ids[0])
]
)
->withAggregateId($ids[1])
->given(
[
new EventCreated($ids[1])
]
)
->when(new TagEvents($ids, $keyword))
->then(
[
new EventWasTagged($ids[0], $keyword),
new EventWasTagged($ids[1], $keyword)
]
);
}
}
| <?php
namespace CultuurNet\UDB3\Event;
use Broadway\CommandHandling\Testing\CommandHandlerScenarioTestCase;
use Broadway\EventStore\EventStoreInterface;
use Broadway\EventHandling\EventBusInterface;
class EventTaggerTest extends CommandHandlerScenarioTestCase
{
protected function createCommandHandler(
EventStoreInterface $eventStore,
EventBusInterface $eventBus
) {
$repository = new EventRepository($eventStore, $eventBus);
return new EventCommandHandler($repository);
}
/**
* @test
*/
public function it_can_tag_a_list_of_events_with_a_keyword()
{
$ids = ['eventId1', 'eventId2'];
$keyword = 'awesome';
$this->scenario
->withAggregateId($ids[0])
->given(
[
new EventCreated($ids[0])
]
)
->withAggregateId($ids[1])
->given(
[
new EventCreated($ids[1])
]
)
->when(new TagEvents($ids, $keyword))
->then(
[
new EventWasTagged($ids[0], $keyword),
new EventWasTagged($ids[1], $keyword)
]
);
}
}
|
Add test for non-GET requests
* Check that we get a 403 result. | from os import environ
from unittest import TestCase
environ['DJANGO_SETTINGS_MODULE'] = 'test_settings'
from incuna_auth.middleware import LoginRequiredMiddleware
class AuthenticatedUser(object):
def is_authenticated(self):
return True
class AnonymousUser(object):
def is_authenticated(self):
return False
class Request(object):
def __init__(self, path_info, method='GET'):
self.path_info = path_info
self.method = method
class TestLoginRequiredMiddleware(TestCase):
def setUp(self):
self.middleware = LoginRequiredMiddleware()
def test_skip_middleware_if_url_is_exempt(self):
self.request = Request('exempt-and-protected-url/')
self.request.user = AnonymousUser()
response = self.middleware.process_request(self.request)
self.assertEqual(response, None)
def test_skip_middleware_if_url_is_not_protected(self):
self.request = Request('non-protected-url/')
self.request.user = AnonymousUser()
response = self.middleware.process_request(self.request)
self.assertEqual(response, None)
def test_skip_middleware_if_user_is_authenticated(self):
self.request = Request('protected-url/')
self.request.user = AuthenticatedUser()
response = self.middleware.process_request(self.request)
self.assertEqual(response, None)
def test_403_result_if_non_get_request(self):
self.request = Request('protected-url/', 'POST')
self.request.user = AnonymousUser()
response = self.middleware.process_request(self.request)
self.assertEqual(response.status_code, 403)
| from os import environ
from unittest import TestCase
environ['DJANGO_SETTINGS_MODULE'] = 'test_settings'
from incuna_auth.middleware import LoginRequiredMiddleware
class AuthenticatedUser(object):
def is_authenticated(self):
return True
class AnonymousUser(object):
def is_authenticated(self):
return False
class Request(object):
def __init__(self, path_info, method='GET'):
self.path_info = path_info
self.method = method
class TestLoginRequiredMiddleware(TestCase):
def setUp(self):
self.middleware = LoginRequiredMiddleware()
def test_skip_middleware_if_url_is_exempt(self):
self.request = Request('exempt-and-protected-url/')
self.request.user = AnonymousUser()
response = self.middleware.process_request(self.request)
self.assertEqual(response, None)
def test_skip_middleware_if_url_is_not_protected(self):
self.request = Request('non-protected-url/')
self.request.user = AnonymousUser()
response = self.middleware.process_request(self.request)
self.assertEqual(response, None)
def test_skip_middleware_if_user_is_authenticated(self):
self.request = Request('protected-url/')
self.request.user = AuthenticatedUser()
response = self.middleware.process_request(self.request)
self.assertEqual(response, None)
|
Upgrade to a way newer boto
Fixes an issue where content-type got %-escaped. | #!/usr/bin/python
from setuptools import setup
setup(name="catsnap",
version="6.0.0",
description="catalog and store images",
author="Erin Call",
author_email="[email protected]",
url="https://github.com/ErinCall/",
packages=['catsnap',
'catsnap.document',
'catsnap.config',
'catsnap.batch'],
install_requires=[
"Flask==0.9",
"gunicorn==0.14.6",
"boto==2.40.0",
"requests==0.13.2",
"argparse==1.2.1",
"psycopg2==2.4.6",
"sqlalchemy==0.8.0b2",
"yoyo-migrations==4.1.6",
"wand==0.3.3",
"celery==3.1.16",
"redis==2.10.3",
"gevent==1.1b5",
"Flask-Sockets==0.1",
"PyYAML==3.11",
"mock==1.0.1",
"nose==1.1.2",
"selenium==2.48",
"splinter==0.5.3",
"bcrypt==1.1.1",
],
)
| #!/usr/bin/python
from setuptools import setup
setup(name="catsnap",
version="6.0.0",
description="catalog and store images",
author="Erin Call",
author_email="[email protected]",
url="https://github.com/ErinCall/",
packages=['catsnap',
'catsnap.document',
'catsnap.config',
'catsnap.batch'],
install_requires=[
"Flask==0.9",
"gunicorn==0.14.6",
"boto==2.5.2",
"requests==0.13.2",
"argparse==1.2.1",
"psycopg2==2.4.6",
"sqlalchemy==0.8.0b2",
"yoyo-migrations==4.1.6",
"wand==0.3.3",
"celery==3.1.16",
"redis==2.10.3",
"gevent==1.1b5",
"Flask-Sockets==0.1",
"PyYAML==3.11",
"mock==1.0.1",
"nose==1.1.2",
"selenium==2.48",
"splinter==0.5.3",
"bcrypt==1.1.1",
],
)
|
fix: Raise non-auth errors from GitHub | import json
from zeus import auth
from zeus.api import client
from zeus.exceptions import ApiError
from zeus.models import Email, Identity
from .base import Resource
from ..schemas import EmailSchema, IdentitySchema, UserSchema
emails_schema = EmailSchema(many=True, strict=True)
identities_schema = IdentitySchema(many=True, strict=True)
user_schema = UserSchema(strict=True)
class AuthIndexResource(Resource):
auth_required = False
def get(self):
"""
Return information on the currently authenticated user.
"""
try:
user_response = client.get("/users/me")
except ApiError as exc:
if exc.code == 401:
return {"isAuthenticated": False}
raise
user = json.loads(user_response.data)
identity_list = list(Identity.query.filter(Identity.user_id == user["id"]))
email_list = list(Email.query.filter(Email.user_id == user["id"]))
return {
"isAuthenticated": True,
"user": user,
"emails": emails_schema.dump(email_list).data,
"identities": identities_schema.dump(identity_list).data,
}
def delete(self):
"""
Logout.
"""
auth.logout()
return {"isAuthenticated": False, "user": None}
| import json
from zeus import auth
from zeus.api import client
from zeus.exceptions import ApiError
from zeus.models import Email, Identity
from .base import Resource
from ..schemas import EmailSchema, IdentitySchema, UserSchema
emails_schema = EmailSchema(many=True, strict=True)
identities_schema = IdentitySchema(many=True, strict=True)
user_schema = UserSchema(strict=True)
class AuthIndexResource(Resource):
auth_required = False
def get(self):
"""
Return information on the currently authenticated user.
"""
try:
user_response = client.get("/users/me")
except ApiError as exc:
if exc.code == 401:
return {"isAuthenticated": False}
user = json.loads(user_response.data)
identity_list = list(Identity.query.filter(Identity.user_id == user["id"]))
email_list = list(Email.query.filter(Email.user_id == user["id"]))
return {
"isAuthenticated": True,
"user": user,
"emails": emails_schema.dump(email_list).data,
"identities": identities_schema.dump(identity_list).data,
}
def delete(self):
"""
Logout.
"""
auth.logout()
return {"isAuthenticated": False, "user": None}
|
Fix sorting dict items in python 3 | from ipywidgets import widgets
from jinja2 import Template
from traitlets import (
observe,
Unicode,
)
from dallinger.config import get_config
header_template = Template(u"""
<h2>{{ name }}</h2>
<div>Status: {{ status }}</div>
{% if app_id %}<div>App ID: {{ app_id }}</div>{% endif %}
""")
config_template = Template(u"""
<table style="min-width: 50%">
{% for k, v in config %}
<tr>
<th>{{ k }}</th>
<td>{{ v }}</td>
</tr>
{% endfor %}
</table>
""")
class ExperimentWidget(widgets.VBox):
status = Unicode('Unknown')
def __init__(self, exp):
self.exp = exp
super(ExperimentWidget, self).__init__()
self.render()
@observe('status')
def render(self, change=None):
header = widgets.HTML(
header_template.render(
name=self.exp.task,
status=self.status,
app_id=self.exp.app_id,
),
)
config = get_config()
if config.ready:
config_items = list(config.as_dict().items())
config_items.sort()
config_tab = widgets.HTML(
config_template.render(config=config_items)
)
else:
config_tab = widgets.HTML('Not loaded.')
tabs = widgets.Tab(children=[config_tab])
tabs.set_title(0, 'Configuration')
self.children = [header, tabs]
| from ipywidgets import widgets
from jinja2 import Template
from traitlets import (
observe,
Unicode,
)
from dallinger.config import get_config
header_template = Template(u"""
<h2>{{ name }}</h2>
<div>Status: {{ status }}</div>
{% if app_id %}<div>App ID: {{ app_id }}</div>{% endif %}
""")
config_template = Template(u"""
<table style="min-width: 50%">
{% for k, v in config %}
<tr>
<th>{{ k }}</th>
<td>{{ v }}</td>
</tr>
{% endfor %}
</table>
""")
class ExperimentWidget(widgets.VBox):
status = Unicode('Unknown')
def __init__(self, exp):
self.exp = exp
super(ExperimentWidget, self).__init__()
self.render()
@observe('status')
def render(self, change=None):
header = widgets.HTML(
header_template.render(
name=self.exp.task,
status=self.status,
app_id=self.exp.app_id,
),
)
config = get_config()
if config.ready:
config_items = config.as_dict().items()
config_items.sort()
config_tab = widgets.HTML(
config_template.render(config=config_items)
)
else:
config_tab = widgets.HTML('Not loaded.')
tabs = widgets.Tab(children=[config_tab])
tabs.set_title(0, 'Configuration')
self.children = [header, tabs]
|
Fix error if regexp doesn't match beause trl() is used directly | <?php
class Kwf_Assets_Util_Trl
{
//returns replacement used for js trl strings
//used by Kwf_Assets_Dependency_File_Js and Kwf_Assets_CommonJs_Underscore_TemplateDependency
public static function getJsReplacement($trlElement)
{
$b = $trlElement['before'];
$fn = substr($b, 0, strpos($b, '('));
$key = $trlElement['type'].'.'.$trlElement['source'];
if (isset($trlElement['context'])) $key .= '.'.$trlElement['context'];
$key .= '.'.str_replace("'", "\\'", $trlElement['text']);
$replace = '';
if (preg_match('#^([a-z]+\.)trl#i', $b, $m)) {
$replace = substr($b, 0, strlen($m[1]));
}
if ($trlElement['type'] == 'trlp' || $trlElement['type'] == 'trlcp') {
$replace .= "_kwfTrlp";
} else {
$replace .= "_kwfTrl";
}
$replace .= "('$key', ".substr($b, strpos($b, '(')+1);
unset($trlElement['before']);
unset($trlElement['linenr']);
unset($trlElement['error_short']);
return array(
'before' => $b,
'replace' => $replace,
'trlElement' => (object)$trlElement
);
}
}
| <?php
class Kwf_Assets_Util_Trl
{
//returns replacement used for js trl strings
//used by Kwf_Assets_Dependency_File_Js and Kwf_Assets_CommonJs_Underscore_TemplateDependency
public static function getJsReplacement($trlElement)
{
$b = $trlElement['before'];
$fn = substr($b, 0, strpos($b, '('));
$key = $trlElement['type'].'.'.$trlElement['source'];
if (isset($trlElement['context'])) $key .= '.'.$trlElement['context'];
$key .= '.'.str_replace("'", "\\'", $trlElement['text']);
if (preg_match('#^([a-z]+\.)trl#i', $b, $m)) {
$replace = substr($b, 0, strlen($m[1]));
}
if ($trlElement['type'] == 'trlp' || $trlElement['type'] == 'trlcp') {
$replace .= "_kwfTrlp";
} else {
$replace .= "_kwfTrl";
}
$replace .= "('$key', ".substr($b, strpos($b, '(')+1);
unset($trlElement['before']);
unset($trlElement['linenr']);
unset($trlElement['error_short']);
return array(
'before' => $b,
'replace' => $replace,
'trlElement' => (object)$trlElement
);
}
}
|
Remove select from command list. | package com.csforge.sstable;
import com.google.common.base.Strings;
import java.io.File;
import java.util.Arrays;
public class Driver {
public static void main(String ... args) {
if (args.length == 0) {
printCommands();
System.exit(-1);
}
switch(args[0].toLowerCase()) {
case "tojson":
SSTable2Json.main(Arrays.copyOfRange(args, 1, args.length));
break;
case "cqlsh":
Cqlsh.main(Arrays.copyOfRange(args, 1, args.length));
break;
case "describe":
String path = new File(args[1]).getAbsolutePath();
try {
System.out.println("\u001B[1;34m" + path);
System.out.println(TableTransformer.ANSI_CYAN + Strings.repeat("=", path.length()));
System.out.print(TableTransformer.ANSI_RESET);
CassandraUtils.printStats(path, System.out);
} catch (Exception e) {
e.printStackTrace();
}
break;
default:
System.err.println("Unknown command: " + args[0]);
printCommands();
System.exit(-2);
break;
}
}
private static void printCommands() {
System.err.println("Available commands: cqlsh, toJson, describe");
}
}
| package com.csforge.sstable;
import com.google.common.base.Strings;
import java.io.File;
import java.util.Arrays;
public class Driver {
public static void main(String ... args) {
if (args.length == 0) {
printCommands();
System.exit(-1);
}
switch(args[0].toLowerCase()) {
case "tojson":
SSTable2Json.main(Arrays.copyOfRange(args, 1, args.length));
break;
case "cqlsh":
Cqlsh.main(Arrays.copyOfRange(args, 1, args.length));
break;
case "describe":
String path = new File(args[1]).getAbsolutePath();
try {
System.out.println("\u001B[1;34m" + path);
System.out.println(TableTransformer.ANSI_CYAN + Strings.repeat("=", path.length()));
System.out.print(TableTransformer.ANSI_RESET);
CassandraUtils.printStats(path, System.out);
} catch (Exception e) {
e.printStackTrace();
}
break;
default:
System.err.println("Unknown command: " + args[0]);
printCommands();
System.exit(-2);
break;
}
}
private static void printCommands() {
System.err.println("Available commands: cqlsh, toJson, select, describe");
}
}
|
Fix NPE with normal bows. | package io.github.lexware.bukkit.enderbow;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Projectile;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityShootBowEvent;
import org.bukkit.event.entity.ProjectileHitEvent;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.metadata.MetadataValue;
/**
* Created by jamie on 09/01/15.
*/
public class EnderBowListener implements Listener {
private final EnderBowPlugin plugin;
public EnderBowListener(EnderBowPlugin plugin) {
this.plugin = plugin;
}
@EventHandler
public void onEntityShootBowEvent(EntityShootBowEvent event) {
if(event.getBow().hasItemMeta() && event.getBow().getItemMeta().getDisplayName().equals("Ender bow")) {
event.getProjectile().setMetadata("enderBowData", new FixedMetadataValue(plugin, "enderArrow"));
}
}
@EventHandler
public void onProjectileHit(ProjectileHitEvent event) {
if(event.getEntity().hasMetadata("enderBowData")) {
for(MetadataValue value : event.getEntity().getMetadata("enderBowData")) {
if(value.asString().equals("enderArrow")) {
((Entity)event.getEntity().getShooter()).teleport(event.getEntity().getLocation());
}
}
}
}
}
| package io.github.lexware.bukkit.enderbow;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Projectile;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityShootBowEvent;
import org.bukkit.event.entity.ProjectileHitEvent;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.metadata.MetadataValue;
/**
* Created by jamie on 09/01/15.
*/
public class EnderBowListener implements Listener {
private final EnderBowPlugin plugin;
public EnderBowListener(EnderBowPlugin plugin) {
this.plugin = plugin;
}
@EventHandler
public void onEntityShootBowEvent(EntityShootBowEvent event) {
if(event.getBow().getItemMeta().getDisplayName().equals("Ender bow")) {
event.getProjectile().setMetadata("enderBowData", new FixedMetadataValue(plugin, "enderArrow"));
}
}
@EventHandler
public void onProjectileHit(ProjectileHitEvent event) {
if(event.getEntity().hasMetadata("enderBowData")) {
for(MetadataValue value : event.getEntity().getMetadata("enderBowData")) {
if(value.asString().equals("enderArrow")) {
((Entity)event.getEntity().getShooter()).teleport(event.getEntity().getLocation());
}
}
}
}
}
|
Add a message if no options are provided to update | <?php
namespace Lstr\DnsmasqMgmt\Command;
use Exception;
use Lstr\Silex\App\AppAwareInterface;
use Lstr\Silex\App\AppAwareTrait;
use Silex\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class AddressUpdateCommand extends Command implements AppAwareInterface
{
use AppAwareTrait;
protected function configure()
{
$this
->setName('address:update')
->setAliases(['update-address'])
->setDescription('Remove an address')
->addArgument(
'hostname',
InputArgument::REQUIRED,
'What is the hostname you want to update?'
)
->addOption(
'ip-address',
null,
InputOption::VALUE_REQUIRED,
'What is the IP address you want to point the hostname to?'
)
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$app = $this->getSilexApplication();
$service = $app['lstr.dnsmasq'];
if (!$input->getOption('ip-address')) {
throw new Exception("At least one option ('ip-address') should be provided.");
}
return $service->updateAddress(
$input->getArgument('hostname'),
$input->getOption('ip-address')
);
}
}
| <?php
namespace Lstr\DnsmasqMgmt\Command;
use Exception;
use Lstr\Silex\App\AppAwareInterface;
use Lstr\Silex\App\AppAwareTrait;
use Silex\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class AddressUpdateCommand extends Command implements AppAwareInterface
{
use AppAwareTrait;
protected function configure()
{
$this
->setName('address:update')
->setAliases(['update-address'])
->setDescription('Remove an address')
->addArgument(
'hostname',
InputArgument::REQUIRED,
'What is the hostname you want to update?'
)
->addOption(
'ip-address',
null,
InputOption::VALUE_REQUIRED,
'What is the IP address you want to point the hostname to?'
)
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$app = $this->getSilexApplication();
$service = $app['lstr.dnsmasq'];
return $service->updateAddress(
$input->getArgument('hostname'),
$input->getOption('ip-address')
);
}
}
|
Handle symlinks in path to home directory | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# © 2017-2021 qsuscs, TobiX
# Should still run with Python 2.7...
from __future__ import print_function, unicode_literals
import os
import sys
from glob import glob
os.chdir(os.path.dirname(os.path.abspath(__file__)))
home = os.path.realpath(os.path.expanduser('~'))
exit = 0
for f in glob('dot.*'):
dst_home = f[3:].replace("--", "\ufffd").replace("-", "/").replace("\ufffd", "-")
dst = home + '/' + dst_home
src = os.path.join(os.getcwd(), f)
src_rel = os.path.relpath(src, os.path.dirname(dst))
try:
os.makedirs(os.path.dirname(dst))
except OSError:
pass
try:
os.symlink(src_rel, dst)
except OSError:
# Broken symbolic links do not "exist"
if not os.path.exists(dst):
print('"{}" is a broken link pointing to "{}", replacing.'.format(
dst_home, os.readlink(dst)))
os.remove(dst)
os.symlink(src_rel, dst)
elif not os.path.samefile(src, dst):
print('"{}" exists and does not link to "{}".'.format(dst_home, f))
exit = 1
sys.exit(exit)
| #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# © 2017-2019 qsuscs, TobiX
# Should still run with Python 2.7...
from __future__ import print_function, unicode_literals
import os
import sys
from glob import glob
os.chdir(os.path.dirname(os.path.abspath(__file__)))
exit = 0
for f in glob('dot.*'):
dst_home = '~/' + f[3:].replace("--", "\ufffd").replace("-", "/").replace("\ufffd", "-")
dst = os.path.expanduser(dst_home)
src = os.path.join(os.getcwd(), f)
src_rel = os.path.relpath(src, os.path.dirname(dst))
try:
os.makedirs(os.path.dirname(dst))
except OSError:
pass
try:
os.symlink(src_rel, dst)
except OSError:
# Broken symbolic links do not "exist"
if not os.path.exists(dst):
print('"{}" is a broken link pointing to "{}", replacing.'.format(
dst_home, os.readlink(dst)))
os.remove(dst)
os.symlink(src_rel, dst)
elif not os.path.samefile(src, dst):
print('"{}" exists and does not link to "{}".'.format(dst_home, f))
exit = 1
sys.exit(exit)
|
Reset the padding on each TextView when the RecyclerView binds it | package net.bloople.stories;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class NodesAdapter extends RecyclerView.Adapter<NodesAdapter.ViewHolder> {
private List<Node> nodes;
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView textView;
public ViewHolder(View view) {
super(view);
textView = (TextView)view.findViewById(R.id.text_view);
}
}
public NodesAdapter(List<Node> inNodes) {
nodes = inNodes;
}
// Create new views (invoked by the layout manager)
@Override
public NodesAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.node_view, parent,
false);
return new ViewHolder(view);
}
// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
TextView tv = holder.textView;
tv.setText(nodes.get(position).content());
tv.setPadding(
tv.getPaddingLeft(),
(position == 0 ? tv.getPaddingBottom() : 0),
tv.getPaddingRight(),
tv.getPaddingBottom()
);
}
// Return the size of your dataset (invoked by the layout manager)
@Override
public int getItemCount() {
return nodes.size();
}
} | package net.bloople.stories;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class NodesAdapter extends RecyclerView.Adapter<NodesAdapter.ViewHolder> {
private List<Node> nodes;
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView textView;
public ViewHolder(View view) {
super(view);
textView = (TextView)view.findViewById(R.id.text_view);
}
}
public NodesAdapter(List<Node> inNodes) {
nodes = inNodes;
}
// Create new views (invoked by the layout manager)
@Override
public NodesAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.node_view, parent,
false);
return new ViewHolder(view);
}
// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
TextView tv = holder.textView;
tv.setText(nodes.get(position).content());
if(position == 0) {
tv.setPadding(
tv.getPaddingLeft(),
tv.getPaddingBottom(),
tv.getPaddingRight(),
tv.getPaddingBottom()
);
}
}
// Return the size of your dataset (invoked by the layout manager)
@Override
public int getItemCount() {
return nodes.size();
}
} |
Add checking empty product code | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
class CsvConverter:
def __init__(self, csv_file_path):
self.csv_file_path = csv_file_path
self.rows = []
self.source_product_code = "product_code"
self.source_quantity = "quantity"
def clear(self):
self.rows = []
def addRow(self, row):
self.rows.append(row)
def getRow(self, index):
return self.rows[index]
def setSourceColumns(self, source_product_code, source_quantity):
self.source_product_code = source_product_code
self.source_quantity = source_quantity
def setTargetColumns(self, target_product_code, target_quantity):
self.target_product_code = target_product_code
self.target_quantity = target_quantity
def convertRow(self, row):
if not row[self.source_product_code]:
raise ValueError
return {
'product_code': row[self.source_product_code],
'quantity': int(row[self.source_quantity])
}
def read_file(self):
with open(self.csv_file_path, 'rb') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
self.addRow(self.convertRow(row))
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
class CsvConverter:
def __init__(self, csv_file_path):
self.csv_file_path = csv_file_path
self.rows = []
self.source_product_code = "product_code"
self.source_quantity = "quantity"
def clear(self):
self.rows = []
def addRow(self, row):
self.rows.append(row)
def getRow(self, index):
return self.rows[index]
def setSourceColumns(self, source_product_code, source_quantity):
self.source_product_code = source_product_code
self.source_quantity = source_quantity
def setTargetColumns(self, target_product_code, target_quantity):
self.target_product_code = target_product_code
self.target_quantity = target_quantity
def convertRow(self, row):
return {
'product_code': int(row[self.source_product_code]),
'quantity': int(row[self.source_quantity])
}
def read_file(self):
with open(self.csv_file_path, 'rb') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
self.addRow(self.convertRow(row))
|
Throw exception if unknown command in used in control console command | <?php
namespace Phobetor\RabbitMqSupervisorBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class ControlCommand extends ContainerAwareCommand
{
protected function configure()
{
$this
->setName('rabbitmq-supervisor:control')
->addArgument('cmd', InputArgument::REQUIRED, '(start|stop|restart|hup)')
->setDescription('Common commands to control the supervisord process')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
/** @var \Phobetor\RabbitMqSupervisorBundle\Services\RabbitMqSupervisor $handler */
$handler = $this->getContainer()->get('phobetor_rabbitmq_supervisor');
switch ($input->getArgument('cmd')) {
case 'start':
$handler->start();
break;
case 'stop':
$handler->stop();
break;
case 'restart':
$handler->restart();
break;
case 'hup':
$handler->hup();
break;
default:
throw new \InvalidArgumentException(sprintf(
'Unknown command. Expected (start|stop|restart|hup), given "%s"', $input->getArgument('cmd')
));
}
}
}
| <?php
namespace Phobetor\RabbitMqSupervisorBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class ControlCommand extends ContainerAwareCommand
{
protected function configure()
{
$this
->setName('rabbitmq-supervisor:control')
->addArgument('cmd', InputArgument::REQUIRED, '(start|stop|restart|hup)')
->setDescription('Common commands to control the supervisord process')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
/** @var \Phobetor\RabbitMqSupervisorBundle\Services\RabbitMqSupervisor $handler */
$handler = $this->getContainer()->get('phobetor_rabbitmq_supervisor');
switch ($input->getArgument('cmd')) {
case 'start':
$handler->start();
break;
case 'stop':
$handler->stop();
break;
case 'restart':
$handler->restart();
break;
case 'hup':
$handler->hup();
break;
}
}
}
|
Convert data to float in sparklines | import { Sparkline } from 'lib/visualizations'
window.GobiertoCharters.ChartersController = (function() {
function ChartersController() {}
ChartersController.prototype.show = function(opts){
// DEBUG: Esta funcion DEBE ser eliminada cuando se obtengan datos verdaderos
function mock(length = 2) {
let json = [];
for (var i = 0; i < length; i++) {
json.push({
date: new Date().getFullYear() - i,
value: Math.floor(Math.random() * Math.floor(100))
})
}
return json
}
function _parseNumericStrings(data) {
for (let i in data) {
data[i].value = parseFloat(data[i].value)
}
return data
}
const $sparklines = $('.sparkline')
$sparklines.each((i, container) => {
let options = {
axes: true,
aspectRatio: 3,
margins: {
top: 0,
bottom: 0,
left: 0,
right: 0
},
freq: opts.freq
}
if (opts.sparklinesData[container.id] && opts.sparklinesData[container.id].length > 1 && $(`#${container.id} svg`).length === 0) {
let chart = new Sparkline(`#${container.id}`, _parseNumericStrings(opts.sparklinesData[container.id]), options)
chart.render()
}
})
};
return ChartersController;
})();
window.GobiertoCharters.charters_controller = new GobiertoCharters.ChartersController;
| import { Sparkline } from 'lib/visualizations'
window.GobiertoCharters.ChartersController = (function() {
function ChartersController() {}
ChartersController.prototype.show = function(opts){
// DEBUG: Esta funcion DEBE ser eliminada cuando se obtengan datos verdaderos
function mock(length = 2) {
let json = [];
for (var i = 0; i < length; i++) {
json.push({
date: new Date().getFullYear() - i,
value: Math.floor(Math.random() * Math.floor(100))
})
}
return json
}
const $sparklines = $('.sparkline')
$sparklines.each((i, container) => {
let options = {
axes: true,
aspectRatio: 3,
margins: {
top: 0,
bottom: 0,
left: 0,
right: 0
},
freq: opts.freq
}
if (opts.sparklinesData[container.id] && opts.sparklinesData[container.id].length > 1 && $(`#${container.id} svg`).length === 0) {
let chart = new Sparkline(`#${container.id}`, opts.sparklinesData[container.id], options)
chart.render()
}
})
};
return ChartersController;
})();
window.GobiertoCharters.charters_controller = new GobiertoCharters.ChartersController;
|
Add balance checking test victim | from django.test import TestCase
from breach.models import SampleSet, Victim, Target, Round
class RuptureTestCase(TestCase):
def setUp(self):
target = Target.objects.create(
endpoint='https://di.uoa.gr/?breach=%s',
prefix='test',
alphabet='0123456789'
)
self.victim = Victim.objects.create(
target=target,
sourceip='192.168.10.140',
snifferendpoint='http://localhost/'
)
round = Round.objects.create(
victim=self.victim,
amount=1,
knownsecret='testsecret',
knownalphabet='01'
)
self.samplesets = [
SampleSet.objects.create(
round=round,
candidatealphabet='0',
data='bigbigbigbigbigbig'
),
SampleSet.objects.create(
round=round,
candidatealphabet='1',
data='small'
)
]
# Balance checking
self.balance_victim = Victim.objects.create(
target=target,
sourceip='192.168.10.141',
snifferendpoint='http://localhost/'
)
| from django.test import TestCase
from breach.models import SampleSet, Victim, Target, Round
class RuptureTestCase(TestCase):
def setUp(self):
target = Target.objects.create(
endpoint='https://di.uoa.gr/?breach=%s',
prefix='test',
alphabet='0123456789'
)
self.victim = Victim.objects.create(
target=target,
sourceip='192.168.10.140',
snifferendpoint='http://localhost/'
)
round = Round.objects.create(
victim=self.victim,
amount=1,
knownsecret='testsecret',
knownalphabet='01'
)
self.samplesets = [
SampleSet.objects.create(
round=round,
candidatealphabet='0',
data='bigbigbigbigbigbig'
),
SampleSet.objects.create(
round=round,
candidatealphabet='1',
data='small'
)
]
|
Allow watching changes in modules map for ymb dev mode | var fs = require('fs'),
path = require('path'),
_ = require('lodash'),
gulp = require('gulp'),
through = require('through2'),
file = require('gulp-file');
module.exports = mapSrcPlugin;
var contents = {};
function requireFresh (src) {
delete require.cache[require.resolve(src)];
return require(src);
}
/**
* @ignore
* Loads `map.json` into stream.
* @alias "map.src"
* @param {Object} data Cross-plugin request data
* @returns {stream.Transform} Stream
*/
function mapSrcPlugin (data) {
if (!data.cacheEnabled || !contents[data.src]) {
contents[data.src] = stringifyMap(
requireFresh(path.resolve(data.src + 'map.json'))
);
}
return file('map.json', contents[data.src], { src: true });
}
// TODO shared with ymb
function stringifyMap (map) {
var stack = [];
_.each(map, function (moduleInfo) {
stack.push('[' + _.map(moduleInfo, function (value, index) {
if (index == 2 && value.slice(0, 8) == 'function') {
return value;
} else if (index == 5 && typeof value == 'object') {
return '{ ' + _.map(value, function (v, k) { return k + ': ' + v; }).join(', ') + ' }';
} else {
return '\'' + value + '\'';
}
}).join(', ') + ']');
});
return '[\n ' + stack.join(',\n ') + '\n]';
}
| var fs = require('fs'),
path = require('path'),
_ = require('lodash'),
gulp = require('gulp'),
through = require('through2'),
file = require('gulp-file');
module.exports = mapSrcPlugin;
var contents = {};
/**
* @ignore
* Loads `map.json` into stream.
* @alias "map.src"
* @param {Object} data Cross-plugin request data
* @returns {stream.Transform} Stream
*/
function mapSrcPlugin (data) {
if (!contents[data.src]) {
contents[data.src] = stringifyMap(require(path.resolve(data.src + 'map.json')));
}
return file('map.json', contents[data.src], { src: true });
}
// TODO shared with ymb
function stringifyMap (map) {
var stack = [];
_.each(map, function (moduleInfo) {
stack.push('[' + _.map(moduleInfo, function (value, index) {
if (index == 2 && value.slice(0, 8) == 'function') {
return value;
} else if (index == 5 && typeof value == 'object') {
return '{ ' + _.map(value, function (v, k) { return k + ': ' + v; }).join(', ') + ' }';
} else {
return '\'' + value + '\'';
}
}).join(', ') + ']');
});
return '[\n ' + stack.join(',\n ') + '\n]';
}
|
refactor(database): Fix MySQL pool createConnection return type | <?php
declare(strict_types=1);
namespace Leevel\Database\Mysql;
use Leevel\Database\Manager;
use Leevel\Database\PoolManager;
use Leevel\Protocol\Pool\IConnection;
use Leevel\Protocol\Pool\IPool;
use Leevel\Protocol\Pool\Pool;
/**
* MySQL 连接池.
*
* @codeCoverageIgnore
*/
class MysqlPool extends Pool implements IPool
{
/**
* 数据库连接池管理.
*/
protected PoolManager $poolManager;
/**
* 数据库管理.
*/
protected Manager $manager;
/**
* MySQL 连接.
*/
protected string $mysqlConnect;
/**
* 构造函数.
*/
public function __construct(Manager $manager, string $mysqlConnect, array $option = [])
{
$this->manager = $manager;
$this->poolManager = $manager->createPoolManager();
$this->mysqlConnect = $mysqlConnect;
parent::__construct($option);
}
/**
* {@inheritDoc}
*/
protected function createConnection(): IConnection
{
if ($this->poolManager->inTransactionConnection()) {
return $this->poolManager->getTransactionConnection();
}
$this->manager->extend('mysqlPoolConnection', function (Manager $manager): IConnection {
return $manager->createMysqlPoolConnection($this->mysqlConnect);
});
/** @var \Leevel\Database\MysqlPoolConnection $mysql */
$mysqlPoolConnection = $this->manager->connect('mysqlPoolConnection', true);
$mysqlPoolConnection->setShouldRelease(true);
return $mysqlPoolConnection;
}
}
| <?php
declare(strict_types=1);
namespace Leevel\Database\Mysql;
use Leevel\Database\Manager;
use Leevel\Database\MysqlPoolConnection;
use Leevel\Database\PoolManager;
use Leevel\Protocol\Pool\IPool;
use Leevel\Protocol\Pool\Pool;
/**
* MySQL 连接池.
*
* @codeCoverageIgnore
*/
class MysqlPool extends Pool implements IPool
{
/**
* 数据库连接池管理.
*/
protected PoolManager $poolManager;
/**
* 数据库管理.
*/
protected Manager $manager;
/**
* MySQL 连接.
*/
protected string $mysqlConnect;
/**
* 构造函数.
*/
public function __construct(Manager $manager, string $mysqlConnect, array $option = [])
{
$this->manager = $manager;
$this->poolManager = $manager->createPoolManager();
$this->mysqlConnect = $mysqlConnect;
parent::__construct($option);
}
/**
* {@inheritDoc}
*/
protected function createConnection(): MysqlPoolConnection
{
if ($this->poolManager->inTransactionConnection()) {
return $this->poolManager->getTransactionConnection();
}
$this->manager->extend('mysqlPoolConnection', function (Manager $manager): MysqlPoolConnection {
return $manager->createMysqlPoolConnection($this->mysqlConnect);
});
/** @var \Leevel\Database\MysqlPoolConnection $mysql */
$mysqlPoolConnection = $this->manager->connect('mysqlPoolConnection', true);
$mysqlPoolConnection->setShouldRelease(true);
return $mysqlPoolConnection;
}
}
|
Fix build to add back the roboto font and bootstrap fonts. | // Copies files not processed by requirejs optimization from source to dist so other tasks can process them
module.exports = {
dist: {
files: [{
expand: true,
dot: true,
cwd: '<%= yeoman.app %>',
dest: '<%= yeoman.dist %>',
src: [
'*.{ico,png,txt}',
'.htaccess',
'*.html',
'bower_components/**/*',
'views/alien4cloud-templates.js',
'js-lib/**/*',
'images/**/*',
'scripts/**/*',
'data/**/*',
'api-doc/**/*',
'version.json',
]
}, {
expand: true,
cwd: '.tmp/images',
dest: '<%= yeoman.dist %>/images',
src: ['generated/*']
}, {
expand: true,
flatten: true,
cwd: '<%= yeoman.app %>',
dest: '<%= yeoman.dist %>/images',
src: ['bower_components/angular-tree-control/images/*']
}]
},
bower: {
files: [{
expand: true,
dot: true,
cwd: '<%= yeoman.app %>',
dest: '<%= yeoman.dist %>',
src: [
'bower_components/es5-shim/es5-shim.min.js',
'bower_components/json3/lib/json3.min.js',
'bower_components/requirejs/require.js',
'bower_components/font-awesome/**/*',
'bower_components/bootstrap-sass-official/assets/fonts/bootstrap/**/*',
'bower_components/roboto-fontface/**/*'
]
}]
}
};
| // Copies files not processed by requirejs optimization from source to dist so other tasks can process them
module.exports = {
dist: {
files: [{
expand: true,
dot: true,
cwd: '<%= yeoman.app %>',
dest: '<%= yeoman.dist %>',
src: [
'*.{ico,png,txt}',
'.htaccess',
'*.html',
'bower_components/**/*',
'views/alien4cloud-templates.js',
'js-lib/**/*',
'images/**/*',
'scripts/**/*',
'data/**/*',
'api-doc/**/*',
'version.json',
]
}, {
expand: true,
cwd: '.tmp/images',
dest: '<%= yeoman.dist %>/images',
src: ['generated/*']
}, {
expand: true,
flatten: true,
cwd: '<%= yeoman.app %>',
dest: '<%= yeoman.dist %>/images',
src: ['bower_components/angular-tree-control/images/*']
}]
},
bower: {
files: [{
expand: true,
dot: true,
cwd: '<%= yeoman.app %>',
dest: '<%= yeoman.dist %>',
src: [
'bower_components/es5-shim/es5-shim.min.js',
'bower_components/json3/lib/json3.min.js',
'bower_components/requirejs/require.js',
'bower_components/font-awesome/**/*'
]
}]
}
};
|
Change max filesize for uploaded images | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Image;
class ImageController extends Controller
{
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$image = Image::find($id);
$data = [
'image' => $image,
'texts' => $image->texts
];
return view('image', $data);
}
/**
* Manage Post Request
*
* @return void
*/
public function postImage(Request $request)
{
$this->validate($request, [
'image_file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:10000',
]);
$imageName = time().'.'.$request->image_file->getClientOriginalExtension();
$request->image_file->move(public_path('images'), $imageName);
$image = new Image;
$image->parent_id = $request->parent_id;
$image->file = $imageName;
$image->save();
return back()
->with('success','You have successfully upload images.')
->with('image',$imageName);
}
} | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Image;
class ImageController extends Controller
{
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$image = Image::find($id);
$data = [
'image' => $image,
'texts' => $image->texts
];
return view('image', $data);
}
/**
* Manage Post Request
*
* @return void
*/
public function postImage(Request $request)
{
$this->validate($request, [
'image_file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:1024',
]);
$imageName = time().'.'.$request->image_file->getClientOriginalExtension();
$request->image_file->move(public_path('images'), $imageName);
$image = new Image;
$image->parent_id = $request->parent_id;
$image->file = $imageName;
$image->save();
return back()
->with('success','You have successfully upload images.')
->with('image',$imageName);
}
} |
Return API error during parse, since it's being sent by the remote server | <?php
namespace BitWasp\Stratum\Request;
use BitWasp\Stratum\Exception\ApiError;
class RequestFactory
{
/**
* @var array
*/
private $nonces = [];
/**
* @param string $method
* @param array $params
* @return Request
*/
public function create($method, $params = array())
{
do {
$id = mt_rand(0, PHP_INT_MAX);
} while (in_array($id, $this->nonces));
return new Request($id, $method, $params);
}
/**
* @param $string
* @return Response|Request
* @throws \Exception
*/
public function response($string)
{
$decoded = json_decode(trim($string), true);
if (json_last_error() === JSON_ERROR_NONE) {
$id = isset($decoded['id']) ? $decoded['id'] : null;
if (isset($decoded['error'])) {
return new ApiError($id, $decoded['error']);
} elseif (isset($decoded['method']) && isset($decoded['params'])) {
return new Request($id, $decoded['method'], $decoded['params']);
} elseif (isset($decoded['result'])) {
return new Response($id, $decoded['result']);
}
throw new \Exception('Response missing error/params/result');
}
throw new \Exception('Invalid JSON');
}
}
| <?php
namespace BitWasp\Stratum\Request;
use BitWasp\Stratum\Exception\ApiError;
class RequestFactory
{
/**
* @var array
*/
private $nonces = [];
/**
* @param string $method
* @param array $params
* @return Request
*/
public function create($method, $params = array())
{
do {
$id = mt_rand(0, PHP_INT_MAX);
} while (in_array($id, $this->nonces));
return new Request($id, $method, $params);
}
/**
* @param $string
* @return Response|Request
* @throws \Exception
*/
public function response($string)
{
$decoded = json_decode(trim($string), true);
if (json_last_error() === JSON_ERROR_NONE) {
$id = isset($decoded['id']) ? $decoded['id'] : null;
if (isset($decoded['error'])) {
throw new ApiError($id, $decoded['error']);
} elseif (isset($decoded['method']) && isset($decoded['params'])) {
return new Request($id, $decoded['method'], $decoded['params']);
} elseif (isset($decoded['result'])) {
return new Response($id, $decoded['result']);
}
throw new \Exception('Response missing error/params/result');
}
throw new \Exception('Invalid JSON');
}
}
|
Fix `is_anonymous` for Django 2 | from django.conf import settings
if settings.HOOVER_RATELIMIT_USER:
from django.http import HttpResponse
from . import signals
from hoover.contrib.ratelimit.limit import RateLimit
class HttpLimitExceeded(HttpResponse):
def __init__(self):
super().__init__(
"Rate limit exceeded\n", 'text/plain',
429, 'Too Many Requests',
)
(_l, _i) = settings.HOOVER_RATELIMIT_USER
_user_limit = RateLimit(_l, _i)
def limit_user(view):
def wrapper(request, *args, **kwargs):
username = request.user.get_username()
key = 'user:' + username
if _user_limit.access(key):
signals.rate_limit_exceeded.send(
'hoover.search',
username=username,
)
return HttpLimitExceeded()
return view(request, *args, **kwargs)
return wrapper
def get_request_limits(user):
if user.is_anonymous:
return None
key = 'user:' + user.get_username()
return {
'interval': _user_limit.interval,
'limit': _user_limit.limit,
'count': _user_limit.get(key),
}
else:
def limit_user(view):
return view
def get_request_limits(user):
return None
| from django.conf import settings
if settings.HOOVER_RATELIMIT_USER:
from django.http import HttpResponse
from . import signals
from hoover.contrib.ratelimit.limit import RateLimit
class HttpLimitExceeded(HttpResponse):
def __init__(self):
super().__init__(
"Rate limit exceeded\n", 'text/plain',
429, 'Too Many Requests',
)
(_l, _i) = settings.HOOVER_RATELIMIT_USER
_user_limit = RateLimit(_l, _i)
def limit_user(view):
def wrapper(request, *args, **kwargs):
username = request.user.get_username()
key = 'user:' + username
if _user_limit.access(key):
signals.rate_limit_exceeded.send(
'hoover.search',
username=username,
)
return HttpLimitExceeded()
return view(request, *args, **kwargs)
return wrapper
def get_request_limits(user):
if user.is_anonymous():
return None
key = 'user:' + user.get_username()
return {
'interval': _user_limit.interval,
'limit': _user_limit.limit,
'count': _user_limit.get(key),
}
else:
def limit_user(view):
return view
def get_request_limits(user):
return None
|
Check response status codes in quickFetch. | // We use this function throughout all the things to send and recieve form our
// django-rest-framework API
function quickFetch(url, method, body) {
let csrftoken = Cookies.get('csrftoken');
method = (typeof method !== 'undefined') ? method : 'get';
// Give us back a promise we can .then() on, data can be accessed via
// .then(function(data) {console.log(data)})
return fetch(url, {
credentials: 'include',
headers: new Headers({
'content-type': 'application/json',
'X-CSRFToken': csrftoken
}),
method: method,
body: JSON.stringify(body)
}).then(function(response) {
let result = null;
switch (response.status) {
case 200: // HTTP_200_OK
case 201: // HTTP_201_CREATED
result = response.json();
break;
default:
result = response;
break;
}
return result;
});
}
// Append number with 0 if there is only 1 digit
function pad(num) {
num = num.toString();
if (num.length === 1) {
num = '0' + num;
}
return num;
}
// Convert a decimal duration to a string (0:00).
function durationToString(duration) {
if (typeof(duration) === 'number') {
let hours = Math.floor(duration);
let minutes = Math.round((duration - hours) * 60);
duration = hours + ':' + pad(minutes);
}
return duration;
}
| // We use this function throughout all the things to send and recieve form our
// django-rest-framework API
function quickFetch(url, method, body) {
let csrftoken = Cookies.get('csrftoken');
method = (typeof method !== 'undefined') ? method : 'get';
// Give us back a promise we can .then() on, data can be accessed via
// .then(function(data) {console.log(data)})
return fetch(url, {
credentials: 'include',
headers: new Headers({
'content-type': 'application/json',
'X-CSRFToken': csrftoken
}),
method: method,
body: JSON.stringify(body)
}).then(function(response) {
// Delete response throws an error with .json().
// TODO: Figure out a proper way to return information on DELETE.
if (method != 'delete') {
return response.json();
}
});
}
// Append number with 0 if there is only 1 digit
function pad(num) {
num = num.toString();
if (num.length === 1) {
num = '0' + num;
}
return num;
}
// Convert a decimal duration to a string (0:00).
function durationToString(duration) {
if (typeof(duration) === 'number') {
let hours = Math.floor(duration);
let minutes = Math.round((duration - hours) * 60);
duration = hours + ':' + pad(minutes);
}
return duration;
}
|
Change test names to follow convention | package se.kits.gakusei.controller;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import se.kits.gakusei.content.model.Course;
import se.kits.gakusei.content.repository.CourseRepository;
import se.kits.gakusei.test_tools.TestTools;
import static org.junit.Assert.*;
@RunWith(MockitoJUnitRunner.class)
public class CourseControllerTest {
@InjectMocks
private CourseController courseController;
@Mock
private CourseRepository courseRepository;
private Course testCourse;
@Before
public void setUp(){
MockitoAnnotations.initMocks(this);
testCourse = TestTools.generateCourse();
}
@Test
public void testGetAllCoursesOK() throws Exception {
}
@Test
public void testGetCourseByIDOK() throws Exception {
Mockito.when(courseRepository.findOne(testCourse.getId())).thenReturn(testCourse);
ResponseEntity<Course> re = courseController.getCourseByID(testCourse.getId());
assertEquals(HttpStatus.OK, re.getStatusCode());
assertEquals(testCourse, re.getBody());
}
@Test
public void tetGetCourseByNameOK() throws Exception {
}
@Test
public void tetsGetCourseByCodeOK() throws Exception {
}
} | package se.kits.gakusei.controller;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import se.kits.gakusei.content.model.Course;
import se.kits.gakusei.content.repository.CourseRepository;
import se.kits.gakusei.test_tools.TestTools;
import static org.junit.Assert.*;
@RunWith(MockitoJUnitRunner.class)
public class CourseControllerTest {
@InjectMocks
private CourseController courseController;
@Mock
private CourseRepository courseRepository;
private Course testCourse;
@Before
public void setUp(){
MockitoAnnotations.initMocks(this);
testCourse = TestTools.generateCourse();
}
@Test
public void getAllCourses() throws Exception {
}
@Test
public void getCourseByID() throws Exception {
Mockito.when(courseRepository.findOne(testCourse.getId())).thenReturn(testCourse);
ResponseEntity<Course> re = courseController.getCourseByID(testCourse.getId());
assertEquals(HttpStatus.OK, re.getStatusCode());
assertEquals(testCourse, re.getBody());
}
@Test
public void getCourseByName() throws Exception {
}
@Test
public void getCourseByCode() throws Exception {
}
} |
Add databse config to production settings file | from gigs.settings_base import *
DEBUG = False
TEMPLATE_DEBUG = False
ADMINS = ()
INSTALLED_APPS += (
'gunicorn',
)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'django',
'OPTIONS':{
'read_default_file':'/etc/tugg/my.cnf',
},
},
}
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'standard': {
'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s'
},
},
'handlers': {
'default': {
'level':'DEBUG',
'class':'logging.handlers.RotatingFileHandler',
'filename': '/var/log/tugg/tugg.log',
'maxBytes': 1024*1024*50, # 50 MB
'backupCount': 5,
'formatter':'standard',
},
'request_handler': {
'level':'DEBUG',
'class':'logging.handlers.RotatingFileHandler',
'filename': '/var/log/tugg/tugg_request.log',
'maxBytes': 1024*1024*50, # 5 MB
'backupCount': 5,
'formatter':'standard',
},
},
'loggers': {
'': {
'handlers': ['default'],
'level': 'DEBUG',
'propagate': True
},
'django.request': {
'handlers': ['request_handler'],
'level': 'DEBUG',
'propagate': False
},
},
}
| from gigs.settings_base import *
DEBUG = False
TEMPLATE_DEBUG = False
ADMINS = ()
INSTALLED_APPS += (
'gunicorn',
)
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'standard': {
'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s'
},
},
'handlers': {
'default': {
'level':'DEBUG',
'class':'logging.handlers.RotatingFileHandler',
'filename': '/var/log/tugg/tugg.log',
'maxBytes': 1024*1024*50, # 50 MB
'backupCount': 5,
'formatter':'standard',
},
'request_handler': {
'level':'DEBUG',
'class':'logging.handlers.RotatingFileHandler',
'filename': '/var/log/tugg/tugg_request.log',
'maxBytes': 1024*1024*50, # 5 MB
'backupCount': 5,
'formatter':'standard',
},
},
'loggers': {
'': {
'handlers': ['default'],
'level': 'DEBUG',
'propagate': True
},
'django.request': {
'handlers': ['request_handler'],
'level': 'DEBUG',
'propagate': False
},
},
}
|
Add parameter for log level | """The parameters dictionary contains global parameter settings."""
__all__ = ['Parameters', 'parameters']
# Be EXTREMELY careful when writing to a Parameters dictionary
# Read here for reference: http://wiki.c2.com/?GlobalVariablesAreBad
# https://softwareengineering.stackexchange.com/questions/148108/why-is-global-state-so-evil
# If any issues related to global state arise, the following class should
# be made immutable. It shall only be written to at application startup
# and never modified.
class Parameters(dict):
""" A dictionary-like class to hold global configuration parameters for devito
On top of a normal dict, this provides the option to provide callback functions
so that any interested module can be informed when the configuration changes.
"""
def __init__(self, name=None, **kwargs):
self._name = name
self.update_functions = None
for key, value in iteritems(kwargs):
self[key] = value
def __setitem__(self, key, value):
super(Parameters, self).__setitem__(key, value)
# If a Parameters dictionary is being added as a child,
# ask it to tell us when it is updated
if isinstance(value, Parameters):
child_update = lambda x: self._updated(*x)
value.update_functions.push(child_update)
# Tell everyone we've been updated
self._updated(key, value)
def _updated(self, key, value):
""" Call any provided update functions so everyone knows we've been updated
"""
for f in self.update_functions:
f(key, value)
parameters = Parameters()
parameters["log_level"] = 'info'
| """The parameters dictionary contains global parameter settings."""
__all__ = ['Parameters', 'parameters']
# Be EXTREMELY careful when writing to a Parameters dictionary
# Read here for reference: http://wiki.c2.com/?GlobalVariablesAreBad
# If any issues related to global state arise, the following class should
# be made immutable. It shall only be written to at application startup
# and never modified.
class Parameters(dict):
""" A dictionary-like class to hold global configuration parameters for devito
On top of a normal dict, this provides the option to provide callback functions
so that any interested module can be informed when the configuration changes.
"""
def __init__(self, name=None, **kwargs):
self._name = name
self.update_functions = None
for key, value in iteritems(kwargs):
self[key] = value
def __setitem__(self, key, value):
super(Parameters, self).__setitem__(key, value)
# If a Parameters dictionary is being added as a child,
# ask it to tell us when it is updated
if isinstance(value, Parameters):
child_update = lambda x: self._updated(*x)
value.update_functions.push(child_update)
# Tell everyone we've been updated
self._updated(key, value)
def _updated(self, key, value):
""" Call any provided update functions so everyone knows we've been updated
"""
for f in self.update_functions:
f(key, value)
|
Update deprecated form type api | <?php
namespace Mapbender\DataSourceBundle\Element\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* Class DataBaseType
*
* @package Mapbender\DataSourceBundle\Element\Type
* @author Andriy Oblivantsev <[email protected]>
*/
class DataBaseType extends AbstractType
{
/**
* Returns the name of this type.
*
* @return string The name of this type
*/
public function getName()
{
/** Name binding? */
return "source";
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array());
}
/**
* @inheritdoc
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$fields = array();
for ($i = 0; $i < rand(3, 12); $i++) {
$id = rand(1, 1000);
$key = "field" . $id;
$fields[] = array($key => "Field #" . $id);
}
$builder
->add('sqlField', 'choice', array(
'choices' => $fields,
'required' => true,
)
);
}
} | <?php
namespace Mapbender\DataSourceBundle\Element\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
/**
* Class DataBaseType
*
* @package Mapbender\DataSourceBundle\Element\Type
* @author Andriy Oblivantsev <[email protected]>
*/
class DataBaseType extends AbstractType
{
/**
* Returns the name of this type.
*
* @return string The name of this type
*/
public function getName()
{
/** Name binding? */
return "source";
}
/**
* @inheritdoc
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array());
}
/**
* @inheritdoc
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$fields = array();
for ($i = 0; $i < rand(3, 12); $i++) {
$id = rand(1, 1000);
$key = "field" . $id;
$fields[] = array($key => "Field #" . $id);
}
$builder
->add('sqlField', 'choice', array(
'choices' => $fields,
'required' => true,
)
);
}
} |
:white_check_mark: Add a test for teams page data | <?php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use App\Org;
use App\User;
class DataTest extends TestCase
{
use DatabaseTransactions;
/**
* Test dashboard gets orgs.
*
* @return void
*/
public function testDashboard()
{
$user = factory(User::class)->create();
$orgs = factory(Org::class, 5)->create([
'userid' => $user->id,
]);
$response = $this->actingAs($user)
->get('dashboard');
$response->assertStatus(200)
->assertViewHas('orgs', Org::where('userid', '=', $user->id)->paginate(15));
}
/**
* Test organization settings page gets org.
*
* @return void
*/
public function testOrg()
{
$user = factory(User::class)->create();
$org = factory(Org::class)->create([
'userid' => $user->id,
]);
$response = $this->actingAs($user)
->get('org/'.$org->id);
$response->assertStatus(200)
->assertViewHas('org');
}
/**
* Test teams page gets org.
*
* @return void
*/
public function testTeams()
{
$user = factory(User::class)->create();
$org = factory(Org::class)->create([
'userid' => $user->id,
]);
$response = $this->actingAs($user)
->get('org/'.$org->id.'/teams');
$response->assertStatus(200)
->assertViewHas('org');
}
}
| <?php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use App\Org;
use App\User;
class DataTest extends TestCase
{
use DatabaseTransactions;
/**
* Test dashboard gets orgs.
*
* @return void
*/
public function testDashboard()
{
$user = factory(User::class)->create();
$orgs = factory(Org::class, 5)->create([
'userid' => $user->id,
]);
$response = $this->actingAs($user)
->get('dashboard');
$response->assertStatus(200)
->assertViewHas('orgs', Org::where('userid', '=', $user->id)->paginate(15));
}
/**
* Test organization settings page gets orgs.
*
* @return void
*/
public function testOrg()
{
$user = factory(User::class)->create();
$org = factory(Org::class)->create([
'userid' => $user->id,
]);
$response = $this->actingAs($user)
->get('org/'.$org->id);
$response->assertStatus(200)
->assertViewHas('org');
}
}
|
Add test for blank audit name. | from pyxform.tests_v1.pyxform_test_case import PyxformTestCase
class AuditTest(PyxformTestCase):
def test_audit(self):
self.assertPyxformXform(
name="meta_audit",
md="""
| survey | | | |
| | type | name | label |
| | audit | audit | |
""",
xml__contains=[
'<meta>',
'<audit/>',
'</meta>',
'<bind nodeset="/meta_audit/meta/audit" type="binary"/>'],
)
def test_audit_random_name(self):
self.assertPyxformXform(
name="meta_audit",
md="""
| survey | | | |
| | type | name | label |
| | audit | bobby | |
""",
xml__contains=[
'<meta>',
'<audit/>',
'</meta>',
'<bind nodeset="/meta_audit/meta/audit" type="binary"/>'],
)
def test_audit_blank_name(self):
self.assertPyxformXform(
name="meta_audit",
md="""
| survey | | | |
| | type | name | label |
| | audit | | |
""",
xml__contains=[
'<meta>',
'<audit/>',
'</meta>',
'<bind nodeset="/meta_audit/meta/audit" type="binary"/>'],
) | from pyxform.tests_v1.pyxform_test_case import PyxformTestCase
class AuditTest(PyxformTestCase):
def test_audit(self):
self.assertPyxformXform(
name="meta_audit",
md="""
| survey | | | |
| | type | name | label |
| | audit | audit | |
""",
xml__contains=[
'<meta>',
'<audit/>',
'</meta>',
'<bind nodeset="/meta_audit/meta/audit" type="binary"/>'],
)
def test_audit_random_name(self):
self.assertPyxformXform(
name="meta_audit",
md="""
| survey | | | |
| | type | name | label |
| | audit | bobby | |
""",
xml__contains=[
'<meta>',
'<audit/>',
'</meta>',
'<bind nodeset="/meta_audit/meta/audit" type="binary"/>'],
) |
Add canBeAttacked condition to Chasing the Sun | const _ = require('underscore');
const DrawCard = require('../../drawcard.js');
const { Locations, CardTypes, EventNames } = require('../../Constants');
class ChasingTheSun extends DrawCard {
setupCardAbilities() {
this.action({
title: 'Move the conflict to another eligible province',
condition: context => context.player.isAttackingPlayer(),
cannotBeMirrored: true,
effect: 'move the conflict to a different province',
handler: context => this.game.promptForSelect(context.player, {
context: context,
cardType: CardTypes.Province,
location: Locations.Provinces,
cardCondition: (card, context) => !card.isConflictProvince() && card.canBeAttacked() && (card.location !== Locations.StrongholdProvince ||
_.size(this.game.provinceCards.filter(card => card.isBroken && card.controller === context.player.opponent)) > 2),
onSelect: (player, card) => {
this.game.addMessage('{0} moves the conflict to {1}', player, card);
card.inConflict = true;
this.game.currentConflict.conflictProvince.inConflict = false;
this.game.currentConflict.conflictProvince = card;
if(card.facedown) {
card.facedown = false;
this.game.raiseEvent(EventNames.OnCardRevealed, { context: context, card: card });
}
return true;
}
})
});
}
}
ChasingTheSun.id = 'chasing-the-sun';
module.exports = ChasingTheSun;
| const _ = require('underscore');
const DrawCard = require('../../drawcard.js');
const { Locations, CardTypes, EventNames } = require('../../Constants');
class ChasingTheSun extends DrawCard {
setupCardAbilities() {
this.action({
title: 'Move the conflict to another eligible province',
condition: context => context.player.isAttackingPlayer(),
cannotBeMirrored: true,
effect: 'move the conflict to a different province',
handler: context => this.game.promptForSelect(context.player, {
context: context,
cardType: CardTypes.Province,
location: Locations.Provinces,
cardCondition: (card, context) => !card.isConflictProvince() && (card.location !== Locations.StrongholdProvince ||
_.size(this.game.provinceCards.filter(card => card.isBroken && card.controller === context.player.opponent)) > 2),
onSelect: (player, card) => {
this.game.addMessage('{0} moves the conflict to {1}', player, card);
card.inConflict = true;
this.game.currentConflict.conflictProvince.inConflict = false;
this.game.currentConflict.conflictProvince = card;
if(card.facedown) {
card.facedown = false;
this.game.raiseEvent(EventNames.OnCardRevealed, { context: context, card: card });
}
return true;
}
})
});
}
}
ChasingTheSun.id = 'chasing-the-sun';
module.exports = ChasingTheSun;
|
Make W0 task handler test play more nicely.
Change-Id: I19bacffb3c7b2cea75fc9efd54af104fcb89f4c4 | package org.wikipedia.test;
import android.content.*;
import android.test.*;
import java.util.HashMap;
import org.mediawiki.api.json.*;
import org.wikipedia.WikipediaApp;
import org.wikipedia.zero.*;
import java.util.concurrent.*;
public class WikipediaZeroTests extends ActivityUnitTestCase<TestDummyActivity> {
private static final int TASK_COMPLETION_TIMEOUT = 20000;
public WikipediaZeroTests() {
super(TestDummyActivity.class);
}
public void testWikipediaZeroEligibilityCheck() throws Throwable {
final CountDownLatch completionLatch = new CountDownLatch(1);
startActivity(new Intent(), null, null);
runTestOnUiThread(new Runnable() {
@Override
public void run() {
HashMap<String,String> customHeaders = new HashMap<String,String>();
customHeaders.put("X-CS", "TEST");
new WikipediaZeroTask(new Api("en.m.wikipedia.org", "WMF-Android-AutomationTest-testWikipediaZeroEligibility", customHeaders), (WikipediaApp)getInstrumentation().getTargetContext().getApplicationContext()) {
@Override
public void onFinish(String result) {
assertNotNull(result);
completionLatch.countDown();
}
}.execute();
}
});
assertTrue(completionLatch.await(TASK_COMPLETION_TIMEOUT, TimeUnit.MILLISECONDS));
}
}
| package org.wikipedia.test;
import android.content.*;
import android.test.*;
import org.mediawiki.api.json.*;
import org.wikipedia.WikipediaApp;
import org.wikipedia.zero.*;
import java.util.concurrent.*;
public class WikipediaZeroTests extends ActivityUnitTestCase<TestDummyActivity> {
private static final int TASK_COMPLETION_TIMEOUT = 20000;
public WikipediaZeroTests() {
super(TestDummyActivity.class);
}
public void testWikipediaZeroEligibilityCheck() throws Throwable {
final CountDownLatch completionLatch = new CountDownLatch(1);
startActivity(new Intent(), null, null);
runTestOnUiThread(new Runnable() {
@Override
public void run() {
new WikipediaZeroTask(new Api("en.wikipedia.org"), (WikipediaApp)getInstrumentation().getTargetContext().getApplicationContext()) {
@Override
public void onFinish(String result) {
assertNotNull(result);
completionLatch.countDown();
}
}.execute();
}
});
assertTrue(completionLatch.await(TASK_COMPLETION_TIMEOUT, TimeUnit.MILLISECONDS));
}
}
|
NXP-11577: Fix Sonar Major violation: Javadoc Type | package org.nuxeo.drive.service.impl;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.nuxeo.ecm.core.api.IdRef;
/**
* Helper to handle synchronization root definitions.
*
* @author Antoine Taillefer
*/
public class RootDefinitionsHelper {
private RootDefinitionsHelper() {
// Utility class
}
/**
* Parses the given synchronization root definitions string.
*/
public static Map<String, Set<IdRef>> parseRootDefinitions(
String rootDefinitions) {
Map<String, Set<IdRef>> lastActiveRootRefs = new LinkedHashMap<String, Set<IdRef>>();
if (rootDefinitions != null) {
String[] rootDefinitionComponents = StringUtils.split(
rootDefinitions, ",");
for (String rootDefinition : rootDefinitionComponents) {
String[] rootComponents = StringUtils.split(rootDefinition, ":");
String repoName = rootComponents[0].trim();
Set<IdRef> refs = lastActiveRootRefs.get(repoName);
if (refs == null) {
refs = new HashSet<IdRef>();
lastActiveRootRefs.put(repoName, refs);
}
refs.add(new IdRef(rootComponents[1].trim()));
}
}
return lastActiveRootRefs;
}
}
| package org.nuxeo.drive.service.impl;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.nuxeo.ecm.core.api.IdRef;
public class RootDefinitionsHelper {
private RootDefinitionsHelper() {
// Utility class
}
public static Map<String, Set<IdRef>> parseRootDefinitions(
String rootDefinitions) {
Map<String, Set<IdRef>> lastActiveRootRefs = new LinkedHashMap<String, Set<IdRef>>();
if (rootDefinitions != null) {
String[] rootDefinitionComponents = StringUtils.split(
rootDefinitions, ",");
for (String rootDefinition : rootDefinitionComponents) {
String[] rootComponents = StringUtils.split(rootDefinition, ":");
String repoName = rootComponents[0].trim();
Set<IdRef> refs = lastActiveRootRefs.get(repoName);
if (refs == null) {
refs = new HashSet<IdRef>();
lastActiveRootRefs.put(repoName, refs);
}
refs.add(new IdRef(rootComponents[1].trim()));
}
}
return lastActiveRootRefs;
}
}
|
Fix fellowship_grant when upload data | import pandas as pd
from django.core.management.base import BaseCommand, CommandError
from django.core.exceptions import ObjectDoesNotExist
from fellowms.models import Fellow
class Command(BaseCommand):
help = "Add old information to database."
# TODO Make use of args and options.
def handle(self, *args, **options):
data = pd.read_csv('all_applications_details.csv')
for idx, line in data.iterrows():
if line['Selected']=='Yes':
is_fellow=True
else:
is_fellow=False
applicants_dict = {
"application_year": line["Inauguration year"],
"selected": is_fellow,
"forenames": line["Forename(s)"],
"surname": line["Surname"],
"affiliation": line["Home institution"],
"research_area": line["Research area"],
"research_area_code": line["Research classification"],
"email": line["E-mail"],
"phone": line["Telephone"],
"gender": line["Gender"] if line["Gender"] else 'R',
"work_description": line["Work area"],
"funding": "{}, {}".format(line["Primary funder"],line["Additional funder"]),
"fellowship_grant": 3000 if is_fellow else 0,
}
applicant = Fellow(**applicants_dict)
applicant.save()
| import pandas as pd
from django.core.management.base import BaseCommand, CommandError
from django.core.exceptions import ObjectDoesNotExist
from fellowms.models import Fellow
class Command(BaseCommand):
help = "Add old information to database."
# TODO Make use of args and options.
def handle(self, *args, **options):
data = pd.read_csv('all_applications_details.csv')
for idx, line in data.iterrows():
if line['Selected']=='Yes':
is_fellow=True
else:
is_fellow=False
applicants_dict = {
"application_year": line["Inauguration year"],
"selected": is_fellow,
"forenames": line["Forename(s)"],
"surname": line["Surname"],
"affiliation": line["Home institution"],
"research_area": line["Research area"],
"research_area_code": line["Research classification"],
"email": line["E-mail"],
"phone": line["Telephone"],
"gender": line["Gender"] if line["Gender"] else 'R',
"work_description": line["Work area"],
"funding": "{}, {}".format(line["Primary funder"],line["Additional funder"]),
}
applicant = Fellow(**applicants_dict)
applicant.save()
|
Bring back useRawDomain for Voyager2 | 'use strict';
// Service for the spec config.
// We keep this separate so that changes are kept even if the spec changes.
angular.module('vlui')
.factory('Config', function() {
var Config = {};
Config.data = {};
Config.config = {};
Config.getConfig = function() {
return {};
};
Config.getData = function() {
return Config.data;
};
Config.large = function() {
return {
cell: {
width: 300,
height: 300
},
facet: {
cell: {
width: 150,
height: 150
}
},
overlay: {line: true},
scale: {useRawDomain: false}
};
};
Config.small = function() {
return {
facet: {
cell: {
width: 150,
height: 150
}
},
overlay: {line: true},
scale: {useRawDomain: true}
};
};
Config.updateDataset = function(dataset, type) {
if (dataset.values) {
Config.data.values = dataset.values;
delete Config.data.url;
Config.data.formatType = undefined;
} else {
Config.data.url = dataset.url;
delete Config.data.values;
Config.data.formatType = type;
}
};
return Config;
});
| 'use strict';
// Service for the spec config.
// We keep this separate so that changes are kept even if the spec changes.
angular.module('vlui')
.factory('Config', function() {
var Config = {};
Config.data = {};
Config.config = {};
Config.getConfig = function() {
return {};
};
Config.getData = function() {
return Config.data;
};
Config.large = function() {
return {
cell: {
width: 300,
height: 300
},
facet: {
cell: {
width: 150,
height: 150
}
},
overlay: {line: true},
scale: {useRawDomain: false}
};
};
Config.small = function() {
return {
facet: {
cell: {
width: 150,
height: 150
}
},
overlay: {line: true},
scale: {useRawDomain: false}
};
};
Config.updateDataset = function(dataset, type) {
if (dataset.values) {
Config.data.values = dataset.values;
delete Config.data.url;
Config.data.formatType = undefined;
} else {
Config.data.url = dataset.url;
delete Config.data.values;
Config.data.formatType = type;
}
};
return Config;
});
|
Use large avatar on profile page | import React, { Component } from 'react';
import { connect } from 'react-redux';
import '../scss/_profile.scss';
import RecipeContainer from './RecipeContainer.js';
class Profile extends Component {
componentDidMount() {
}
componentWillUpdate(nextProps) {
}
render() {
const { avatar, user, recipesOwned, recipesFollowed, recipesLiked } = this.props;
const avatarLarge = avatar.slice(0, avatar.length-6);
return (
<div className="profile-content">
<div className="col-1-4">
<img className="profile-avatar" src={avatarLarge} alt="avatar"></img>
<p className="profile-username">{user.displayName}</p>
</div>
<div className="profile-recipe-containers col-3-4">
<RecipeContainer
className="recipes-owned"
type="My Recipes"
recipes={recipesOwned}
/>
<RecipeContainer
className="recipes-followed"
type="Followed Recipes"
recipes={recipesFollowed}
/>
<RecipeContainer
className="recipes-liked"
type="Liked Recipes"
recipes={recipesLiked}
/>
</div>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
user: state.user,
avatar: state.user.photos[0].value,
recipesOwned: state.recipesOwned,
recipesFollowed: state.recipesFollowed,
recipesLiked: state.recipesLiked,
};
};
export default connect(mapStateToProps)(Profile);
| import React, { Component } from 'react';
import { connect } from 'react-redux';
import '../scss/_profile.scss';
import RecipeContainer from './RecipeContainer.js';
class Profile extends Component {
componentDidMount() {
}
componentWillUpdate(nextProps) {
}
render() {
const { avatar, user, recipesOwned, recipesFollowed, recipesLiked } = this.props;
return (
<div className="profile-content">
<div className="col-1-4">
<img className="profile-avatar" src={avatar/*props.avatar.slice(0, props.avatar.length-6)*/} alt="avatar"></img>
<p className="profile-username">{user.displayName}</p>
</div>
<div className="profile-recipe-containers col-3-4">
<RecipeContainer
className="recipes-owned"
type="My Recipes"
recipes={recipesOwned}
/>
<RecipeContainer
className="recipes-followed"
type="Followed Recipes"
recipes={recipesFollowed}
/>
<RecipeContainer
className="recipes-liked"
type="Liked Recipes"
recipes={recipesLiked}
/>
</div>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
user: state.user,
avatar: state.user.photos[0].value,
recipesOwned: state.recipesOwned,
recipesFollowed: state.recipesFollowed,
recipesLiked: state.recipesLiked,
};
};
export default connect(mapStateToProps)(Profile);
|
Revert "set 0000-00-00 00:00:00 to expires default instead of CURRENT_TIMESTAMP"
This reverts commit 939da875a5dd6b20dbc3d940b2e540a9154f2766.
refs #4 | <?php
use Migrations\AbstractMigration;
class CreateRememberMeTokens extends AbstractMigration
{
/**
* Change Method.
*
* More information on this method is available here:
* http://docs.phinx.org/en/latest/migrations.html#the-change-method
* @return void
*/
public function change()
{
$table = $this->table('remember_me_tokens');
$table->addTimestamps('created', 'modified');
$table->addColumn('model', 'string', [
'default' => null,
'limit' => 64,
'null' => false,
]);
$table->addColumn('foreign_id', 'string', [
'default' => null,
'limit' => 36,
'null' => false,
]);
$table->addColumn('series', 'string', [
'default' => null,
'limit' => 64,
'null' => false,
]);
$table->addColumn('token', 'string', [
'default' => null,
'limit' => 255,
'null' => false,
]);
$table->addColumn('expires', 'timestamp', [
'default' => 'CURRENT_TIMESTAMP',
'null' => false,
]);
$table->addIndex([
'model',
'foreign_id',
'series',
], [
'name' => 'U_token_identifier',
'unique' => true,
]);
$table->create();
}
}
| <?php
use Migrations\AbstractMigration;
class CreateRememberMeTokens extends AbstractMigration
{
/**
* Change Method.
*
* More information on this method is available here:
* http://docs.phinx.org/en/latest/migrations.html#the-change-method
* @return void
*/
public function change()
{
$table = $this->table('remember_me_tokens');
$table->addTimestamps('created', 'modified');
$table->addColumn('model', 'string', [
'default' => null,
'limit' => 64,
'null' => false,
]);
$table->addColumn('foreign_id', 'string', [
'default' => null,
'limit' => 36,
'null' => false,
]);
$table->addColumn('series', 'string', [
'default' => null,
'limit' => 64,
'null' => false,
]);
$table->addColumn('token', 'string', [
'default' => null,
'limit' => 255,
'null' => false,
]);
$table->addColumn('expires', 'timestamp', [
'default' => '0000-00-00 00:00:00',
'null' => false,
]);
$table->addIndex([
'model',
'foreign_id',
'series',
], [
'name' => 'U_token_identifier',
'unique' => true,
]);
$table->create();
}
}
|
Add js, coffee, yaml, json flags
fixes #3 | /*
* grunt-generate-configs
* https://github.com/creynders/grunt-generate-configs
*
* Copyright (c) 2014 Camille Reynders
* Licensed under the MIT license.
*/
'use strict';
var inquirer = require('inquirer');
var writeFiles = require('./lib/writeFiles');
module.exports = function(grunt){
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntjs.com/creating-tasks
grunt.registerTask('generate_configs', 'Splits your grunt configuration into separate files', function(){
var done = this.async();
var type;
if(grunt.option('json')){
type = 'json';
}
if(grunt.option('js')){
type = 'js';
}
if(grunt.option('coffee')){
type = 'coffee';
}
if(grunt.option('yaml')){
type = 'yaml';
}
var type = type || grunt.option('type') || 'json';
var opts = {
target : grunt.option('target') || 'config',
type : type,
data : grunt.config.data,
log : grunt.log.writeln
};
if(grunt.file.exists(opts.target)){
inquirer.prompt(
[
{
type : "confirm",
message : "A directory '" + opts.target + "' already exists, its files will be overwritten.\nAre you sure you want to continue?",
name : "overwrite",
default : false
}
], function(answers){
if(answers.overwrite){
writeFiles(opts);
done(true);
}else{
done(false);
}
});
}else{
writeFiles(opts);
done(true);
}
});
};
| /*
* grunt-generate-configs
* https://github.com/creynders/grunt-generate-configs
*
* Copyright (c) 2014 Camille Reynders
* Licensed under the MIT license.
*/
'use strict';
var inquirer = require('inquirer');
var writeFiles = require('./lib/writeFiles');
module.exports = function(grunt){
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntjs.com/creating-tasks
grunt.registerTask('generate_configs', 'Splits your grunt configuration into separate files', function(){
var done = this.async();
var opts = {
target : grunt.option('target') || 'config',
type : grunt.option('type') || 'json',
data : grunt.config.data,
log : grunt.log.writeln
};
if(grunt.file.exists(opts.target)){
inquirer.prompt(
[
{
type : "confirm",
message : "A directory '" + opts.target + "' already exists, its files will be overwritten.\nAre you sure you want to continue?",
name : "overwrite",
default : false
}
], function(answers){
if(answers.overwrite){
writeFiles(opts);
done(true);
}else{
done(false);
}
});
}else{
writeFiles(opts);
done(true);
}
});
};
|
Fix namespacing of generated if | <?php
$vendor_path = 'vendor-bin/box/vendor/humbug/php-scoper/src/PhpParser/NodeVisitor/ClassAliasStmtAppender.php';
if (!file_exists($vendor_path)) {
die('Vendor file does not exist' . PHP_EOL);
}
$search = '/* @var FullyQualified $originalName */
$stmts[] = $this->createAliasStmt($originalName, $stmt);';
$replace = '/* @var FullyQualified $originalName */
$aliasStmt = $this->createAliasStmt($originalName, $stmt);
$stmts[] = new Node\Stmt\If_(
new Node\Expr\BooleanNot(
new Node\Expr\FuncCall(
new FullyQualified(\'class_exists\'),
[
new Node\Arg(
new Node\Expr\ClassConstFetch(
$originalName,
\'class\'
)
),
new Node\Arg(
new Node\Expr\ConstFetch(
new Node\Name(\'false\')
)
)
]
)
),
[\'stmts\' => [$aliasStmt]]
);';
$contents = file_get_contents($vendor_path);
$contents = str_replace($search, $replace, $contents);
file_put_contents($vendor_path, $contents);
| <?php
$vendor_path = 'vendor-bin/box/vendor/humbug/php-scoper/src/PhpParser/NodeVisitor/ClassAliasStmtAppender.php';
if (!file_exists($vendor_path)) {
die('Vendor file does not exist' . PHP_EOL);
}
$search = '/* @var FullyQualified $originalName */
$stmts[] = $this->createAliasStmt($originalName, $stmt);';
$replace = '/* @var FullyQualified $originalName */
$aliasStmt = $this->createAliasStmt($originalName, $stmt);
$stmts[] = new If_(
new FuncCall(
new FullyQualified(\'class_exists\'),
[
new Node\Arg(
new Node\Expr\ClassConstFetch(
$originalName,
\'class\'
)
),
new Node\Arg(
new Node\Expr\ConstFetch(
new Node\Name(\'false\')
)
)
]
),
[\'stmts\' => [$aliasStmt]]
);';
$contents = file_get_contents($vendor_path);
$contents = str_replace($search, $replace, $contents);
file_put_contents($vendor_path, $contents);
|
Put the time summary in an html table | # -*- encoding: utf-8 -*-
import logging
from celery import shared_task
from django.utils import timezone
from invoice.models import InvoiceUser
from mail.service import queue_mail_message
from mail.tasks import process_mail
from .report import time_summary
logger = logging.getLogger(__name__)
@shared_task
def mail_time_summary():
users = []
for item in InvoiceUser.objects.all():
if item.mail_time_summary and item.user.email:
users.append(item.user)
for user in users:
logger.info('mail_time_summary: {}'.format(user.username))
report = time_summary(user, days=1)
message = '<table border="0">'
for d, summary in report.items():
message = message + '<tr colspan="3">'
message = message + '<td>{}</td>'.format(d.strftime('%d/%m/%Y %A'))
message = message + '</tr>'
for ticket in summary['tickets']:
message = message + '<tr>'
message = message + '<td>{}</td>'.format(ticket['pk'])
message = message + '<td>{}, {}</td>'.format(
ticket['contact'],
ticket['description'],
)
message = message + '<td>{}</td>'.format(
ticket['format_minutes'],
)
message = message + '</tr>'
message = message + '<tr>'
message = message + '<td></td><td></td>'
message = message + '<td><b>{}</b></td>'.format(
summary['format_total']
)
message = message + '</tr>'
message = message + '</table>'
queue_mail_message(
user,
[user.email],
'Time Summary for {}'.format(timezone.now().strftime('%d/%m/%Y')),
message,
)
if users:
process_mail.delay()
| # -*- encoding: utf-8 -*-
import logging
from celery import shared_task
from django.utils import timezone
from invoice.models import InvoiceUser
from mail.service import queue_mail_message
from mail.tasks import process_mail
from .report import time_summary
logger = logging.getLogger(__name__)
@shared_task
def mail_time_summary():
users = []
for item in InvoiceUser.objects.all():
if item.mail_time_summary and item.user.email:
users.append(item.user)
for user in users:
logger.debug('mail_time_summary: {}'.format(user.username))
report = time_summary(user, days=1)
message = ''
for d, summary in report.items():
message = message + '\n\n{}, total time {}'.format(
d.strftime('%d/%m/%Y %A'),
summary['format_total'],
)
for ticket in summary['tickets']:
message = message + '\n{}: {}, {} ({})'.format(
ticket['pk'],
ticket['contact'],
ticket['description'],
ticket['format_minutes'],
)
queue_mail_message(
user,
[user.email],
'Time Summary for {}'.format(timezone.now().strftime('%d/%m/%Y')),
message,
)
if users:
process_mail.delay()
|
Make test suite pass when there are no tests | from pathlib import Path
import shutil
from subprocess import call
from django.core.management.base import BaseCommand
from django.core.management import call_command
from django.conf import settings
BABEL_CONF = '''
module.exports = {
presets: [
[
'@babel/preset-env',
{
targets: {
node: 'current',
},
},
],
],
}
'''
class Command(BaseCommand):
help = 'Run jest unit tests.'
def handle(self, *ars, **options):
call_command('transpile')
p = Path(settings.PROJECT_PATH) / '.transpile'
shutil.os.chdir(p)
conf_file = p / 'babel.config.js'
if not conf_file.exists():
print(f'Creating "babel.config.js" at {p}.')
conf_file.write_text(BABEL_CONF)
command_array = [
p / 'node_modules' / '.bin' / 'jest',
'--no-cache',
'--passWithNoTests',
]
return_value = call(command_array)
if return_value > 0:
exit(return_value)
| from pathlib import Path
import shutil
from subprocess import call
from django.core.management.base import BaseCommand
from django.core.management import call_command
from django.conf import settings
BABEL_CONF = '''
module.exports = {
presets: [
[
'@babel/preset-env',
{
targets: {
node: 'current',
},
},
],
],
}
'''
class Command(BaseCommand):
help = 'Run jest unit tests.'
def handle(self, *ars, **options):
call_command('transpile')
p = Path(settings.PROJECT_PATH) / '.transpile'
shutil.os.chdir(p)
conf_file = p / 'babel.config.js'
if not conf_file.exists():
print(f'Creating "babel.config.js" at {p}.')
conf_file.write_text(BABEL_CONF)
command_array = [
p / 'node_modules' / '.bin' / 'jest',
'--no-cache',
]
return_value = call(command_array)
if return_value > 0:
exit(return_value)
|
Use file scope cache to detect main function in file | package org.jetbrains.kotlin.ui.launch;
import org.eclipse.core.expressions.PropertyTester;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.jetbrains.kotlin.core.builder.KotlinPsiManager;
import org.jetbrains.kotlin.core.model.KotlinAnalysisFileCache;
import org.jetbrains.kotlin.idea.MainFunctionDetector;
import org.jetbrains.kotlin.psi.JetFile;
import org.jetbrains.kotlin.resolve.BindingContext;
public class KotlinLaunchableTester extends PropertyTester {
@Override
public boolean test(Object receiver, String property, Object[] args, Object expectedValue) {
if (receiver instanceof IAdaptable) {
IFile file = (IFile) ((IAdaptable) receiver).getAdapter(IFile.class);
if (file != null) {
JetFile jetFile = KotlinPsiManager.getKotlinParsedFile(file);
if (jetFile == null) {
return false;
}
IJavaProject javaProject = JavaCore.create(file.getProject());
BindingContext bindingContext = KotlinAnalysisFileCache.INSTANCE$.getAnalysisResult(jetFile, javaProject)
.getAnalysisResult().getBindingContext();
return new MainFunctionDetector(bindingContext).hasMain(jetFile.getDeclarations());
}
}
return false;
}
}
| package org.jetbrains.kotlin.ui.launch;
import org.eclipse.core.expressions.PropertyTester;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.jetbrains.kotlin.core.builder.KotlinPsiManager;
import org.jetbrains.kotlin.core.model.KotlinAnalysisProjectCache;
import org.jetbrains.kotlin.idea.MainFunctionDetector;
import org.jetbrains.kotlin.psi.JetFile;
import org.jetbrains.kotlin.resolve.BindingContext;
public class KotlinLaunchableTester extends PropertyTester {
@Override
public boolean test(Object receiver, String property, Object[] args, Object expectedValue) {
if (receiver instanceof IAdaptable) {
IFile file = (IFile) ((IAdaptable) receiver).getAdapter(IFile.class);
if (file != null) {
JetFile jetFile = KotlinPsiManager.getKotlinParsedFile(file);
if (jetFile == null) {
return false;
}
IJavaProject javaProject = JavaCore.create(file.getProject());
BindingContext bindingContext = KotlinAnalysisProjectCache.INSTANCE$.getAnalysisResult(javaProject).getBindingContext();
return new MainFunctionDetector(bindingContext).hasMain(jetFile.getDeclarations());
}
}
return false;
}
}
|
Move Zig source normalization to `create_files`
This actually works, even if I don't know why. | from dmoj.executors.compiled_executor import CompiledExecutor
class Executor(CompiledExecutor):
ext = 'zig'
name = 'ZIG'
command = 'zig'
test_program = '''
const std = @import("std");
pub fn main() !void {
const io = std.io;
const stdin = std.io.getStdIn().inStream();
const stdout = std.io.getStdOut().outStream();
var line_buf: [50]u8 = undefined;
while (try stdin.readUntilDelimiterOrEof(&line_buf, '\n')) |line| {
if (line.len == 0) break;
try stdout.print("{}", .{line});
}
}'''
def create_files(self, problem_id, source_code, *args, **kwargs):
# This cleanup needs to happen because Zig refuses to compile carriage returns.
# See <https://github.com/ziglang/zig/issues/544>.
source_code = source_code.replace(b'\r\n', b'\r').replace(b'\r', b'\n')
super().create_files(problem_id, source_code, *args, **kwargs)
def get_compile_args(self):
return [
self.get_command(),
'build-exe',
self._code,
'--release-safe',
'--name',
self.problem,
]
@classmethod
def get_version_flags(cls, command):
return ['version']
| from dmoj.executors.compiled_executor import CompiledExecutor
class Executor(CompiledExecutor):
ext = 'zig'
name = 'ZIG'
command = 'zig'
test_program = '''
const std = @import("std");
pub fn main() !void {
const io = std.io;
const stdin = std.io.getStdIn().inStream();
const stdout = std.io.getStdOut().outStream();
var line_buf: [50]u8 = undefined;
while (try stdin.readUntilDelimiterOrEof(&line_buf, '\n')) |line| {
if (line.len == 0) break;
try stdout.print("{}", .{line});
}
}'''
def __init__(self, problem_id, source_code, **kwargs):
# this clean needs to happen because zig refuses to compile carriage returns
# https://github.com/ziglang/zig/issues/544
code = source_code.replace(b'\r\n', b'\r').replace(b'\r', b'\n')
super().__init__(problem_id, code, **kwargs)
def get_compile_args(self):
return [
self.get_command(),
'build-exe',
self._code,
'--release-safe',
'--name',
self.problem,
]
@classmethod
def get_version_flags(cls, command):
return ['version']
|
Fix --raw option for help command | <?php
/**
* @file
* Override Symfony Console's HelpCommand to customize the appearance of help.
*/
namespace Platformsh\Cli\Command;
use Platformsh\Cli\CustomTextDescriptor;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Command\HelpCommand as ParentHelpCommand;
use Symfony\Component\Console\Helper\DescriptorHelper;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class HelpCommand extends ParentHelpCommand
{
protected $command;
/**
* @inheritdoc
*/
public function setCommand(Command $command)
{
$this->command = $command;
}
/**
* @inheritdoc
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
if (null === $this->command) {
$this->command = $this->getApplication()
->find($input->getArgument('command_name'));
}
if ($input->getOption('xml')) {
$input->setOption('format', 'xml');
}
$helper = new DescriptorHelper();
$helper->register('txt', new CustomTextDescriptor());
$helper->describe(
$output,
$this->command,
array(
'format' => $input->getOption('format'),
'raw_text' => $input->getOption('raw'),
)
);
}
}
| <?php
/**
* @file
* Override Symfony Console's HelpCommand to customize the appearance of help.
*/
namespace Platformsh\Cli\Command;
use Platformsh\Cli\CustomTextDescriptor;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Command\HelpCommand as ParentHelpCommand;
use Symfony\Component\Console\Helper\DescriptorHelper;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class HelpCommand extends ParentHelpCommand
{
protected $command;
/**
* @inheritdoc
*/
public function setCommand(Command $command)
{
$this->command = $command;
}
/**
* @inheritdoc
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
if (null === $this->command) {
$this->command = $this->getApplication()
->find($input->getArgument('command_name'));
}
if ($input->getOption('xml')) {
$input->setOption('format', 'xml');
}
$helper = new DescriptorHelper();
$helper->register('txt', new CustomTextDescriptor());
$helper->describe(
$output,
$this->command,
array(
'format' => $input->getOption('format'),
'raw' => $input->getOption('raw'),
)
);
}
}
|
Change Planning to Pre Alpha | #!/usr/bin/env python
from setuptools import setup, find_packages
def install():
setup(
name='dogu',
version='1.0',
license='MIT',
description='Dogu server, Implementation of dogu interace',
long_description='Dogu server, Implementation of dogu interace',
author='Luavis Kang',
author_email='[email protected]',
url='https://github.com/SomaSoma/dogu',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'License :: Freeware',
'Operating System :: POSIX',
'Operating System :: Microsoft :: Windows',
'Operating System :: MacOS :: MacOS X',
'Topic :: Scientific/Engineering :: Interface Engine/Protocol Translator',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'],
packages=find_packages(),
install_requires=[
'pytest==2.7.2',
'gevent==1.1b3',
'hpack==1.1.0',
'daemonize==2.3.1',
],
scripts=["dogu-server"],
)
if __name__ == "__main__":
install()
| #!/usr/bin/env python
from setuptools import setup, find_packages
def install():
setup(
name='dogu',
version='1.0',
license='MIT',
description='Dogu server, Implementation of dogu interace',
long_description='Dogu server, Implementation of dogu interace',
author='Luavis Kang',
author_email='[email protected]',
url='https://github.com/SomaSoma/dogu',
classifiers=[
'Development Status :: 1 - Planning',
'License :: Freeware',
'Operating System :: POSIX',
'Operating System :: Microsoft :: Windows',
'Operating System :: MacOS :: MacOS X',
'Topic :: Scientific/Engineering :: Interface Engine/Protocol Translator',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'],
packages=find_packages(),
install_requires=[
'pytest==2.7.2',
'gevent==1.1b3',
'hpack==1.1.0',
'daemonize==2.3.1',
],
script="dogu-server"
)
if __name__ == "__main__":
install()
|
Replace ternary by default value | import React, { Component } from 'react'
import Card from '../Card'
const DEBOUNCE_MS = 500
const DEFAULT_DOMAIN = 'https://stripe.com'
export default class extends Component {
state = { domain: DEFAULT_DOMAIN }
onChange = e => {
const domain = e.target.value.trim() || DEFAULT_DOMAIN
clearTimeout(this.debouncedSetState)
this.debouncedSetState = setTimeout(
() => this.setState({ domain }),
DEBOUNCE_MS
)
}
render = () => (
<main className='vh-100 dt w-100 bg-grey-50'>
<div className='tc white ph3 ph4-l'>
<h1 className='f2 fw6 tc pv4 grey-700 avenir'>
react-atv-logo
</h1>
<div className='flex justify-center flex-column items-center'>
<Card className='pb4' domain={this.state.domain} />
<form className='pa4 pb4 black-80 w-30-l'>
<div className='measure'>
<input
id='name'
className='input-reset ba b--black-20 pa2 mb2 db w-100 br2'
type='text'
placeholder='Enter domain...'
onChange={this.onChange}
/>
</div>
</form>
</div>
</div>
</main>
)
}
| import React, { Component } from 'react'
import Card from '../Card'
const DEBOUNCE_MS = 500
const DEFAULT_DOMAIN = 'https://stripe.com'
export default class extends Component {
state = { domain: DEFAULT_DOMAIN }
onChange = e => {
const domain = e.target.value.trim()
clearTimeout(this.debouncedSetState)
this.debouncedSetState = setTimeout(() => (!domain || domain === '')
? this.setState({ domain: DEFAULT_DOMAIN })
: this.setState({ domain }), DEBOUNCE_MS)
}
render = () => (
<main className='vh-100 dt w-100 bg-grey-50'>
<div className='tc white ph3 ph4-l'>
<h1 className='f2 fw6 tc pv4 grey-700 avenir'>
react-atv-logo
</h1>
<div className='flex justify-center flex-column items-center'>
<Card className='pb4' domain={this.state.domain} />
<form className='pa4 pb4 black-80 w-30-l'>
<div className='measure'>
<input
id='name'
className='input-reset ba b--black-20 pa2 mb2 db w-100 br2'
type='text'
placeholder='Enter domain...'
onChange={this.onChange}
/>
</div>
</form>
</div>
</div>
</main>
)
}
|
Write the critical multiplier or the range when the damage gets converted into a String | from random import random
class Die:
"""
Abstracts the random dice throw. Roll will produce the result.
The die can be further parametrized by a multiplicator and/or
a modifier, like 2 * Die(8) +4.
"""
def __init__(self, number, multiplicator=1, modifier=0):
self.number = number
self.multiplicator = multiplicator
self.modifier = modifier
def roll(self):
return self.multiplicator * random.choice(range(1, self.number + 1)) + self.modifier
def __rmul__(self, other):
return Die(self.number, multiplicator=other, modifier=self.modifier)
def __add__(self, other):
return Die(self.number, multiplicator=self.multiplicator, modifier=other)
def __call__(self):
return self.roll()
def __eq__(self, other):
return (other.number == self.number and
other.multiplicator == self.multiplicator and
other.modifier == self.modifier)
@classmethod
def parse(cls, text):
return cls.__new__()
def __repr__(self):
base = "%sd%s" % (self.multiplicator, self.number)
if self.modifier > 0:
return base + ("+%s" % self.modifier)
return base
d4 = Die(4)
d6 = Die(6)
d8 = Die(8)
d10 = Die(10)
d12 = Die(12)
d20 = Die(20)
d100 = Die(100) | from random import random
class Die:
"""
Abstracts the random dice throw. Roll will produce the result.
The die can be further parametrized by a multiplicator and/or
a modifier, like 2 * Die(8) +4.
"""
def __init__(self, number, multiplicator=1, modifier=0):
self.number = number
self.multiplicator = multiplicator
self.modifier = modifier
def roll(self):
return self.multiplicator * random.choice(range(1, self.number + 1)) + self.modifier
def __rmul__(self, other):
return Die(self.number, multiplicator=other, modifier=self.modifier)
def __add__(self, other):
return Die(self.number, multiplicator=self.multiplicator, modifier=other)
def __call__(self):
return self.roll()
def __eq__(self, other):
return (other.number == self.number and
other.multiplicator == self.multiplicator and
other.modifier == self.modifier)
@classmethod
def parse(cls, text):
return cls.__new__()
def __repr__(self):
return "%sd%s+%s" % (self.multiplicator, self.number, self.modifier)
d4 = Die(4)
d6 = Die(6)
d8 = Die(8)
d10 = Die(10)
d12 = Die(12)
d20 = Die(20)
d100 = Die(100) |
Make test logging level set by getenv. | import os
try:
from psycopg2cffi import compat
compat.register()
except ImportError:
pass
DEBUG=False
TEMPLATE=DEBUG
USE_TZ = True
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'django-pq',
'USER': 'django-pq',
'PASSWORD': 'django-pq',
'HOST': '127.0.0.1', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': 5432,
'OPTIONS': {'autocommit': True}
},
}
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.admin',
'pq',
)
ROOT_URLCONF='test_pq.urls'
SECRET_KEY = '1234'
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'standard': {
'format': '[%(levelname)s] %(name)s: %(message)s'
},
},
'handlers': {
'console':{
'level':'DEBUG',
'class':"logging.StreamHandler",
'formatter': 'standard'
},
},
'loggers': {
'': {
'handlers': ['console'],
'level': os.getenv('LOGGING_LEVEL', 'CRITICAL'),
'propagate': True
},
}
}
| try:
from psycopg2cffi import compat
compat.register()
except ImportError:
pass
DEBUG=False
TEMPLATE=DEBUG
USE_TZ = True
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'django-pq',
'USER': 'django-pq',
'PASSWORD': 'django-pq',
'HOST': '127.0.0.1', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': 5432,
'OPTIONS': {'autocommit': True}
},
}
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.admin',
'pq',
)
ROOT_URLCONF='test_pq.urls'
SECRET_KEY = '1234'
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'standard': {
'format': '[%(levelname)s] %(name)s: %(message)s'
},
},
'handlers': {
'console':{
'level':'DEBUG',
'class':"logging.StreamHandler",
'formatter': 'standard'
},
},
'loggers': {
'': {
'handlers': ['console'],
'level': 'CRITICAL',
'propagate': True
},
}
}
|
Fix adding the geolocation to the cache | 'use strict';
let geolocation = require('nativescript-geolocation');
let requester = require('../web/requester').defaultInstance;
let cacheService = require('../common/cache/cache-service');
let constants = require('../common/constants');
let settings = require('../common/settings');
class GeolocationHelper {
isEnabled() {
return geolocation.isEnabled();
}
enableLocationRequest() {
return geolocation.enableLocationRequest();
}
getCurrentLocation(configuration) {
if (settings.isCacheEnabled() && cacheService.hasItem(constants.CACHE_LOCATION_KEY)) {
return new Promise(function (resolve, reject) {
resolve(cacheService.getItem(constants.CACHE_LOCATION_KEY));
});
}
let promise = new Promise(function (resolve, reject) {
geolocation.getCurrentLocation(configuration)
.then(function(location) {
if (settings.isCacheEnabled()) {
let cacheDuration = settings.cacheDuration();
cacheService.addItem(constants.CACHE_LOCATION_KEY, location, cacheDuration);
}
resolve(location);
}, function (err) {
return requester.getJsonAsync('http://ipinfo.io/json', true);
})
.then(function (response) {
let latitude = +response.loc.split(',')[0];
let longitude = +response.loc.split(',')[1];
let location = {
latitude,
longitude
};
resolve(location);
}, reject);
});
return promise;
}
}
module.exports = {
GeolocationHelper: GeolocationHelper,
defaultInstance: new GeolocationHelper()
}; | 'use strict';
let geolocation = require('nativescript-geolocation');
let requester = require('../web/requester').defaultInstance;
let cacheService = require('../common/cache/cache-service');
let constants = require('../common/constants');
let settings = require('../common/settings');
class GeolocationHelper {
isEnabled() {
return geolocation.isEnabled();
}
enableLocationRequest() {
return geolocation.enableLocationRequest();
}
getCurrentLocation(configuration) {
if (settings.isCacheEnabled() && cacheService.hasItem(constants.CACHE_LOCATION_KEY)) {
return new Promise(function (resolve, reject) {
resolve(cacheService.getItem(constants.CACHE_LOCATION_KEY));
});
}
let promise = new Promise(function (resolve, reject) {
geolocation.getCurrentLocation(configuration)
.then(function(location) {
if (settings.isCacheEnabled()) {
cacheService.addItem(location);
}
resolve(location);
}, function (err) {
return requester.getJsonAsync('http://ipinfo.io/json', true);
})
.then(function (response) {
let latitude = +response.loc.split(',')[0];
let longitude = +response.loc.split(',')[1];
let location = {
latitude,
longitude
};
resolve(location);
}, reject);
});
return promise;
}
}
module.exports = {
GeolocationHelper: GeolocationHelper,
defaultInstance: new GeolocationHelper()
}; |
Add wos-only option to script | #!/usr/bin/env python3
from parsers.wos import WOSStream
from util.PajekFactory import PajekFactory
from util.misc import open_file, Checkpoint
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Creates Pajek (.net) files from WOS XML")
parser.add_argument('outfile')
parser.add_argument('--wos-only', action="store_true", help="Only include nodes/edges in WOS")
parser.add_argument('infile', nargs='+')
args = parser.parse_args()
chk = Checkpoint()
nodes = args.outfile + ".nodes"
edges = args.outfile + ".edges"
nodes_f = open_file(nodes, "w")
edges_f = open_file(edges, "w")
parsed = 1
total_files = len(args.infile)
pjk = PajekFactory(node_stream=nodes_f, edge_stream=edges_f)
for file in args.infile:
print(chk.checkpoint("Parsing {}: {}/{}: {:.2%}".format(file, parsed, total_files, parsed/float(total_files))))
f = open_file(file)
parser = WOSStream(f, args.wos_only)
for entry in parser.parse():
if "citations" in entry:
for citation in entry["citations"]:
pjk.add_edge(entry["id"], citation)
print(chk.checkpoint(" Done: "+str(pjk)))
parsed += 1
with open_file(args.outfile, "w") as f:
f.writelines(pjk.make_header())
chk.end("Done")
| #!/usr/bin/env python3
from parsers.wos import WOSStream
from util.PajekFactory import PajekFactory
from util.misc import open_file, Checkpoint
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Creates Pajek (.net) files from WOS XML")
parser.add_argument('outfile')
parser.add_argument('infile', nargs='+')
args = parser.parse_args()
chk = Checkpoint()
nodes = args.outfile + ".nodes"
edges = args.outfile + ".edges"
nodes_f = open_file(nodes, "w")
edges_f = open_file(edges, "w")
parsed = 1
total_files = len(args.infile)
pjk = PajekFactory(node_stream=nodes_f, edge_stream=edges_f)
for file in args.infile:
print(chk.checkpoint("Parsing {}: {}/{}: {:.2%}".format(file, parsed, total_files, parsed/float(total_files))))
f = open_file(file)
parser = WOSStream(f)
for entry in parser.parse():
if "citations" in entry:
for citation in entry["citations"]:
pjk.add_edge(entry["id"], citation)
print(chk.checkpoint(" Done: "+str(pjk)))
parsed += 1
with open_file(args.outfile, "w") as f:
f.writelines(pjk.make_header())
chk.end("Done")
|
Remove duplicate code for alternative function | import warnings
import functools
__all__ = ['deprecated']
class deprecated(object):
'''Decorator to mark deprecated functions with warning.
Adapted from <http://wiki.python.org/moin/PythonDecoratorLibrary>.
Parameters
----------
alt_func : str
If given, tell user what function to use instead.
behavior : {'warn', 'raise'}
Behavior during call to deprecated function: 'warn' = warn user that
function is deprecated; 'raise' = raise error.
'''
def __init__(self, alt_func=None, behavior='warn'):
self.alt_func = alt_func
self.behavior = behavior
def __call__(self, func):
alt_msg = ''
if self.alt_func is not None:
alt_msg = ' Use `%s` instead.' % self.alt_func
msg = 'Call to deprecated function `%s`.' % func.__name__
msg += alt_msg
@functools.wraps(func)
def wrapped(*args, **kwargs):
if self.behavior == 'warn':
warnings.warn_explicit(msg,
category=DeprecationWarning,
filename=func.func_code.co_filename,
lineno=func.func_code.co_firstlineno + 1)
elif self.behavior == 'raise':
raise DeprecationWarning(msg)
return func(*args, **kwargs)
# modify doc string to display deprecation warning
doc = 'Deprecated function.' + alt_msg
if wrapped.__doc__ is None:
wrapped.__doc__ = doc
else:
wrapped.__doc__ = doc + '\n\n' + wrapped.__doc__
return wrapped
| import warnings
import functools
__all__ = ['deprecated']
class deprecated(object):
'''Decorator to mark deprecated functions with warning.
Adapted from <http://wiki.python.org/moin/PythonDecoratorLibrary>.
Parameters
----------
alt_func : str
If given, tell user what function to use instead.
behavior : {'warn', 'raise'}
Behavior during call to deprecated function: 'warn' = warn user that
function is deprecated; 'raise' = raise error.
'''
def __init__(self, alt_func=None, behavior='warn'):
self.alt_func = alt_func
self.behavior = behavior
def __call__(self, func):
msg = 'Call to deprecated function `%s`.' % func.__name__
if self.alt_func is not None:
msg += ' Use `%s` instead.' % self.alt_func
@functools.wraps(func)
def wrapped(*args, **kwargs):
if self.behavior == 'warn':
warnings.warn_explicit(msg,
category=DeprecationWarning,
filename=func.func_code.co_filename,
lineno=func.func_code.co_firstlineno + 1)
elif self.behavior == 'raise':
raise DeprecationWarning(msg)
return func(*args, **kwargs)
# modify doc string to display deprecation warning
doc = 'Deprecated function.'
if self.alt_func is not None:
doc += ' Use `%s` instead.' % self.alt_func
if wrapped.__doc__ is None:
wrapped.__doc__ = doc
else:
wrapped.__doc__ = doc + '\n\n' + wrapped.__doc__
return wrapped
|
Add basic formatting to table values | /** Component for showing the queried index data as a table */
define( [
"lodash",
"jquery",
"preferences",
"aspects",
"dataTables.bootstrap"
], function(
_,
$,
Preferences,
Aspects
) {
"use strict";
var DataTableView = function() {
};
_.extend( DataTableView.prototype, {
showQueryResults: function( qr ) {
var aspects = this.preferences().aspects();
var data = this.formulateData( qr, aspects );
$(".c-results").removeClass( "js-hidden" );
$("#results-table").DataTable( {
data: data,
destroy: true, // todo there are more efficient ways than this
columns: [
{title: "Date"},
{title: "Measure"},
{title: "Value", type: "num-fmt", className: "text-right"}
]
} );
},
preferences: function() {
return new Preferences();
},
formulateData: function( qr, aspects ) {
var rowSets = _.map( qr.results(), function( result ) {
var values = result.valuesFor( aspects );
var zValues = _.zip( aspects, values );
return _.map( zValues, function( zv ) {
return [
result.period(),
zv[0],
zv[1] ? formatValue( zv[0], zv[1] ) : null
];
} );
} );
return _.flatten( rowSets );
}
} );
var formatValue = function( aspectName, value ) {
var aspect = Aspects[aspectName];
switch (aspect.unitType) {
case "percentage":
return value + "%";
case "pound_sterling":
return "£" + value;
default:
return value;
}
};
return DataTableView;
} );
| /** Component for showing the queried index data as a table */
define( [
"lodash",
"jquery",
"preferences",
"dataTables.bootstrap"
], function(
_,
$,
Preferences
) {
"use strict";
var DataTableView = function() {
};
_.extend( DataTableView.prototype, {
showQueryResults: function( qr ) {
var aspects = this.preferences().aspects();
var data = this.formulateData( qr, aspects );
$(".c-results").removeClass( "js-hidden" );
$("#results-table").DataTable( {
data: data,
destroy: true, // todo there are more efficient ways than this
columns: [
{title: "Date"},
{title: "Measure"},
{title: "Value", type: "num"}
]
} );
},
preferences: function() {
return new Preferences();
},
formulateData: function( qr, aspects ) {
var rowSets = _.map( qr.results(), function( result ) {
var values = result.valuesFor( aspects );
var zValues = _.zip( aspects, values );
return _.map( zValues, function( zv ) {
return [
result.period(),
zv[0],
zv[1] || null
];
} );
} );
return _.flatten( rowSets );
}
} );
return DataTableView;
} );
|
BB-1413: Cover validation by unit tests
- fix model tests after changes | <?php
namespace Oro\Bundle\EntityExtendBundle\Tests\Unit\Model;
use Oro\Bundle\EntityExtendBundle\Model\EnumValue;
use Oro\Component\Testing\Unit\EntityTestCaseTrait;
class EnumValueTest extends \PHPUnit_Framework_TestCase
{
use EntityTestCaseTrait;
/** @var EnumValue */
protected $enumValue;
/**
* {@inheritdoc}
*/
protected function setUp()
{
$this->enumValue = new EnumValue();
}
public function testProperties()
{
static::assertPropertyAccessors($this->enumValue, [
['id', 'testId'],
['label', 'test label'],
['isDefault', true],
['priority', 100],
]);
}
public function testToArray()
{
static::assertPropertyAccessors($this->enumValue, [
['id', 'testId'],
['label', 'test label'],
['isDefault', true],
['priority', 100],
]);
}
public function testFromToArray()
{
$array = [
'id' => 'testId',
'label' => 'test label',
'is_default' => true,
'priority' => 100,
];
$enumValue = (new EnumValue())
->setLabel('test label')
->setId('testId')
->setIsDefault(true)
->setPriority(100)
;
static::assertEquals($enumValue, EnumValue::createFromArray($array));
static::assertEquals($array, $enumValue->toArray($array));
}
}
| <?php
namespace Oro\Bundle\EntityExtendBundle\Tests\Unit\Model;
use Oro\Bundle\EntityExtendBundle\Model\EnumValue;
use Oro\Component\Testing\Unit\EntityTestCaseTrait;
class EnumValueTest extends \PHPUnit_Framework_TestCase
{
use EntityTestCaseTrait;
/** @var EnumValue */
protected $enumValue;
/**
* {@inheritdoc}
*/
protected function setUp()
{
$this->enumValue = new EnumValue();
}
public function testProperties()
{
static::assertPropertyAccessors($this->enumValue, [
['id', 'testId'],
['label', 'test label'],
['isDefault', true],
['priority', 100],
]);
}
public function testToArray()
{
static::assertPropertyAccessors($this->enumValue, [
['id', 'testId'],
['label', 'test label'],
['isDefault', true],
['priority', 100],
]);
}
public function testFromToArray()
{
$array = [
'id' => 'testId',
'label' => 'test label',
'isDefault' => true,
'priority' => 100,
];
$enumValue = (new EnumValue())
->setLabel('test label')
->setId('testId')
->setIsDefault(true)
->setPriority(100)
;
static::assertEquals($enumValue, (new EnumValue())->fromArray($array));
static::assertEquals($array, $enumValue->toArray($array));
}
}
|
Set display URL from wurl if curl not specified. | import React from 'react';
import PropTypes from 'prop-types';
import url from 'url';
export default class AppPermission extends React.Component {
constructor(props) {
super(props);
const curl = this.getCurl();
this.state = {
curl: curl,
};
console.log('curl', curl);
}
getCurl() {
const wurl = url.parse(this.props.url);
let curl;
const searchParams = new URLSearchParams(wurl.search);
if(searchParams && searchParams.get('url')) {
curl = searchParams.get('url');
}
if (!curl && wurl) {
wurl.search = wurl.query = "";
curl = wurl.format();
}
return curl;
}
render() {
return (
<div className='mx_AppPermissionWarning'>
<div className='mx_AppPermissionWarningImage'>
<img src='img/warning.svg' alt='Warning'/>
</div>
<div className='mx_AppPermissionWarningText'>
<span className='mx_AppPermissionWarningTextLabel'>Do you want to load widget from URL:</span> <span className='mx_AppPermissionWarningTextURL'>{this.state.curl}</span>
</div>
<input
className='mx_AppPermissionButton'
type='button'
value='Allow'
onClick={this.props.onPermissionGranted}
/>
</div>
);
}
}
AppPermission.propTypes = {
url: PropTypes.string.isRequired,
onPermissionGranted: PropTypes.func.isRequired,
};
AppPermission.defaultPropTypes = {
onPermissionGranted: function() {},
};
| import React from 'react';
import PropTypes from 'prop-types';
import url from 'url';
export default class AppPermission extends React.Component {
constructor(props) {
super(props);
const curl = this.getCurl();
this.state = {
curl: curl,
};
console.log('curl', curl);
}
getCurl() {
const wurl = url.parse(this.props.url);
let curl;
const searchParams = new URLSearchParams(wurl.search);
if(searchParams && searchParams.get('url')) {
curl = searchParams.get('url');
}
curl = curl || wurl;
return curl;
}
render() {
return (
<div className='mx_AppPermissionWarning'>
<div className='mx_AppPermissionWarningImage'>
<img src='img/warning.svg' alt='Warning'/>
</div>
<div className='mx_AppPermissionWarningText'>
<span className='mx_AppPermissionWarningTextLabel'>Do you want to load widget from URL?:</span> <span className='mx_AppPermissionWarningTextURL'>{this.state.curl}</span>
</div>
<input
className='mx_AppPermissionButton'
type='button'
value='Allow'
onClick={this.props.onPermissionGranted}
/>
</div>
);
}
}
AppPermission.propTypes = {
url: PropTypes.string.isRequired,
onPermissionGranted: PropTypes.func.isRequired,
};
AppPermission.defaultPropTypes = {
onPermissionGranted: function() {},
};
|
[INT-205] Add deprecation error for using `addLicenseKey` after Shopware 5.5. | <?php
namespace K10rProject\Helpers;
use Shopware\Bundle\PluginInstallerBundle\Service\PluginLicenceService;
use Shopware\Components\Model\ModelManager;
use Shopware\Models\Plugin\License;
class LicenseHelper
{
/** @var PluginLicenceService */
private $licenseService;
/** @var ModelManager */
private $modelManager;
public function __construct(PluginLicenceService $licenseService, ModelManager $modelManager)
{
$this->licenseService = $licenseService;
$this->modelManager = $modelManager;
}
/**
* Add a license key using SwagLicense
*
* @param string $licenseKey
*/
public function addLicenseKey($licenseKey)
{
if (method_exists($this->licenseService, 'importLicence')) { // SW 5.5 compatibility
$this->licenseService->importLicence($licenseKey);
} else {
trigger_error('There is no plugin license management after Shopware 5.5', E_USER_DEPRECATED);
}
}
/**
* Removes a license for a Plugin or Module, given by name.
*
* @param string $pluginName
*
* @return bool
*/
public function removeLicenseByPluginName($pluginName)
{
$license = $this->modelManager->getRepository(License::class)->findOneBy(['module' => $pluginName]);
if (!$license instanceof License) {
return false;
}
$this->modelManager->remove($license);
$this->modelManager->flush();
return true;
}
}
| <?php
namespace K10rProject\Helpers;
use Shopware\Bundle\PluginInstallerBundle\Service\PluginLicenceService;
use Shopware\Components\Model\ModelManager;
use Shopware\Models\Plugin\License;
class LicenseHelper
{
/** @var PluginLicenceService */
private $licenseService;
/** @var ModelManager */
private $modelManager;
public function __construct(PluginLicenceService $licenseService, ModelManager $modelManager)
{
$this->licenseService = $licenseService;
$this->modelManager = $modelManager;
}
/**
* Add a license key using SwagLicense
*
* @param string $licenseKey
*/
public function addLicenseKey($licenseKey)
{
if (method_exists($this->licenseService, 'importLicence')) { // SW 5.5 compatibility
$this->licenseService->importLicence($licenseKey);
}
}
/**
* Removes a license for a Plugin or Module, given by name.
*
* @param string $pluginName
*
* @return bool
*/
public function removeLicenseByPluginName($pluginName)
{
$license = $this->modelManager->getRepository(License::class)->findOneBy(['module' => $pluginName]);
if (!$license instanceof License) {
return false;
}
$this->modelManager->remove($license);
$this->modelManager->flush();
return true;
}
}
|
Add eslint 'fix' flag to config.
Can be flipped to 'true' to auto-fix linting violations! | module.exports = function (grunt) {
var allJSFilesInJSFolder = "js/**/*.js";
var distFolder = '../wikipedia/assets/';
grunt.loadNpmTasks( 'grunt-browserify' );
grunt.loadNpmTasks( 'gruntify-eslint' );
grunt.loadNpmTasks( 'grunt-contrib-copy' );
grunt.loadNpmTasks( 'grunt-contrib-less' );
grunt.initConfig( {
browserify: {
distMain: {
src: ["index-main.js", allJSFilesInJSFolder, "!preview-main.js"],
dest: distFolder + "index.js"
},
distPreview: {
src: ["preview-main.js", "js/utilities.js"],
dest: distFolder + "preview.js"
}
},
less: {
all: {
options: {
compress: true,
yuicompress: true,
optimization: 2
},
files: [
{ src: ["less/**/*.less", "node_modules/wikimedia-page-library/build/wikimedia-page-library-transform.css"], dest: distFolder + "styleoverrides.css"}
]
}
},
eslint: {
src: [allJSFilesInJSFolder],
options: {
fix: false
}
},
copy: {
main: {
files: [{
src: ["*.html",
"*.css",
"ios.json",
"languages.json",
"mainpages.json",
"*.png"],
dest: distFolder
}]
}
}
} );
grunt.registerTask('default', ['eslint', 'browserify', 'less', 'copy']);
};
| module.exports = function (grunt) {
var allJSFilesInJSFolder = "js/**/*.js";
var distFolder = '../wikipedia/assets/';
grunt.loadNpmTasks( 'grunt-browserify' );
grunt.loadNpmTasks( 'gruntify-eslint' );
grunt.loadNpmTasks( 'grunt-contrib-copy' );
grunt.loadNpmTasks( 'grunt-contrib-less' );
grunt.initConfig( {
browserify: {
distMain: {
src: ["index-main.js", allJSFilesInJSFolder, "!preview-main.js"],
dest: distFolder + "index.js"
},
distPreview: {
src: ["preview-main.js", "js/utilities.js"],
dest: distFolder + "preview.js"
}
},
less: {
all: {
options: {
compress: true,
yuicompress: true,
optimization: 2
},
files: [
{ src: ["less/**/*.less", "node_modules/wikimedia-page-library/build/wikimedia-page-library-transform.css"], dest: distFolder + "styleoverrides.css"}
]
}
},
eslint: {
src: [allJSFilesInJSFolder]
},
copy: {
main: {
files: [{
src: ["*.html",
"*.css",
"ios.json",
"languages.json",
"mainpages.json",
"*.png"],
dest: distFolder
}]
}
}
} );
grunt.registerTask('default', ['eslint', 'browserify', 'less', 'copy']);
};
|
Add header comments
Remove magic numbers | //@@author A0139248X
package seedu.ezdo.model;
import java.util.EmptyStackException;
/**
* Array-based implementation for a stack with fixed size. Used for undo & redo stacks.
* If stack goes past max capacity, the oldest item that was pushed is replaced.
*/
public class FixedStack<T> {
private static final int STARTING_INDEX = -1;
private int index;
private T[] array;
public FixedStack(int capacity) {
array = (T[]) new Object[capacity];
index = STARTING_INDEX;
}
public void push(T item) {
index = (index + 1) % ModelManager.STACK_CAPACITY; // wraps around
array[index] = item;
}
public T pop() throws EmptyStackException {
if (index == STARTING_INDEX || array[index] == null) {
throw new EmptyStackException();
}
T item = array[index];
array[index] = null;
if (index == 0) { // top of stack is 0, need to wrap around
index = array.length - 1;
} else {
index = index - 1;
}
return item;
}
public boolean isEmpty() {
for (int i = 0; i < array.length; i++) {
if (array[i] != null) {
return false;
}
}
return true;
}
public void clear() {
for (int i = 0; i < array.length; i++) {
array[i] = null;
}
index = STARTING_INDEX;
}
}
| package seedu.ezdo.model;
import java.util.EmptyStackException;
//@@author A0139248X
/*
* Array-based implementation for a stack with fixed size. Used for undo & redo stacks.
* If stack goes past max capacity, the oldest item to be pushed is replaced.
*/
public class FixedStack<T> {
private int index;
private T[] array;
public FixedStack(int capacity) {
array = (T[]) new Object[capacity];
index = -1;
}
public void push(T item) {
index = (index + 1) % ModelManager.STACK_CAPACITY; // wraps around
array[index] = item;
}
public T pop() throws EmptyStackException {
if (index == -1 || array[index] == null) {
throw new EmptyStackException();
}
T item = array[index];
array[index] = null;
if (index == 0) {
index = array.length - 1;
} else {
index = index - 1;
}
return item;
}
public boolean isEmpty() {
for (int i = 0; i < array.length; i++) {
if (array[i] != null) {
return false;
}
}
return true;
}
public void clear() {
for (int i = 0; i < array.length; i++) {
array[i] = null;
}
index = -1;
}
}
|
Add force pull image option in docker sub entity | <?php
/**
* @package: chapi
*
* @author: bthapaliya
* @since: 2016-10-16
*
*/
namespace Chapi\Entity\Marathon\AppEntity;
use Chapi\Entity\Marathon\AppEntity\DockerParameters;
use Chapi\Entity\Marathon\AppEntity\DockerPortMapping;
use Chapi\Entity\Marathon\MarathonEntityUtils;
class Docker
{
const DIC = self::class;
public $image = '';
public $network = '';
/**
* @var DockerPortMapping[]
*/
public $portMappings = [];
public $privileged = false;
public $forcePullImage = false;
/**
* @var DockerParameters
*/
public $parameters = [];
public function __construct($aData = [])
{
MarathonEntityUtils::setAllPossibleProperties($aData, $this);
if (isset($aData['portMappings']))
{
foreach ($aData['portMappings'] as $portMapping)
{
$this->portMappings[] = new DockerPortMapping((array) $portMapping);
}
}
if (isset($aData['parameters']))
{
foreach ($aData['parameters'] as $parameter)
{
$this->parameters[] = new DockerParameters((array) $parameter);
}
}
}
} | <?php
/**
* @package: chapi
*
* @author: bthapaliya
* @since: 2016-10-16
*
*/
namespace Chapi\Entity\Marathon\AppEntity;
use Chapi\Entity\Marathon\AppEntity\DockerParameters;
use Chapi\Entity\Marathon\AppEntity\DockerPortMapping;
use Chapi\Entity\Marathon\MarathonEntityUtils;
class Docker
{
const DIC = self::class;
public $image = '';
public $network = '';
/**
* @var DockerPortMapping[]
*/
public $portMappings = [];
public $privileged = false;
/**
* @var DockerParameters
*/
public $parameters = [];
public function __construct($aData = [])
{
MarathonEntityUtils::setAllPossibleProperties($aData, $this);
if (isset($aData['portMappings']))
{
foreach ($aData['portMappings'] as $portMapping)
{
$this->portMappings[] = new DockerPortMapping((array) $portMapping);
}
}
if (isset($aData['parameters']))
{
foreach ($aData['parameters'] as $parameter)
{
$this->parameters[] = new DockerParameters((array) $parameter);
}
}
}
} |
Add croniter as an install dependency. | # -*- coding: utf-8 -*-
import os
from setuptools import find_packages
from setuptools import setup
base_dir = os.path.dirname(__file__)
setup(
name='elastalert',
version='0.0.72',
description='Runs custom filters on Elasticsearch and alerts on matches',
author='Quentin Long',
author_email='[email protected]',
setup_requires='setuptools',
license='Copyright 2014 Yelp',
entry_points={
'console_scripts': ['elastalert-create-index=elastalert.create_index:main',
'elastalert-test-rule=elastalert.test_rule:main',
'elastalert-rule-from-kibana=elastalert.rule_from_kibana:main',
'elastalert=elastalert.elastalert:main']},
packages=find_packages(),
package_data={'elastalert': ['schema.yaml']},
install_requires=[
'argparse',
'elasticsearch',
'jira==0.32', # jira.exceptions is missing from later versions
'jsonschema',
'mock',
'python-dateutil',
'PyStaticConfiguration',
'pyyaml',
'simplejson',
'boto',
'blist',
'croniter'
]
)
| # -*- coding: utf-8 -*-
import os
from setuptools import find_packages
from setuptools import setup
base_dir = os.path.dirname(__file__)
setup(
name='elastalert',
version='0.0.72',
description='Runs custom filters on Elasticsearch and alerts on matches',
author='Quentin Long',
author_email='[email protected]',
setup_requires='setuptools',
license='Copyright 2014 Yelp',
entry_points={
'console_scripts': ['elastalert-create-index=elastalert.create_index:main',
'elastalert-test-rule=elastalert.test_rule:main',
'elastalert-rule-from-kibana=elastalert.rule_from_kibana:main',
'elastalert=elastalert.elastalert:main']},
packages=find_packages(),
package_data={'elastalert': ['schema.yaml']},
install_requires=[
'argparse',
'elasticsearch',
'jira==0.32', # jira.exceptions is missing from later versions
'jsonschema',
'mock',
'python-dateutil',
'PyStaticConfiguration',
'pyyaml',
'simplejson',
'boto',
'blist'
]
)
|
Add test to check that uris are set | from mopidy.models import Track
class BaseCurrentPlaylistControllerTest(object):
uris = []
backend_class = None
def setUp(self):
self.backend = self.backend_class()
def test_uri_set(self):
self.assert_(self.uris)
def test_add(self):
playlist = self.backend.current_playlist
for uri in self.uris:
playlist.add(uri)
self.assertEqual(uri, playlist.tracks[-1].uri)
def test_add_at_position(self):
playlist = self.backend.current_playlist
for uri in self.uris:
playlist.add(uri, 0)
self.assertEqual(uri, playlist.tracks[0].uri)
# FIXME test other placements
class BasePlaybackControllerTest(object):
backend_class = None
def setUp(self):
self.backend = self.backend_class()
def test_play_with_no_current_track(self):
playback = self.backend.playback
self.assertEqual(playback.state, playback.STOPPED)
result = playback.play()
self.assertEqual(result, False)
self.assertEqual(playback.state, playback.STOPPED)
def test_next(self):
playback = self.backend.playback
current_song = playback.playlist_position
playback.next()
self.assertEqual(playback.playlist_position, current_song+1)
| from mopidy.models import Track
class BaseCurrentPlaylistControllerTest(object):
uris = []
backend_class = None
def setUp(self):
self.backend = self.backend_class()
def test_add(self):
playlist = self.backend.current_playlist
for uri in self.uris:
playlist.add(uri)
self.assertEqual(uri, playlist.tracks[-1].uri)
def test_add_at_position(self):
playlist = self.backend.current_playlist
for uri in self.uris:
playlist.add(uri, 0)
self.assertEqual(uri, playlist.tracks[0].uri)
# FIXME test other placements
class BasePlaybackControllerTest(object):
backend_class = None
def setUp(self):
self.backend = self.backend_class()
def test_play_with_no_current_track(self):
playback = self.backend.playback
self.assertEqual(playback.state, playback.STOPPED)
result = playback.play()
self.assertEqual(result, False)
self.assertEqual(playback.state, playback.STOPPED)
def test_next(self):
playback = self.backend.playback
current_song = playback.playlist_position
playback.next()
self.assertEqual(playback.playlist_position, current_song+1)
|
Send title to navigator on control panel item press |
import React, {View, Text, Linking} from 'react-native'
import {logout} from '../api/Account'
import Styles from '../styles/Styles'
import ControlPanelItem from '../components/ControlPanelItem'
import Settings from '../settings'
export default React.createClass({
render() {
return (
<View style={Styles.controlPanel.container}>
<ControlPanelItem
onPress={()=>{
this.props.closeDrawer();
this.props.logout();
}}
text="Logout"
/>
<ControlPanelItem
onPress={()=>{
this.props.navigator.push({name: 'surveylist', title: "Surveys"})
this.props.closeDrawer()
}}
text="Surveys"
/>
<ControlPanelItem
text="Notifications"
/>
<ControlPanelItem
text="Profile"
/>
<ControlPanelItem
text="Account"
/>
<ControlPanelItem
onPress={()=>{
// mailto links do not work in the ios simulator.
// https://github.com/facebook/react-native/issues/916
// TODO: Set up support mailing list
Linking.openURL("mailto:[email protected]?subject=Support")
.catch(err => console.error('An error occurred', err))
this.props.closeDrawer()
}}
text="Support"
/>
<View style={Styles.controlPanel.item}>
<Text>Version: {Settings.version || "None"}</Text>
</View>
</View>
)
}
})
|
import React, {View, Text, Linking} from 'react-native'
import {logout} from '../api/Account'
import Styles from '../styles/Styles'
import ControlPanelItem from '../components/ControlPanelItem'
import Settings from '../settings'
export default React.createClass({
render() {
return (
<View style={Styles.controlPanel.container}>
<ControlPanelItem
onPress={()=>{
this.props.closeDrawer();
this.props.logout();
}}
text="Logout"
/>
<ControlPanelItem
onPress={()=>{
this.props.navigator.push({name: 'surveylist'})
this.props.closeDrawer()
}}
text="Surveys"
/>
<ControlPanelItem
text="Notifications"
/>
<ControlPanelItem
text="Profile"
/>
<ControlPanelItem
text="Account"
/>
<ControlPanelItem
onPress={()=>{
// mailto links do not work in the ios simulator.
// https://github.com/facebook/react-native/issues/916
// TODO: Set up support mailing list
Linking.openURL("mailto:[email protected]?subject=Support")
.catch(err => console.error('An error occurred', err))
this.props.closeDrawer()
}}
text="Support"
/>
<View style={Styles.controlPanel.item}>
<Text>Version: {Settings.version || "None"}</Text>
</View>
</View>
)
}
})
|
Fix error in expected TOC output | /***************************************************************************
* *
* EXAMPLE1 *
* *
* CONTENTS LINE *
* object ........................................................... 17 *
* Core Properties .................................................. 22 *
* Special Properties ............................................... 28 *
* *
/***************************************************************************/
/***************************************************************************
* BEGIN MODULE *
****************************************************************************/
var object = {
/* Core Properties
/*************************************************************************/
foo: 'bar',
bar: 'baz',
/* Special Properties
/*************************************************************************/
baz: 'qux'
}; | /***************************************************************************
* *
* EXAMPLE1 *
* * *
* CONTENTS LINE *
* object ........................................................... 17 *
* Core Properties .................................................. 22 *
* Special Properties ............................................... 28 *
* *
/***************************************************************************/
/***************************************************************************
* BEGIN MODULE *
****************************************************************************/
var object = {
/* Core Properties
/*************************************************************************/
foo: 'bar',
bar: 'baz',
/* Special Properties
/*************************************************************************/
baz: 'qux'
}; |
Fix propTypes of MyLocalities component | import React from "react-native";
import RoomItem from "./room-item";
import PageEmpty from "./page-empty";
import PageLoading from "./page-loading";
import PageRetry from "./page-retry";
const {
ListView,
View
} = React;
export default class MyLocalities extends React.Component {
constructor(props) {
super(props);
this.dataSource = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
}
_getDataSource() {
return this.dataSource.cloneWithRows(this.props.data);
}
render() {
return (
<View {...this.props}>
{(() => {
if (this.props.data.length === 0) {
return <PageEmpty />;
}
if (this.props.data.length === 1) {
if (this.props.data[0] === "LOADING") {
return <PageLoading />;
}
if (this.props.data[0] === "FAILED") {
return <PageRetry onRetry={this.props.refreshData} />;
}
}
return (
<ListView
dataSource={this._getDataSource()}
renderRow={room =>
<RoomItem
key={room.id}
room={room}
navigator={this.props.navigator}
/>
}
/>
);
})()}
</View>
);
}
}
MyLocalities.propTypes = {
data: React.PropTypes.array.isRequired,
refreshData: React.PropTypes.func,
navigator: React.PropTypes.object.isRequired
};
| import React from "react-native";
import RoomItem from "./room-item";
import PageEmpty from "./page-empty";
import PageLoading from "./page-loading";
import PageRetry from "./page-retry";
const {
ListView,
View
} = React;
export default class MyLocalities extends React.Component {
constructor(props) {
super(props);
this.dataSource = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
}
_getDataSource() {
return this.dataSource.cloneWithRows(this.props.data);
}
render() {
return (
<View {...this.props}>
{(() => {
if (this.props.data.length === 0) {
return <PageEmpty />;
}
if (this.props.data.length === 1) {
if (this.props.data[0] === "LOADING") {
return <PageLoading />;
}
if (this.props.data[0] === "FAILED") {
return <PageRetry onRetry={this.props.refreshData} />;
}
}
return (
<ListView
dataSource={this._getDataSource()}
renderRow={room =>
<RoomItem
key={room.id}
room={room}
navigator={this.props.navigator}
/>
}
/>
);
})()}
</View>
);
}
}
MyLocalities.propTypes = {
data: React.PropTypes.arrayOf(React.PropTypes.shape({
id: React.PropTypes.string.isRequired
})).isRequired,
refreshData: React.PropTypes.func,
navigator: React.PropTypes.object.isRequired
};
|
Use keyword arguments to avoid accidentally setting timeout | import unittest
import bz2
import bmemcached
class MemcachedTests(unittest.TestCase):
def setUp(self):
self.server = '127.0.0.1:11211'
self.client = bmemcached.Client(self.server, 'user', 'password')
self.bzclient = bmemcached.Client(self.server, 'user', 'password',
compression=bz2)
self.data = b'this is test data. ' * 32
def tearDown(self):
self.client.delete(b'test_key')
self.client.delete(b'test_key2')
self.client.disconnect_all()
self.bzclient.disconnect_all()
def testCompressedData(self):
self.client.set(b'test_key', self.data)
self.assertEqual(self.data, self.client.get(b'test_key'))
def testBZ2CompressedData(self):
self.bzclient.set(b'test_key', self.data)
self.assertEqual(self.data, self.bzclient.get(b'test_key'))
def testCompressionMissmatch(self):
self.client.set(b'test_key', self.data)
self.bzclient.set(b'test_key2', self.data)
self.assertEqual(self.client.get(b'test_key'),
self.bzclient.get(b'test_key2'))
self.assertRaises(IOError, self.bzclient.get, b'test_key')
| import unittest
import bmemcached
import bz2
class MemcachedTests(unittest.TestCase):
def setUp(self):
self.server = '127.0.0.1:11211'
self.client = bmemcached.Client(self.server, 'user', 'password')
self.bzclient = bmemcached.Client(self.server, 'user', 'password', bz2)
self.data = b'this is test data. ' * 32
def tearDown(self):
self.client.delete(b'test_key')
self.client.delete(b'test_key2')
self.client.disconnect_all()
self.bzclient.disconnect_all()
def testCompressedData(self):
self.client.set(b'test_key', self.data)
self.assertEqual(self.data, self.client.get(b'test_key'))
def testBZ2CompressedData(self):
self.bzclient.set(b'test_key', self.data)
self.assertEqual(self.data, self.bzclient.get(b'test_key'))
def testCompressionMissmatch(self):
self.client.set(b'test_key', self.data)
self.bzclient.set(b'test_key2', self.data)
self.assertEqual(self.client.get(b'test_key'),
self.bzclient.get(b'test_key2'))
self.assertRaises(IOError, self.bzclient.get, b'test_key')
|
Handle if the listeners value is already an array. | import { RENDERER_SUFFIX } from './constants';
import contentRendererMixin from './mixin';
export default {
mixins: [contentRendererMixin],
methods: {
/**
* @public
*/
checkAnswer() {
if (this.$refs.contentView && this.$refs.contentView.checkAnswer) {
return this.$refs.contentView.checkAnswer();
/* eslint-disable no-console */
} else if (!this.$refs.contentView) {
console.warn('No content view to check answer of');
} else if (!this.$refs.contentView.checkAnswer) {
console.warn('This content renderer has not implemented the checkAnswer method');
/* eslint-enable */
}
this.registerContentActivity();
return null;
},
},
render: function(createElement) {
if (this.canRenderContent(this.defaultItemPreset)) {
const listeners = {
...this.$listeners,
};
contentRendererMixin.interactionEvents.forEach(event => {
if (listeners[event]) {
if (Array.isArray(listeners[event])) {
listeners[event] = [...listeners[event], this.registerContentActivity];
} else {
listeners[event] = [listeners[event], this.registerContentActivity];
}
} else {
listeners[event] = this.registerContentActivity;
}
});
return createElement(this.defaultItemPreset + RENDERER_SUFFIX, {
props: this.$props,
attrs: this.$attrs,
on: listeners,
ref: 'contentView',
});
}
return createElement('ContentRendererError');
},
};
| import { RENDERER_SUFFIX } from './constants';
import contentRendererMixin from './mixin';
export default {
mixins: [contentRendererMixin],
methods: {
/**
* @public
*/
checkAnswer() {
if (this.$refs.contentView && this.$refs.contentView.checkAnswer) {
return this.$refs.contentView.checkAnswer();
/* eslint-disable no-console */
} else if (!this.$refs.contentView) {
console.warn('No content view to check answer of');
} else if (!this.$refs.contentView.checkAnswer) {
console.warn('This content renderer has not implemented the checkAnswer method');
/* eslint-enable */
}
this.registerContentActivity();
return null;
},
},
render: function(createElement) {
if (this.canRenderContent(this.defaultItemPreset)) {
const listeners = {
...this.$listeners,
};
contentRendererMixin.interactionEvents.forEach(event => {
if (listeners[event]) {
listeners[event] = [listeners[event], this.registerContentActivity];
} else {
listeners[event] = this.registerContentActivity;
}
});
return createElement(this.defaultItemPreset + RENDERER_SUFFIX, {
props: this.$props,
attrs: this.$attrs,
on: listeners,
ref: 'contentView',
});
}
return createElement('ContentRendererError');
},
};
|
Adjust the style to truncate post index. | $(function() {
function traverse($node, len, maxCount) {
var reachMaxCount = len > maxCount;
if (reachMaxCount) {
$node.hide();
}
var $contents = $node.contents();
for (var i = 0; i < $contents.length; ++i) {
if (reachMaxCount) {
$contents.eq(i).hide();
continue;
}
if ($contents[i].nodeType == 3) { // TextNode
var tmp = len;
var s = $contents[i].nodeValue;
len += s.length;
reachMaxCount = len > maxCount;
if (reachMaxCount) {
$contents[i].nodeValue = s.substring(0, maxCount - tmp);
}
}
else if ($contents[i].nodeType == 1) { // Element
len = traverse($contents.eq(i), len, maxCount);
}
}
return len;
}
$('.article-item').find("p").each(function() {
traverse($(this), 0, 365);
$(this).append('...');
});
});
| $(function() {
function traverse($node, len, maxCount) {
var reachMaxCount = len > maxCount;
if (reachMaxCount) {
$node.hide();
}
var $contents = $node.contents();
for (var i = 0; i < $contents.length; ++i) {
if (reachMaxCount) {
$contents.eq(i).hide();
continue;
}
if ($contents[i].nodeType == 3) { // TextNode
var tmp = len;
var s = $contents[i].nodeValue;
len += s.length;
reachMaxCount = len > maxCount;
if (reachMaxCount) {
$contents[i].nodeValue = s.substring(0, maxCount - tmp);
}
}
else if ($contents[i].nodeType == 1) { // Element
len = traverse($contents.eq(i), len, maxCount);
}
}
return len;
}
$('.post-excerpt').each(function() {
traverse($(this), 0, 200);
$(this).after('...');
});
});
|
FIX: Use the correct Event loop. | import epics
import asyncio
class PVSuspender:
"""
A class to manage the callback interface between asyincio and
pyepics.
This will probably be a base class eventually.
"""
def __init__(self, RE, pv_name, loop=None):
if loop is None:
loop = asyncio.get_event_loop()
self._loop = loop
self.RE = RE
self._ev = None
self._pv = epics.PV(pv_name, auto_monitor=True)
self._pv.add_callback(self)
def _should_suspend(self, value):
"""
Determine if the current value of the PV is such
that we need to tell the scan to suspend
"""
return bool(value)
def _should_resume(self, value):
"""
Determine if the scan is ready to automatically
restart.
"""
return not bool(value)
def __call__(self, **kwargs):
"""
Make the class callable so that we can
pass it off to the pyepics callback stack.
"""
value = kwargs['value']
if self._ev is None or self._ev.is_set():
# in the case where either have never been
# called or have already fully cycled once
if self._should_suspend(value):
self._ev = asyncio.Event(loop=self._loop)
self._loop.call_soon_threadsafe(
self.RE.request_suspend,
self._ev.wait())
else:
if self._should_resume(value):
self._loop.call_soon_threadsafe(self._ev.set)
| import epics
import asyncio
class PVSuspender:
"""
A class to manage the callback interface between asyincio and
pyepics.
This will probably be a base class eventually.
"""
def __init__(self, RE, pv_name, loop=None):
if loop is None:
loop = asyncio.get_event_loop()
self._loop = loop
self.RE = RE
self._ev = None
self._pv = epics.PV(pv_name, auto_monitor=True)
self._pv.add_callback(self)
def _should_suspend(self, value):
"""
Determine if the current value of the PV is such
that we need to tell the scan to suspend
"""
return bool(value)
def _should_resume(self, value):
"""
Determine if the scan is ready to automatically
restart.
"""
return not bool(value)
def __call__(self, **kwargs):
"""
Make the class callable so that we can
pass it off to the pyepics callback stack.
"""
value = kwargs['value']
if self._ev is None or self._ev.is_set():
# in the case where either have never been
# called or have already fully cycled once
if self._should_suspend(value):
self._ev = asyncio.Event()
self._loop.call_soon_threadsafe(
self.RE.request_suspend,
self._ev.wait())
else:
if self._should_resume(value):
self._loop.call_soon_threadsafe(self._ev.set)
|
Remove pymvpa from documentation build.
git-svn-id: 24f545668198cdd163a527378499f2123e59bf9f@931 ead46cd0-7350-4e37-8683-fc4c6f79bf00 | #!/usr/bin/env python
"""Script to auto-generate our API docs.
"""
# stdlib imports
import os
import sys
# local imports
from interfacedocgen import InterfaceHelpWriter
#*****************************************************************************
if __name__ == '__main__':
nipypepath = os.path.abspath('..')
sys.path.insert(1,nipypepath)
package = 'nipype'
outdir = os.path.join('interfaces','generated')
docwriter = InterfaceHelpWriter(package)
# Packages that should not be included in generated API docs.
docwriter.package_skip_patterns += ['\.externals$',
'\.utils$',
'\.pipeline',
'.\testing',
'\.interfaces\.gorlin_glue',
]
# Modules that should not be included in generated API docs.
docwriter.module_skip_patterns += ['\.version$',
'\.interfaces\.afni$',
'\.interfaces\.base$',
'\.interfaces\.matlab$',
'\.interfaces\.rest$',
'\.interfaces\.pymvpa$',
'\.pipeline\.alloy$',
'\.pipeline\.s3_node_wrapper$',
]
docwriter.class_skip_patterns += ['FSL',
'spm.\SpecifyModel',
'SpmInfo',
'FSCommandLine',
'SpmMatlab'
]
docwriter.write_api_docs(outdir)
docwriter.write_index(outdir, 'gen', relative_to='interfaces')
print '%d files written' % len(docwriter.written_modules)
| #!/usr/bin/env python
"""Script to auto-generate our API docs.
"""
# stdlib imports
import os
import sys
# local imports
from interfacedocgen import InterfaceHelpWriter
#*****************************************************************************
if __name__ == '__main__':
nipypepath = os.path.abspath('..')
sys.path.insert(1,nipypepath)
package = 'nipype'
outdir = os.path.join('interfaces','generated')
docwriter = InterfaceHelpWriter(package)
# Packages that should not be included in generated API docs.
docwriter.package_skip_patterns += ['\.externals$',
'\.utils$',
'\.pipeline',
'.\testing',
'\.interfaces\.gorlin_glue',
]
# Modules that should not be included in generated API docs.
docwriter.module_skip_patterns += ['\.version$',
'\.interfaces\.afni$',
'\.interfaces\.base$',
'\.interfaces\.matlab$',
'\.interfaces\.rest$',
'\.pipeline\.alloy$',
'\.pipeline\.s3_node_wrapper$',
]
docwriter.class_skip_patterns += ['FSL',
'spm.\SpecifyModel',
'SpmInfo',
'FSCommandLine',
'SpmMatlab'
]
docwriter.write_api_docs(outdir)
docwriter.write_index(outdir, 'gen', relative_to='interfaces')
print '%d files written' % len(docwriter.written_modules)
|
Move date format to setter
* Change date format options to be set from a setter instead of in the
constructor for ResponseParser | package com.fanpics.opensource.android.modelrecord;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.lang.reflect.Type;
import retrofit.client.Response;
import retrofit.converter.ConversionException;
import retrofit.converter.GsonConverter;
public class ResponseParser<T> {
private final Response response;
private final Type type;
private String dateFormat;
public ResponseParser(Response response, Type type) {
this.response = response;
this.type = type;
}
public void setDateFormat(String dateFormat) {
this.dateFormat = dateFormat;
}
public Result<T> parse() {
try {
final T object = parseFromResponse();
return new Result<T>(response, object);
} catch (ConversionException e) {
throw new RuntimeException("Response body must match type passed in at constructor", e);
}
}
private T parseFromResponse() throws ConversionException {
final Gson gson = getGson();
final GsonConverter converter = new GsonConverter(gson);
return (T) converter.fromBody(response.getBody(), type);
}
public Gson getGson() {
Gson gson;
if (dateFormat != null) {
gson = new GsonBuilder().setDateFormat(dateFormat).create();
} else {
gson = new GsonBuilder().create();
}
return gson;
}
}
| package com.fanpics.opensource.android.modelrecord;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.lang.reflect.Type;
import retrofit.client.Response;
import retrofit.converter.ConversionException;
import retrofit.converter.GsonConverter;
public class ResponseParser<T> {
private final Response response;
private final Type type;
private String dateFormat;
public ResponseParser(Response response, Type type) {
this.response = response;
this.type = type;
}
public ResponseParser(Response response, Type type, String dateFormat) {
this.response = response;
this.type = type;
this.dateFormat = dateFormat;
}
public Result<T> parse() {
try {
final T object = parseFromResponse();
return new Result<T>(response, object);
} catch (ConversionException e) {
throw new RuntimeException("Response body must match type passed in at constructor", e);
}
}
private T parseFromResponse() throws ConversionException {
final Gson gson = getGson();
final GsonConverter converter = new GsonConverter(gson);
return (T) converter.fromBody(response.getBody(), type);
}
public Gson getGson() {
Gson gson;
if (dateFormat != null) {
gson = new GsonBuilder().setDateFormat(dateFormat).create();
} else {
gson = new GsonBuilder().create();
}
return gson;
}
}
|
Fix jboss-all generation. Name should be attribute | package org.bedework.util.deployment;
import org.w3c.dom.Element;
import java.io.File;
import java.util.List;
/** Represent a jboss-web.xml file.
*
* @author douglm
*/
public class JbossAllXml extends XmlFile {
private final PropertiesChain props;
private final String version;
public JbossAllXml(final Utils utils,
final File metaInf,
final String version,
final PropertiesChain props) throws Throwable {
super(utils, metaInf, "jboss-all.xml", false);
this.version = version;
this.props = props;
}
public void update() throws Throwable {
utils.debug("Update " + theXml.getAbsolutePath());
final List<String> earDependencies =
props.listProperty("app.ear.dependencies");
if (earDependencies != null) {
for (final String ed: earDependencies) {
addDependency(ed);
}
}
}
public void addDependency(final String dep) throws Throwable {
final Element el = findElement(root, "jboss-deployment-dependencies");
if (el == null) {
utils.error("Cannot locate jboss-deployment-dependencies");
return;
}
final Element depNode = doc.createElement("dependency");
depNode.setAttribute("name", dep + "-" + version + ".ear");
el.appendChild(depNode);
updated = true;
}
}
| package org.bedework.util.deployment;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import java.io.File;
import java.util.List;
/** Represent a jboss-web.xml file.
*
* @author douglm
*/
public class JbossAllXml extends XmlFile {
private final PropertiesChain props;
private final String version;
public JbossAllXml(final Utils utils,
final File metaInf,
final String version,
final PropertiesChain props) throws Throwable {
super(utils, metaInf, "jboss-all.xml", false);
this.version = version;
this.props = props;
}
public void update() throws Throwable {
utils.debug("Update " + theXml.getAbsolutePath());
final List<String> earDependencies =
props.listProperty("app.ear.dependencies");
if (earDependencies != null) {
for (final String ed: earDependencies) {
addDependency(ed);
}
}
}
public void addDependency(final String dep) throws Throwable {
final Element el = findElement(root, "jboss-deployment-dependencies");
if (el == null) {
utils.error("Cannot locate jboss-deployment-dependencies");
return;
}
final Node depNode = doc.createElement("dependency");
final Node textNode = doc.createTextNode(dep + "-" + version + ".ear");
depNode.appendChild(textNode);
el.appendChild(depNode);
updated = true;
}
}
|
Remove file loader from conf | const path = require('path')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const WebpackBundleTracker = require('webpack-bundle-tracker')
module.exports = {
mode: 'development',
entry: {
base: './static/javascript/base',
pages: './static/javascript/pages',
home: './static/javascript/home',
queries: './static/javascript/queries',
},
output: {
filename: '[name]_[hash].js',
path: path.resolve(__dirname, 'staticfiles/bundles'),
publicPath: 'http://localhost:8080/static/bundles/',
},
devtool: 'eval-source-map',
devServer: {
compress: true,
hot: true,
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'],
}
},
},
{
test: /\.(sa|sc|c)ss$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
},
{
loader: 'css-loader',
},
{
loader: 'sass-loader',
options: {
implementation: require('sass'),
}
},
]
},
]
},
plugins: [
new WebpackBundleTracker({
filename: './webpack-stats.json',
}),
new MiniCssExtractPlugin({
filename: '[name]_[hash].css',
}),
],
}
| const path = require('path')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const WebpackBundleTracker = require('webpack-bundle-tracker')
module.exports = {
mode: 'development',
entry: {
base: './static/javascript/base',
pages: './static/javascript/pages',
home: './static/javascript/home',
queries: './static/javascript/queries',
},
output: {
filename: '[name]_[hash].js',
path: path.resolve(__dirname, 'staticfiles/bundles'),
publicPath: 'http://localhost:8080/static/bundles/',
},
devtool: 'eval-source-map',
devServer: {
compress: true,
hot: true,
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'],
}
},
},
{
test: /\.(sa|sc|c)ss$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
},
{
loader: 'css-loader',
},
{
loader: 'sass-loader',
options: {
implementation: require('sass'),
}
},
]
},
{
test: /\.(png|jpe?g|gif|svg)$/,
use: [
{
loader: 'file-loader',
},
]
},
]
},
plugins: [
new WebpackBundleTracker({
filename: './webpack-stats.json',
}),
new MiniCssExtractPlugin({
filename: '[name]_[hash].css',
}),
],
}
|
Fix AR list module test | define((require) => {
describe('requester_module', () => {
beforeEach(() => {
require('app/views/teacher/modules/assistance_request_list_module');
});
describe('>RetrieveAssistanceRequests', () => {
it('should be defined', () => {
expect(RetrieveAssistanceRequests).toBeDefined();
});
[[], ['a'], ['a', 'b', 'random_course_id_42']].forEach(selectedCourseList => {
it(`should request assistance requests for selected courses (${selectedCourseList})`, () => {
const mock_socket = {
emit: () => undefined
};
socket = mock_socket;
const spy_emit = spyOn(mock_socket, 'emit').and.callThrough();
const spy_getSelectedClassIds = jasmine.createSpy('getSelectedClassIds').and.returnValue(selectedCourseList);
getSelectedClassIds = spy_getSelectedClassIds;
expect(RetrieveAssistanceRequests()).toBeUndefined();
expect(spy_emit.calls.count()).toEqual(1);
expect(spy_emit.calls.argsFor(0)).toEqual(['Request_RetrieveAssistanceRequests', {cids: selectedCourseList, qty: 5}]);
expect(spy_getSelectedClassIds.calls.count()).toEqual(1);
expect(spy_getSelectedClassIds.calls.argsFor(0)).toEqual([]);
});
});
});
});
}); | define((require) => {
describe('requester_module', () => {
beforeEach(() => {
require('app/views/teacher/modules/assistance_request_list_module');
});
define('>RetrieveAssistanceRequests', () => {
it('should be defined', () => {
expect(RetrieveAssistanceRequests).toBeDefined();
});
[[], ['a'], ['a', 'b', 'random_course_id_42']].forEach(selectedCourseList => {
it(`should request assistance requests for selected courses (${selectedCourseList})`, () => {
const mock_socket = {
emit: () => undefined
};
const spy_emit = spyOn(mock_socket, 'emit').and.callThrough();
const spy_getSelectedClassIds = jasmine.createSpy('getSelectedClassIds').and.returnValue(selectedCourseList);
selectedClassIds = spy_getSelectedClassIds;
expect(RetrieveAssistanceRequests()).toBeUndefined();
expect(spy_emit.calls.count()).toEqual(1);
expect(spy_emit.calls.argsFor(0)).toEqual([{cids: selectedCourseList, qty: 5}]);
expect(spy_getSelectedClassIds.calls.count()).toEqual(1);
expect(spy_emit.calls.argsFor(0)).toEqual([]);
});
});
});
});
}); |
Make error message a bit more neutral | package io.quarkus.hibernate.search.orm.elasticsearch.runtime.devconsole;
import java.time.Duration;
import java.util.stream.Collectors;
import org.hibernate.search.mapper.orm.entity.SearchIndexedEntity;
import org.hibernate.search.mapper.orm.mapping.SearchMapping;
import io.quarkus.devconsole.runtime.spi.DevConsolePostHandler;
import io.quarkus.devconsole.runtime.spi.FlashScopeUtil;
import io.quarkus.runtime.annotations.Recorder;
import io.vertx.core.Handler;
import io.vertx.core.MultiMap;
import io.vertx.ext.web.RoutingContext;
@Recorder
public class HibernateSearchDevConsoleRecorder {
public Handler<RoutingContext> indexEntity() {
return new DevConsolePostHandler() {
@Override
protected void handlePostAsync(RoutingContext event, MultiMap form) throws Exception {
if (form.isEmpty()) {
return;
}
SearchMapping mapping = HibernateSearchSupplier.searchMapping();
if (mapping == null) {
flashMessage(event, "There are no indexed entity types.", FlashScopeUtil.FlashMessageStatus.ERROR);
return;
}
mapping.scope(Object.class,
mapping.allIndexedEntities().stream()
.map(SearchIndexedEntity::jpaName)
.filter(form::contains)
.collect(Collectors.toList()))
.massIndexer()
.startAndWait();
flashMessage(event, "Entities successfully reindexed", Duration.ofSeconds(10));
}
};
}
}
| package io.quarkus.hibernate.search.orm.elasticsearch.runtime.devconsole;
import java.time.Duration;
import java.util.stream.Collectors;
import org.hibernate.search.mapper.orm.entity.SearchIndexedEntity;
import org.hibernate.search.mapper.orm.mapping.SearchMapping;
import io.quarkus.devconsole.runtime.spi.DevConsolePostHandler;
import io.quarkus.devconsole.runtime.spi.FlashScopeUtil;
import io.quarkus.runtime.annotations.Recorder;
import io.vertx.core.Handler;
import io.vertx.core.MultiMap;
import io.vertx.ext.web.RoutingContext;
@Recorder
public class HibernateSearchDevConsoleRecorder {
public Handler<RoutingContext> indexEntity() {
return new DevConsolePostHandler() {
@Override
protected void handlePostAsync(RoutingContext event, MultiMap form) throws Exception {
if (form.isEmpty()) {
return;
}
SearchMapping mapping = HibernateSearchSupplier.searchMapping();
if (mapping == null) {
flashMessage(event, "There aren't any indexed entity types!", FlashScopeUtil.FlashMessageStatus.ERROR);
return;
}
mapping.scope(Object.class,
mapping.allIndexedEntities().stream()
.map(SearchIndexedEntity::jpaName)
.filter(form::contains)
.collect(Collectors.toList()))
.massIndexer()
.startAndWait();
flashMessage(event, "Entities successfully reindexed", Duration.ofSeconds(10));
}
};
}
}
|
Set up test directory for js testing | /*
* grunt-perl-tidy
* https://github.com/rabrooks/grunt-perl-tidy
*
* Copyright (c) 2014 Aaron Brooks
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntjs.com/creating-tasks
grunt.registerMultiTask('perl_tidy', 'Run perl tidy on perl files.', function() {
// Merge task-specific and/or target-specific options with these defaults.
var options = this.options({
punctuation: '.',
separator: ', '
});
// Iterate over all specified file groups.
this.files.forEach(function(f) {
// Concat specified files.
var src = f.src.filter(function(filepath) {
// Warn on and remove invalid source files (if nonull was set).
if (!grunt.file.exists(filepath)) {
grunt.log.warn('Source file "' + filepath + '" not found.');
return false;
} else {
// Use this to preform logic on each file that is in the group
conosle.log (filepath);
return true;
}
}).map(function(filepath) {
// Read file source.
return grunt.file.read(filepath);
}).join(grunt.util.normalizelf(options.separator));
// Handle options.
src += options.punctuation;
// Write the destination file.
grunt.file.write(f.dest, src);
// Print a success message.
grunt.log.writeln('File "' + f.dest + '" is now all tidy.');
});
});
};
| /*
* grunt-perl-tidy
* https://github.com/rabrooks/grunt-perl-tidy
*
* Copyright (c) 2014 Aaron Brooks
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntjs.com/creating-tasks
grunt.registerMultiTask('perl_tidy', 'Run perl tidy on perl files.', function() {
// Merge task-specific and/or target-specific options with these defaults.
var options = this.options({
punctuation: '.',
separator: ', '
});
// Iterate over all specified file groups.
this.files.forEach(function(f) {
// Concat specified files.
var src = f.src.filter(function(filepath) {
// Warn on and remove invalid source files (if nonull was set).
if (!grunt.file.exists(filepath)) {
grunt.log.warn('Source file "' + filepath + '" not found.');
return false;
} else {
return true;
}
}).map(function(filepath) {
// Read file source.
return grunt.file.read(filepath);
}).join(grunt.util.normalizelf(options.separator));
// Handle options.
src += options.punctuation;
// Write the destination file.
grunt.file.write(f.dest, src);
// Print a success message.
grunt.log.writeln('File "' + f.dest + '" is now all tidy.');
});
});
};
|
MRWidget: Make error message bold and red. | import eventHub from '../../event_hub';
export default {
name: 'MRWidgetAutoMergeFailed',
props: {
mr: { type: Object, required: true },
},
data() {
return {
isRefreshing: false,
};
},
methods: {
refreshWidget() {
this.isRefreshing = true;
eventHub.$emit('MRWidgetUpdateRequested', () => {
this.isRefreshing = false;
});
},
},
template: `
<div class="mr-widget-body">
<button
class="btn btn-success btn-small"
disabled="true"
type="button">
Merge
</button>
<span class="bold danger">
This merge request failed to be merged automatically.
<button
@click="refreshWidget"
:class="{ disabled: isRefreshing }"
type="button"
class="btn btn-xs btn-default">
<i
v-if="isRefreshing"
class="fa fa-spinner fa-spin"
aria-hidden="true" />
Refresh
</button>
</span>
<div class="merge-error-text danger bold">
{{mr.mergeError}}
</div>
</div>
`,
};
| import eventHub from '../../event_hub';
export default {
name: 'MRWidgetAutoMergeFailed',
props: {
mr: { type: Object, required: true },
},
data() {
return {
isRefreshing: false,
};
},
methods: {
refreshWidget() {
this.isRefreshing = true;
eventHub.$emit('MRWidgetUpdateRequested', () => {
this.isRefreshing = false;
});
},
},
template: `
<div class="mr-widget-body">
<button
class="btn btn-success btn-small"
disabled="true"
type="button">
Merge
</button>
<span class="bold danger">
This merge request failed to be merged automatically.
<button
@click="refreshWidget"
:class="{ disabled: isRefreshing }"
type="button"
class="btn btn-xs btn-default">
<i
v-if="isRefreshing"
class="fa fa-spinner fa-spin"
aria-hidden="true" />
Refresh
</button>
</span>
<div class="merge-error-text">
{{mr.mergeError}}
</div>
</div>
`,
};
|
Use Conan Center provided libcurl. | from conans import ConanFile, CMake, tools
class LibWFUTConan(ConanFile):
name = "libwfut"
version = "0.2.4"
license = "GPL-2.0+"
author = "Erik Ogenvik <[email protected]>"
homepage = "https://www.worldforge.org"
url = "https://github.com/worldforge/libwfut"
description = "A client side C++ implementation of WFUT (WorldForge Update Tool)."
topics = ("mmorpg", "worldforge")
settings = "os", "compiler", "build_type", "arch"
options = {"shared": [False, True], "fPIC": [True, False]}
default_options = {"shared": False, "fPIC": True}
generators = "cmake"
requires = ["sigc++/2.10.0@worldforge/stable",
"zlib/1.2.11",
"libcurl/7.75.0"]
scm = {
"type": "git",
"url": "https://github.com/worldforge/libwfut.git",
"revision": "auto"
}
def build(self):
cmake = CMake(self)
cmake.configure(source_folder=".")
cmake.build()
cmake.install()
def package_info(self):
self.cpp_info.libs = tools.collect_libs(self)
self.cpp_info.includedirs = ["include/wfut-0.2"]
def package(self):
pass
| from conans import ConanFile, CMake, tools
class LibWFUTConan(ConanFile):
name = "libwfut"
version = "0.2.4"
license = "GPL-2.0+"
author = "Erik Ogenvik <[email protected]>"
homepage = "https://www.worldforge.org"
url = "https://github.com/worldforge/libwfut"
description = "A client side C++ implementation of WFUT (WorldForge Update Tool)."
topics = ("mmorpg", "worldforge")
settings = "os", "compiler", "build_type", "arch"
options = {"shared": [False, True], "fPIC": [True, False]}
default_options = {"shared": False, "fPIC": True}
generators = "cmake"
requires = ["sigc++/2.10.0@worldforge/stable",
"zlib/1.2.11",
"libcurl/7.66.0@worldforge/stable"]
scm = {
"type": "git",
"url": "https://github.com/worldforge/libwfut.git",
"revision": "auto"
}
def build(self):
cmake = CMake(self)
cmake.configure(source_folder=".")
cmake.build()
cmake.install()
def package_info(self):
self.cpp_info.libs = tools.collect_libs(self)
self.cpp_info.includedirs = ["include/wfut-0.2"]
def package(self):
pass
|
Test getenv au lieu d'une référence vers un paramètres | <?php
// app/config/security.php
$container->loadFromExtension('security', [
'encoders' => [
'Tm\UserBundle\Entity\Utilisateur' => 'sha512',
],
'role_hierarchy' => [
'ROLE_ADMIN' => 'ROLE_UTILISATEUR',
'ROLE_SUPER_ADMIN' => ['ROLE_ADMIN', 'ROLE_ALLOWED_TO_SWITCH'],
],
'providers' => [
'main' => [
'id' => 'fos_user.user_provider.username',
],
],
'firewalls' => [
'dev' => [
'pattern' => '^/(_(profiler|wdt)|css|images|js)/',
'security' => false,
],
'main' => [
'pattern' => '^/',
'anonymous' => true,
'provider' => 'main',
'form_login' => [
'login_path' => 'fos_user_security_login',
'check_path' => 'fos_user_security_check',
],
'logout' => [
'path' => 'fos_user_security_logout',
'target' => '/',
],
'remember_me' => [
'key' => getenv('SECRET_KEY'),
],
],
],
'access_control' => [// array('path' => '^/admin', 'role' => 'ROLE_ADMIN'),
]
]
); | <?php
// app/config/security.php
$container->loadFromExtension('security', [
'encoders' => [
'Tm\UserBundle\Entity\Utilisateur' => 'sha512',
],
'role_hierarchy' => [
'ROLE_ADMIN' => 'ROLE_UTILISATEUR',
'ROLE_SUPER_ADMIN' => ['ROLE_ADMIN', 'ROLE_ALLOWED_TO_SWITCH'],
],
'providers' => [
'main' => [
'id' => 'fos_user.user_provider.username',
],
],
'firewalls' => [
'dev' => [
'pattern' => '^/(_(profiler|wdt)|css|images|js)/',
'security' => false,
],
'main' => [
'pattern' => '^/',
'anonymous' => true,
'provider' => 'main',
'form_login' => [
'login_path' => 'fos_user_security_login',
'check_path' => 'fos_user_security_check',
],
'logout' => [
'path' => 'fos_user_security_logout',
'target' => '/',
],
'remember_me' => [
'key' => '%secret%',
],
],
],
'access_control' => [// array('path' => '^/admin', 'role' => 'ROLE_ADMIN'),
]
]
); |
Add more photoshopper tool functions
New function to resize to height
Get dimensions now supported | <?php
/**
* @license MIT
* Full license text in LICENSE file
*/
namespace VLibrary\Core\Tool;
interface Photoshopper
{
/**
* Sets the source image to manipulate, and the destination to save the result
*
* Example:
* $photoshopper->setup('/tmp/myfile.png', '/home/user/profile.png');
*
* @param string $source The path to the source image file
* @param string $destination The path of the destination image file. If
* blank, the source file will be overwritten.
*
* @return void
*/
public function setup($source, $destination = NULL);
/**
* Returns image dimensions
*
* @return array($width, $height) in pixels
*/
public function get_dimensions();
/**
* Resizes an image to a width in pixels, maintaining aspect ratio
*
* Example:
* $photoshopper->resize_to_width(40);
*
* @param int $width Width in pixels to resize to
*
* @return void
*/
public function resize_to_width($width);
/**
* Resizes an image to a height in pixels, maintaining aspect ratio
*
* Example:
* $photoshopper->resize_to_height(40);
*
* @param int $height height in pixels to resize to
*
* @return void
*/
public function resize_to_height($height);
/**
* Blurs the image using the Gaussian algorithm
*
* Example:
* $photoshopper->gaussian_blur(2.5);
*
* @param float $sigma The sigma magnitude of the Gaussian blur
*
* @return void
*/
public function gaussian_blur($sigma);
}
| <?php
/**
* @license MIT
* Full license text in LICENSE file
*/
namespace VLibrary\Core\Tool;
interface Photoshopper
{
/**
* Sets the source image to manipulate, and the destination to save the result
*
* Example:
* $photoshopper->setup('/tmp/myfile.png', '/home/user/profile.png');
*
* @param string $source The path to the source image file
* @param string $destination The path of the destination image file. If
* blank, the source file will be overwritten.
*
* @return void
*/
public function setup($source, $destination = NULL);
/**
* Returns image width in pixels
*
* @return int
*/
public function get_width();
/**
* Resizes an image to a width in pixels, maintaining aspect ratio
*
* Example:
* $photoshopper->resize_to_width(40);
*
* @param int $width Width in pixels to resize to
*
* @return void
*/
public function resize_to_width($width);
/**
* Blurs the image using the Gaussian algorithm
*
* Example:
* $photoshopper->gaussian_blur(2.5);
*
* @param float $sigma The sigma magnitude of the Gaussian blur
*
* @return void
*/
public function gaussian_blur($sigma);
}
|
Fix code style according to PSR standard. | <?php
/**
* @author Jean Silva <[email protected]>
* @license MIT
*/
namespace Jeancsil\FlightSpy\Service\Currency;
class PriceFormatter
{
const CURRENCIES_FILE = 'currencies.json';
private $currencies;
public function __construct($resourcesDir)
{
$this->initializeCurrenciesFile($resourcesDir);
}
/**
* @param string $price
* @param string $currencyCode
* @return string
*/
public function format($price, $currencyCode)
{
foreach ($this->currencies as $currency) {
if ($currency['Code'] == $currencyCode) {
if ($currency['SymbolOnLeft'] == 'true') {
return $currency['Symbol'] .
number_format(
$price,
2,
$currency['DecimalSeparator'],
$currency['ThousandsSeparator']
);
}
return number_format(
$price,
2,
$currency['DecimalSeparator'],
$currency['ThousandsSeparator']
) . $currency['Symbol'];
}
}
}
/**
* @param $resourcesDir
*/
private function initializeCurrenciesFile($resourcesDir)
{
if (!$this->currencies) {
$currenciesFile = getcwd() . '/' . $resourcesDir . '/' . static::CURRENCIES_FILE;
$currenciesArray = json_decode(file_get_contents($currenciesFile), true);
$this->currencies = $currenciesArray['ReferenceServiceResponseDto']['Currencies']['CurrencyDto'];
}
}
}
| <?php
/**
* @author Jean Silva <[email protected]>
* @license MIT
*/
namespace Jeancsil\FlightSpy\Service\Currency;
class PriceFormatter
{
const CURRENCIES_FILE = 'currencies.json';
private $currencies;
public function __construct($resourcesDir)
{
$this->initializeCurrenciesFile($resourcesDir);
}
/**
* @param string $price
* @param string $currencyCode
* @return string
*/
public function format($price, $currencyCode) {
foreach ($this->currencies as $currency) {
if ($currency['Code'] == $currencyCode) {
if ($currency['SymbolOnLeft'] == 'true') {
return $currency['Symbol'] .
number_format(
$price,
2,
$currency['DecimalSeparator'],
$currency['ThousandsSeparator']
);
}
return number_format(
$price,
2,
$currency['DecimalSeparator'],
$currency['ThousandsSeparator']
) . $currency['Symbol'];
}
}
}
/**
* @param $resourcesDir
*/
private function initializeCurrenciesFile($resourcesDir)
{
if (!$this->currencies) {
$currenciesFile = getcwd() . '/' . $resourcesDir . '/' . static::CURRENCIES_FILE;
$currenciesArray = json_decode(file_get_contents($currenciesFile), true);
$this->currencies = $currenciesArray['ReferenceServiceResponseDto']['Currencies']['CurrencyDto'];
}
}
}
|
Fix drop event with preventDefault
If preventDefault is not triggered, we can't use drop event. I fix it
and added an over function to disable it by default. | (function ($) {
$.fn.dragster = function (options) {
var settings = $.extend({
enter: $.noop,
leave: $.noop,
over: $.noop
}, options);
return this.each(function () {
var first = false,
second = false,
$this = $(this);
$this.on({
dragenter: function (event) {
if (first) {
return second = true;
} else {
first = true;
$this.trigger('dragster:enter', event);
}
event.preventDefault();
},
dragleave: function (event) {
if (second) {
second = false;
} else if (first) {
first = false;
}
if (!first && !second) {
$this.trigger('dragster:leave', event);
}
event.preventDefault();
},
dragover: function (event) {
event.preventDefault();
},
'dragster:enter': settings.enter,
'dragster:leave': settings.leave,
'dragster:over': settings.over
});
});
};
}(jQuery));
| (function ($) {
$.fn.dragster = function (options) {
var settings = $.extend({
enter: $.noop,
leave: $.noop
}, options);
return this.each(function () {
var first = false,
second = false,
$this = $(this);
$this.on({
dragenter: function () {
if (first) {
return second = true;
} else {
first = true;
$this.trigger('dragster:enter');
}
},
dragleave: function () {
if (second) {
second = false;
} else if (first) {
first = false;
}
if (!first && !second) {
$this.trigger('dragster:leave');
}
},
'dragster:enter': settings.enter,
'dragster:leave': settings.leave
});
});
};
}(jQuery));
|
Support passing an array of urls. | const fs = require('fs');
const {join} = require('path');
const {promisify} = require('util');
const readFile = promisify(fs.readFile);
const writeFile = promisify(fs.writeFile);
const mkdirp = promisify(require('mkdirp'));
const request = promisify(require('request'));
const checkCacheExpiry = require('../utils/check-cache-expiry');
const generateUUID = require('../utils/generate-uuid');
const DEFAULT_CACHE_TTL = 3600;
const MILLISECONDS = 1000;
const requestFromUrlorCache = (url, {
cacheDirectory = 'temp/cache/',
requestOptions = {},
ttl = DEFAULT_CACHE_TTL
} = {}) => {
const uuid = generateUUID(url);
const path = join(
cacheDirectory,
uuid
);
return checkCacheExpiry(
path,
ttl * MILLISECONDS
)
.then(() => readFile(
path,
'utf8'
))
.catch(() =>
request(
url,
requestOptions
).then(({body}) =>
mkdirp(cacheDirectory).then(() =>
writeFile(
path,
body
).then(() => body))));
};
const fetch = (urls, options) => {
if (Array.isArray(urls)) {
return Promise.all(urls.map(url => requestFromUrlorCache(
url,
options
)));
}
return requestFromUrlorCache(
urls,
options
);
};
module.exports = {
fetch,
requestFromUrlorCache
};
| const fs = require('fs');
const {join} = require('path');
const {promisify} = require('util');
const readFile = promisify(fs.readFile);
const writeFile = promisify(fs.writeFile);
const mkdirp = promisify(require('mkdirp'));
const request = promisify(require('request'));
const checkCacheExpiry = require('../utils/check-cache-expiry');
const generateUUID = require('../utils/generate-uuid');
const DEFAULT_CACHE_TTL = 3600;
const MILLISECONDS = 1000;
const fetch = (url, {
cacheDirectory = 'temp/cache/',
requestOptions = {},
ttl = DEFAULT_CACHE_TTL
} = {}) => {
const uuid = generateUUID(url);
const path = join(
cacheDirectory,
uuid
);
return checkCacheExpiry(
path,
ttl * MILLISECONDS
)
.then(() => readFile(
path,
'utf8'
))
.catch(() =>
request(
url,
requestOptions
).then(({body}) =>
mkdirp(cacheDirectory).then(() =>
writeFile(
path,
body
).then(() => body))));
};
module.exports = {fetch};
|
Disable menu selection in member list | import { ListItem } from 'material-ui/List';
import React from 'react';
import { Link } from 'react-router';
import Phone from './Phone';
export default class MemberItem extends React.Component {
static propTypes = {
isMember: React.PropTypes.bool,
user: React.PropTypes.object,
role: React.PropTypes.object,
}
render() {
if (this.props.user) {
const user = this.props.user;
return (
<div>
{this.props.isMember
? <ListItem
disabled
primaryText={
<div>
<Link to={`/users/${user.id}`}>{user.name}</Link>
{' '}
{this.props.role.tile || user.instrument
? <span>({this.props.role.title || user.instrument})</span>
: null
}
</div>
}
secondaryText={
<div>
<Phone phone={user.phone} />
{user.phone && user.email
? ' – '
: null
}
<a
href={`mailto:${user.email}`}
>
{user.email}
</a>
</div>
}
/>
: <ListItem
primaryText={
<div>
{user.name}
{' '}
{this.props.role.tile || user.instrument
? <span>({this.props.role.title || user.instrument})</span>
: null
}
</div>
}
/>
}
</div>
);
}
return null;
}
}
| import { ListItem } from 'material-ui/List';
import React from 'react';
import { Link } from 'react-router';
import Phone from './Phone';
export default class MemberItem extends React.Component {
static propTypes = {
isMember: React.PropTypes.bool,
user: React.PropTypes.object,
role: React.PropTypes.object,
}
render() {
if (this.props.user) {
const user = this.props.user;
return (
<div>
{this.props.isMember
? <ListItem
primaryText={
<div>
<Link to={`/users/${user.id}`}>{user.name}</Link>
{' '}
{this.props.role.tile || user.instrument
? <span>({this.props.role.title || user.instrument})</span>
: null
}
</div>
}
secondaryText={
<div>
<Phone phone={user.phone} />
{user.phone && user.email
? ' – '
: null
}
<a
href={`mailto:${user.email}`}
>
{user.email}
</a>
</div>
}
/>
: <ListItem
primaryText={
<div>
{user.name}
{' '}
{this.props.role.tile || user.instrument
? <span>({this.props.role.title || user.instrument})</span>
: null
}
</div>
}
/>
}
</div>
);
}
return null;
}
}
|
Fix hard coded "Edit" translation link
Edit link generates 404 error when using http://localhost/<your-project>/public/en/admin/translation | @extends(layoutExtend())
@section('title')
{{ trans('categorie.Translation') }} {{ trans('home.control') }}
@endsection
@section('content')
<table class="table table-bordered table-striped">
<tr>
<th>{{ trans('admin.Files') }}</th>
@foreach(LaravelLocalization::getSupportedLocales() as $localeCode => $properties)
<th>{{ $properties['native'] }}</th>
@endforeach
<th>{{ trans('admin.Both') }}</th>
</tr>
@foreach($files as $h)
<tr>
@php $path = explode(DIRECTORY_SEPARATOR , (string)$h) @endphp
<td>{{ end($path) }}</td>
@foreach(LaravelLocalization::getSupportedLocales() as $localeCode => $properties)
<td>
<a href="{{ url('admin/translation/readFile/'.$localeCode.'_'.end($path)) }}">{{ trans('admin.Edit') }} </a>
</td>
@endforeach
<td><a href="{{ url('admin/translation/getAllContent/'.end($path)) }}">{{ trans('admin.Edit All Language') }}</a></td>
</tr>
@endforeach
</table>
@endsection
| @extends(layoutExtend())
@section('title')
{{ trans('categorie.Translation') }} {{ trans('home.control') }}
@endsection
@section('content')
<table class="table table-bordered table-striped">
<tr>
<th>{{ trans('admin.Files') }}</th>
@foreach(LaravelLocalization::getSupportedLocales() as $localeCode => $properties)
<th>{{ $properties['native'] }}</th>
@endforeach
<th>{{ trans('admin.Both') }}</th>
</tr>
@foreach($files as $h)
<tr>
@php $path = explode(DIRECTORY_SEPARATOR , (string)$h) @endphp
<td>{{ end($path) }}</td>
@foreach(LaravelLocalization::getSupportedLocales() as $localeCode => $properties)
<td>
<a href="/admin/translation/readFile/{{ $localeCode.'_'.end($path) }}">{{ trans('admin.Edit') }} </a>
</td>
@endforeach
<td><a href="{{ url('admin/translation/getAllContent/'.end($path)) }}">{{ trans('admin.Edit All Language') }}</a></td>
</tr>
@endforeach
</table>
@endsection
|
Remove cronos_debug, un-hardcode the mail address in mail_cronos_admin | # -*- coding: utf-8 -*-
from django.conf import settings
from django.core.mail import send_mail
def mail_cronos_admin(title, message):
'''
Wrapper function of send_mail
'''
try:
send_mail(title, message, '[email protected]', [settings.ADMIN[0][1]])
except:
pass
class CronosError(Exception):
'''
Custom Exception class
'''
def __init__(self, value):
self.value = value
def __unicode__(self):
return repr(self.value)
def log_extra_data(request = None, form = None):
'''
Extra data needed by the custom formatter
All values default to None
'''
log_extra_data = {
'client_ip': request.META.get('REMOTE_ADDR','None') if request else '',
'username': '',
}
if form:
log_extra_data['username'] = form.data.get('username', 'None')
else:
try:
if request.user.is_authenticated():
'''
Handle logged in users
'''
log_extra_data['username'] = request.user.name
else:
'''
Handle anonymous users
'''
log_extra_data['username'] = 'Anonymous'
except AttributeError:
pass
return log_extra_data
| # -*- coding: utf-8 -*-
from django.conf import settings
from django.core.mail import send_mail
import logging
#import traceback
def cronos_debug(msg, logfile):
'''
To be deprecated, along with the import logging and settings
'''
logging.basicConfig(level = logging.DEBUG, format = '%(asctime)s: %(message)s', filename = settings.LOGDIR + logfile, filemode = 'a+')
logging.debug(msg)
def mail_cronos_admin(title, message):
'''
Wrapper function of send_mail
'''
try:
send_mail(title, message, '[email protected]', ['[email protected]'])
except:
pass
class CronosError(Exception):
'''
Custom Exception class
'''
def __init__(self, value):
self.value = value
def __unicode__(self):
return repr(self.value)
def log_extra_data(request = None, form = None):
'''
Extra data needed by the custom formatter
All values default to None
'''
log_extra_data = {
'client_ip': request.META.get('REMOTE_ADDR','None') if request else '',
'username': '',
}
if form:
log_extra_data['username'] = form.data.get('username', 'None')
else:
try:
if request.user.is_authenticated():
'''
Handle logged in users
'''
log_extra_data['username'] = request.user.name
else:
'''
Handle anonymous users
'''
log_extra_data['username'] = 'Anonymous'
except AttributeError:
pass
return log_extra_data
|
Fix for relationships with dashes on POST|PUT | <?php
namespace Luminary\Services\ApiRequest\Content;
class Content
{
/**
* The request body content
*
* @var array
*/
protected $content;
/**
* Content constructor.
*
* @param array $content
*/
public function __construct(array $content)
{
$this->content = $content;
}
/**
* Get the attributes from an request
*
* @return array
*/
public function attributes() :array
{
$attributes = array_get($this->content, 'data.attributes', []);
if ($id = array_get($this->content, 'data.id')) {
$attributes = array_add($attributes, 'id', $id);
}
return $attributes;
}
/**
* Set the relationships from a request
*
* @return array
*/
public function relationships() :array
{
$relationships = array_get($this->content, 'data.relationships', []) ?: [];
$relationships = collect($relationships)->map(
function ($values) {
$data = array_get($values, 'data');
$id = array_get($data, 'id');
return is_null($id) ? array_pluck($data, 'id') : $id;
}
)->toArray();
$keys = array_map(function($key) {
return camel_case($key);
}, array_keys($relationships));
return array_combine($keys, array_values($relationships));
}
/**
* Set the document type from request
*
* @return string
*/
public function type() :string
{
return array_get($this->content, 'data.type', '');
}
}
| <?php
namespace Luminary\Services\ApiRequest\Content;
class Content
{
/**
* The request body content
*
* @var array
*/
protected $content;
/**
* Content constructor.
*
* @param array $content
*/
public function __construct(array $content)
{
$this->content = $content;
}
/**
* Get the attributes from an request
*
* @return array
*/
public function attributes() :array
{
$attributes = array_get($this->content, 'data.attributes', []);
if ($id = array_get($this->content, 'data.id')) {
$attributes = array_add($attributes, 'id', $id);
}
return $attributes;
}
/**
* Set the relationships from a request
*
* @return array
*/
public function relationships() :array
{
$relationships = array_get($this->content, 'data.relationships', []) ?: [];
$relationships = collect($relationships)->map(
function ($values) {
$data = array_get($values, 'data');
$id = array_get($data, 'id');
return is_null($id) ? array_pluck($data, 'id') : $id;
}
)->toArray();
return $relationships;
}
/**
* Set the document type from request
*
* @return string
*/
public function type() :string
{
return array_get($this->content, 'data.type', '');
}
}
|
Change single Lecture query to use first() in stead of all() | from flask import request
from flask_restful import Resource, Api, abort, reqparse
from .models import db, Comment, Lecture
api = Api()
class CommentListResource(Resource):
def get(self, lecture_id):
db_lecture = Lecture.query.filter(Lecture.id == lecture_id).first()
if not db_lecture:
abort(404, message="Lecture {} does not exist".format(lecture_id))
db_comments = Comment.query.filter(Comment.lecture_id == lecture_id)
comments = [
{'id': c.id, 'content': c.content}
for c in db_comments
]
return {
'comments': comments
}
def post(self, lecture_id):
lecture = Lecture.query.filter(Lecture.id == lecture_id).first()
if not lecture:
abort(404, message="Lecture {} does not exist".format(lecture_id))
parser = reqparse.RequestParser()
parser.add_argument('data', help='Text content of comment')
args = parser.parse_args()
if not args.data:
abort(400, message="Comment has no data parameter")
content = args.data
comment = Comment(content, lecture)
db.session.add(comment)
db.session.commit()
return {
'id': comment.id
}
api.add_resource(CommentListResource, '/api/0/lectures/<lecture_id>/comments')
| from flask import request
from flask_restful import Resource, Api, abort, reqparse
from .models import db, Comment, Lecture
api = Api()
class CommentListResource(Resource):
def get(self, lecture_id):
db_lecture = Lecture.query.filter(Lecture.id == lecture_id).first()
if not db_lecture:
abort(404, message="Lecture {} does not exist".format(lecture_id))
db_comments = Comment.query.filter(Comment.lecture_id == lecture_id)
comments = [
{'id': c.id, 'content': c.content}
for c in db_comments
]
return {
'comments': comments
}
def post(self, lecture_id):
db_lectures = Lecture.query.filter(Lecture.id == lecture_id).all()
if not db_lectures:
abort(404, message="Lecture {} does not exist".format(lecture_id))
parser = reqparse.RequestParser()
parser.add_argument('data', help='Text content of comment')
args = parser.parse_args()
if not args.data:
abort(400, message="Comment has no data parameter")
content = args.data
lecture = db_lectures[0]
comment = Comment(content, lecture)
db.session.add(comment)
db.session.commit()
return {
'id': comment.id
}
api.add_resource(CommentListResource, '/api/0/lectures/<lecture_id>/comments')
|
Add SQL error message to log | package com.ksoichiro.task.aspect;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.NestedRuntimeException;
import org.springframework.stereotype.Component;
import java.sql.SQLException;
@Component
@Aspect
@Slf4j
public class ServiceAdvice {
@Pointcut("@within(org.springframework.stereotype.Service)")
public void service() {
}
@Around("service() && execution(* com.ksoichiro.task.service.*.*(..))")
public Object execution(ProceedingJoinPoint pjp) throws Throwable {
try {
return pjp.proceed();
} catch (NestedRuntimeException e) {
if (e.contains(SQLException.class)) {
// If needed, we can handle specific SQL error codes.
SQLException cause = getCause(e, SQLException.class);
log.warn("SQL Error: {}, SQLState: {}, message: {}", cause.getErrorCode(), cause.getSQLState(), cause.getMessage());
}
// Rethrow it to delegate handling
throw e;
}
}
@SuppressWarnings("unchecked")
<T> T getCause(NestedRuntimeException e, Class<T> exceptionClass) {
Throwable cause = e.getCause();
while (cause != null) {
if (exceptionClass.isAssignableFrom(cause.getClass())) {
break;
}
cause = cause.getCause();
}
return (T) cause;
}
}
| package com.ksoichiro.task.aspect;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.NestedRuntimeException;
import org.springframework.stereotype.Component;
import java.sql.SQLException;
@Component
@Aspect
@Slf4j
public class ServiceAdvice {
@Pointcut("@within(org.springframework.stereotype.Service)")
public void service() {
}
@Around("service() && execution(* com.ksoichiro.task.service.*.*(..))")
public Object execution(ProceedingJoinPoint pjp) throws Throwable {
try {
return pjp.proceed();
} catch (NestedRuntimeException e) {
if (e.contains(SQLException.class)) {
// If needed, we can handle specific SQL error codes.
SQLException cause = getCause(e, SQLException.class);
log.warn("SQL Error: {}, SQLState: {}", cause.getErrorCode(), cause.getSQLState());
}
// Rethrow it to delegate handling
throw e;
}
}
@SuppressWarnings("unchecked")
<T> T getCause(NestedRuntimeException e, Class<T> exceptionClass) {
Throwable cause = e.getCause();
while (cause != null) {
if (exceptionClass.isAssignableFrom(cause.getClass())) {
break;
}
cause = cause.getCause();
}
return (T) cause;
}
}
|
Check the end of notification fade-out animation | var NotificationComponent = Ember.Component.extend({
classNames: ['js-bb-notification'],
typeClass: function () {
var classes = '',
message = this.get('message'),
type,
dismissible;
// Check to see if we're working with a DS.Model or a plain JS object
if (typeof message.toJSON === 'function') {
type = message.get('type');
dismissible = message.get('dismissible');
}
else {
type = message.type;
dismissible = message.dismissible;
}
classes += 'notification-' + type;
if (type === 'success' && dismissible !== false) {
classes += ' notification-passive';
}
return classes;
}.property(),
didInsertElement: function () {
var self = this;
self.$().on('animationend webkitAnimationEnd oanimationend MSAnimationEnd', function (event) {
/* jshint unused: false */
if (event.originalEvent.animationName === 'fade-out') {
self.notifications.removeObject(self.get('message'));
}
});
},
actions: {
closeNotification: function () {
var self = this;
self.notifications.closeNotification(self.get('message'));
}
}
});
export default NotificationComponent;
| var NotificationComponent = Ember.Component.extend({
classNames: ['js-bb-notification'],
typeClass: function () {
var classes = '',
message = this.get('message'),
type,
dismissible;
// Check to see if we're working with a DS.Model or a plain JS object
if (typeof message.toJSON === 'function') {
type = message.get('type');
dismissible = message.get('dismissible');
}
else {
type = message.type;
dismissible = message.dismissible;
}
classes += 'notification-' + type;
if (type === 'success' && dismissible !== false) {
classes += ' notification-passive';
}
return classes;
}.property(),
didInsertElement: function () {
var self = this;
self.$().on('animationend webkitAnimationEnd oanimationend MSAnimationEnd', function (event) {
/* jshint unused: false */
self.notifications.removeObject(self.get('message'));
});
},
actions: {
closeNotification: function () {
var self = this;
self.notifications.closeNotification(self.get('message'));
}
}
});
export default NotificationComponent;
|
Expand selected mutation's row on load | var MutationTable = function ()
{
var element
function detailFormatter(index, row, element)
{
var impact = row[4]
var affected_sites_count = row[5]
html = 'Impact: ' + impact + '<br>'
html += '# of affected sites: ' + affected_sites_count + '<br>'
if(affected_sites_count != 0)
{
html += 'Closest affected site(s): <div>' + row[6] + '</div>'
}
if(impact == 'network-rewiring')
{
var row_element = $('#' + row[0] + row[2])
var meta = JSON.parse($(row_element).data('metadata').slice(2, -2).replace(/'/g, '"'))
html += MIMP_image_from_meta(meta.MIMP)
}
return html
}
function getMutationRow(mutation_id)
{
return $('#' + mutation_id)
}
var publicSpace = {
init: function(table_element)
{
element = table_element
element.bootstrapTable({
detailFormatter: detailFormatter
})
if(window.location.hash)
{
publicSpace.expandRow(window.location.hash.substring(1))
}
},
expandRow: function(mutation_id)
{
element.bootstrapTable(
'expandRow',
getMutationRow(mutation_id).data('index')
)
}
}
return publicSpace
}
| var MutationTable = function ()
{
var element
function detailFormatter(index, row, element)
{
var impact = row[4]
var affected_sites_count = row[5]
html = 'Impact: ' + impact + '<br>'
html += '# of affected sites: ' + affected_sites_count + '<br>'
if(affected_sites_count != 0)
{
html += 'Closest affected site(s): <div>' + row[6] + '</div>'
}
if(impact == 'network-rewiring')
{
var row_element = $('#' + row[0] + row[2])
var meta = JSON.parse($(row_element).data('metadata').slice(2, -2).replace(/'/g, '"'))
html += MIMP_image_from_meta(meta.MIMP)
}
return html
}
function getMutationRow(mutation_id)
{
return $('#' + mutation_id)
}
var publicSpace = {
init: function(table_element)
{
element = table_element
element.bootstrapTable({
detailFormatter: detailFormatter
})
},
expandRow: function(mutation_id)
{
element.bootstrapTable(
'expandRow',
getMutationRow(mutation_id).data('index')
)
}
}
return publicSpace
}
|
Check that input to port is an integer | def parse(s):
try:
return Port(int(s))
except ValueError:
if s == "all":
return Port(None)
else:
start, _, end = s.partition('-')
try:
return Port(int(start), int(end))
except ValueError:
return None
class Port(object):
def __init__(self, fromport, toport=None):
assert(isinstance(fromport, int))
assert(isinstance(toport, int))
self._fromport = fromport
if toport:
self._toport = toport
else:
self._toport = fromport
@property
def fromport(self):
return self._fromport
@property
def toport(self):
return self._toport
@property
def all(self):
return self.fromport == None and self.toport == None
def yaml_str(self):
if self.all:
return "all"
elif self.fromport < self.toport:
return "%d-%d" % (self.fromport, self.toport)
else:
return self.fromport
def __hash__(self):
return hash((self.fromport, self.toport))
def __eq__(self, other):
return self.__dict__ == other.__dict__
| def parse(s):
try:
return Port(int(s))
except ValueError:
if s == "all":
return Port(None)
else:
start, _, end = s.partition('-')
try:
return Port(int(start), int(end))
except ValueError:
return None
class Port(object):
def __init__(self, fromport, toport=None):
self._fromport = fromport
if toport:
self._toport = toport
else:
self._toport = fromport
@property
def fromport(self):
return self._fromport
@property
def toport(self):
return self._toport
@property
def all(self):
return self.fromport == None and self.toport == None
def yaml_str(self):
if self.all:
return "all"
elif self.fromport < self.toport:
return "%d-%d" % (self.fromport, self.toport)
else:
return self.fromport
def __hash__(self):
return hash((self.fromport, self.toport))
def __eq__(self, other):
return self.__dict__ == other.__dict__
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.