text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Revert code changes from bea7cd1 | package ch.jalu.injector.annotationhandlers;
import javax.annotation.Nullable;
import java.lang.annotation.Annotation;
/**
* Type safe annotation handler base, which will fire the resolve method only if
* an annotation of the given type is present.
*/
public abstract class TypeSafeAnnotationHandler<T extends Annotation> implements AnnotationHandler {
@Override
public final Object resolveValue(Class<?> clazz, Annotation... annotations) throws Exception {
final Class<T> type = getAnnotationType();
for (Annotation annotation : annotations) {
if (type.isInstance(annotation)) {
return resolveValueSafely(clazz, type.cast(annotation));
}
}
return null;
}
/**
* Returns the class of the annotation the handler can process.
*
* @return the annotation type
*/
protected abstract Class<T> getAnnotationType();
/**
* Resolves the value with the matched annotation, guaranteed to never be null.
*
* @param clazz the dependency's type
* @param annotation the matched annotation
* @return the resolved value, or null if none applicable
*/
@Nullable
protected abstract Object resolveValueSafely(Class<?> clazz, T annotation) throws Exception;
} | package ch.jalu.injector.annotationhandlers;
import javax.annotation.Nullable;
import java.lang.annotation.Annotation;
/**
* .
*/
public abstract class TypeSafeAnnotationHandler<T extends Annotation> implements AnnotationHandler {
@Override
public final Object resolveValue(Annotation... annotations) {
final Class<T> type = getAnnotationType();
for (Annotation annotation : annotations) {
if (type.isInstance(annotation)) {
return resolveValueSafely(type.cast(annotation));
}
}
return null;
}
protected abstract Class<T> getAnnotationType();
@Nullable
protected abstract Object resolveValueSafely(T annotation);
}
|
Exclude test_project from installation so it won't pollute site-packages. | try:
from setuptools import setup, find_packages
except:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name = 'django-flatblocks',
version = '0.3.5',
description = 'django-flatblocks acts like django.contrib.flatpages but '
'for parts of a page; like an editable help box you want '
'show alongside the main content.',
long_description = open('README.rst').read(),
keywords = 'django apps',
license = 'New BSD License',
author = 'Horst Gutmann',
author_email = 'zerok@zerokspot.com',
url = 'http://github.com/zerok/django-flatblocks/',
dependency_links = [],
classifiers = [
'Development Status :: 3 - Alpha',
'Environment :: Plugins',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
],
packages = find_packages(exclude=['ez_setup', 'test_project']),
include_package_data = True,
zip_safe = False,
)
| try:
from setuptools import setup, find_packages
except:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name = 'django-flatblocks',
version = '0.3.5',
description = 'django-flatblocks acts like django.contrib.flatpages but '
'for parts of a page; like an editable help box you want '
'show alongside the main content.',
long_description = open('README.rst').read(),
keywords = 'django apps',
license = 'New BSD License',
author = 'Horst Gutmann',
author_email = 'zerok@zerokspot.com',
url = 'http://github.com/zerok/django-flatblocks/',
dependency_links = [],
classifiers = [
'Development Status :: 3 - Alpha',
'Environment :: Plugins',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
],
packages = find_packages(exclude='ez_setup'),
include_package_data = True,
zip_safe = False,
)
|
Fix hashing for Python 3 | try:
from hashlib import md5
except ImportError:
from md5 import md5
from django.http import HttpResponseBadRequest
from secretballot.middleware import SecretBallotIpUseragentMiddleware
class SecretBallotUserIpUseragentMiddleware(SecretBallotIpUseragentMiddleware):
def generate_token(self, request):
if request.user.is_authenticated():
return request.user.username
else:
try:
s = u''.join((request.META['REMOTE_ADDR'], request.META['HTTP_USER_AGENT']))
return md5(s).hexdigest()
except KeyError:
return None
| try:
from hashlib import md5
except ImportError:
from md5 import md5
from django.http import HttpResponseBadRequest
from secretballot.middleware import SecretBallotIpUseragentMiddleware
class SecretBallotUserIpUseragentMiddleware(SecretBallotIpUseragentMiddleware):
def generate_token(self, request):
if request.user.is_authenticated():
return request.user.username
else:
try:
s = ''.join((request.META['REMOTE_ADDR'], request.META['HTTP_USER_AGENT']))
return md5(s).hexdigest()
except KeyError:
return None
|
Support urls that are not relative by leaving them un-changed | 'use strict';
var path = require('path');
var less = require('../thirdparty/less');
module.exports = fixUrls;
function fixUrls(getURL) {
less.tree.URL.prototype.genCSS = function (env, output) {
output.add("url(");
var basedir = this.currentFileInfo.currentDirectory;
var add = output.add;
var buf = [];
output.add = function (chunk) {
buf.push(chunk);
};
this.value.genCSS(env, output);
output.add = add;
if (buf.length === 3 && buf[0] === buf[2] && (buf[0] === '\'' || buf[0] === '"')
&& buf[1].substr(0, 2) !== '//'
&& buf[1].substr(0, 5) !== 'http:'
&& buf[1].substr(0, 6) !== 'https:') {
var fragment = buf[1].replace(/^[^#]*/, '');
buf[1] = getURL(path.resolve(basedir, buf[1].split('#')[0]));
}
for (var i = 0; i < buf.length; i++) {
output.add(buf[i]);
}
output.add(")");
}
} | 'use strict';
var path = require('path');
var less = require('../thirdparty/less');
module.exports = fixUrls;
function fixUrls(getURL) {
less.tree.URL.prototype.genCSS = function (env, output) {
output.add("url(");
var basedir = this.currentFileInfo.currentDirectory;
var add = output.add;
var buf = [];
output.add = function (chunk) {
buf.push(chunk);
};
this.value.genCSS(env, output);
output.add = add;
if (buf.length === 3 && buf[0] === buf[2] && buf[0] === '\'' || buf[0] === '"') {
var fragment = buf[1].replace(/^[^#]*/, '');
buf[1] = getURL(path.resolve(basedir, buf[1].split('#')[0]));
}
for (var i = 0; i < buf.length; i++) {
output.add(buf[i]);
}
output.add(")");
}
} |
Update to follow latest py.test recommendations
http://pytest.org/latest/goodpractises.html#integrating-with-setuptools-python-setup-py-test | import sys
import setuptools
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")]
def initialize_options(self):
TestCommand.initialize_options(self)
self.pytest_args = []
def finalize_options(self):
pass
def run_tests(self):
import pytest
errno = pytest.main(self.pytest_args)
sys.exit(errno)
VERSION = '0.0.1'
setuptools.setup(
name='multihash',
description='An implementation of Multihash in Python',
author='bmcorser',
author_email='bmcorser@gmail.com',
version=VERSION,
packages=setuptools.find_packages(),
tests_require=['pytest'],
install_requires=['six'],
cmdclass={'test': PyTest},
)
| import sys
import setuptools
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")]
def initialize_options(self):
TestCommand.initialize_options(self)
self.pytest_args = []
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import pytest
errno = pytest.main(self.pytest_args)
sys.exit(errno)
VERSION = '0.0.1'
setuptools.setup(
name='multihash',
description='An implementation of Multihash in Python',
author='bmcorser',
author_email='bmcorser@gmail.com',
version=VERSION,
packages=setuptools.find_packages(),
tests_require=['pytest'],
install_requires=['six'],
cmdclass={'test': PyTest},
)
|
Fix operation call function to allow null argument in addition to associative array | <?php
namespace Fortean\Webservice;
use Httpful\Request as HttpfulRequest;
class Client
{
protected $serviceName;
protected $description;
protected $config;
/**
* Webservice client constructor
*
* @param array $service
* @return void
*/
public function __construct($serviceName)
{
$this->serviceName = $serviceName;
$this->description = new Description($serviceName);
$this->config = config('webservice.'.$serviceName.'.client', []);
}
/**
* The magic function handler used to execute service operations
*
* @param string $name
* @param array $args
* @return variant
*/
public function __call($name, $args)
{
// The first argument should always be an associative array of operation parameters
if ((count($args) == 0) || !is_array($args[0]))
{
throw new WebserviceException('Operations must pass null or an associative array as their first parameter');
}
// Build a URI from the passed data
$uri = $this->description->buildUri($name, $args[0]);
// Find the response type we're expecting
$responseType = $this->description->getResponseType($name);
// Return the results of the request
return HttpfulRequest::get($uri)->expectsType($responseType)->send()->body;
}
} | <?php
namespace Fortean\Webservice;
use Httpful\Request as HttpfulRequest;
class Client
{
protected $serviceName;
protected $description;
protected $config;
/**
* Webservice client constructor
*
* @param array $service
* @return void
*/
public function __construct($serviceName)
{
$this->serviceName = $serviceName;
$this->description = new Description($serviceName);
$this->config = config('webservice.'.$serviceName.'.client', []);
}
/**
* The magic function handler used to execute service operations
*
* @param string $name
* @param array $args
* @return variant
*/
public function __call($name, $args)
{
// Parameters should be an associative array
$parameters = count($args) ? $args[0] : [];
if (!is_array($parameters) || (count($args) > 1))
{
throw new WebserviceException('Operations must pass an associative array as their only parameter');
}
// Build a URI from the passed data
$uri = $this->description->buildUri($name, $parameters);
// Find the response type we're expecting
$responseType = $this->description->getResponseType($name);
// Return the results of the request
return HttpfulRequest::get($uri)->expectsType($responseType)->send()->body;
}
} |
Disable bbox draw in sponza example | import moderngl as mgl
from demosys.effects import effect
class SceneEffect(effect.Effect):
"""Generated default effect"""
def __init__(self):
self.scene = self.get_scene("Sponza/glTF/Sponza.gltf", local=True)
self.proj_mat = self.create_projection(fov=75.0, near=0.01, far=1000.0)
@effect.bind_target
def draw(self, time, frametime, target):
self.ctx.enable(mgl.DEPTH_TEST)
self.sys_camera.velocity = self.scene.diagonal_size / 5.0
self.scene.draw(
projection_matrix=self.proj_mat,
camera_matrix=self.sys_camera.view_matrix,
time=time,
)
# Draw bbox
# self.scene.draw_bbox(self.proj_mat, self.sys_camera.view_matrix, all=True)
| import moderngl as mgl
from demosys.effects import effect
class SceneEffect(effect.Effect):
"""Generated default effect"""
def __init__(self):
self.scene = self.get_scene("Sponza/glTF/Sponza.gltf", local=True)
self.proj_mat = self.create_projection(fov=75.0, near=0.01, far=1000.0)
@effect.bind_target
def draw(self, time, frametime, target):
self.ctx.enable(mgl.DEPTH_TEST)
self.sys_camera.velocity = self.scene.diagonal_size / 5.0
self.scene.draw(
projection_matrix=self.proj_mat,
camera_matrix=self.sys_camera.view_matrix,
time=time,
)
# Draw bbox
self.scene.draw_bbox(self.proj_mat, self.sys_camera.view_matrix, all=True)
|
Use MD5 to encode passwords | from eve import Eve
from eve_swagger import swagger
from eve.auth import BasicAuth
from config import *
from hashlib import md5
class MyBasicAuth(BasicAuth):
def check_auth(self, username, password, allowed_roles, resource,
method):
accounts = app.data.driver.db['accounts']
account = accounts.find_one({'username': username})
return account and md5(password).hexdigest() == account['password']
def set_reporter(request, lookup):
print request
app = Eve(auth=MyBasicAuth)
app.on_pre_PUT_event += set_reporter
app.register_blueprint(swagger)
app.config['SWAGGER_INFO'] = SWAGGER_INFO
app.config['SWAGGER_HOST'] = SWAGGER_HOST
if __name__ == '__main__':
app.run(host=LISTEN_IP, port=LISTEN_PORT)
| from eve import Eve
from eve_swagger import swagger
from eve.auth import BasicAuth
from config import *
from hashlib import md5
class MyBasicAuth(BasicAuth):
def check_auth(self, username, password, allowed_roles, resource,
method):
accounts = app.data.driver.db['accounts']
account = accounts.find_one({'username': username})
return account and password == account['password']
def set_reporter(request, lookup):
print request
app = Eve(auth=MyBasicAuth)
app.on_pre_PUT_event += set_reporter
app.register_blueprint(swagger)
app.config['SWAGGER_INFO'] = SWAGGER_INFO
app.config['SWAGGER_HOST'] = SWAGGER_HOST
if __name__ == '__main__':
app.run(host=LISTEN_IP, port=LISTEN_PORT)
|
Apply a blur filter automatically for each detected face | import requests
import json
imgUrl = 'https://pixlab.io/images/m3.jpg' # Target picture we want to blur any face on
# Detect all human faces in a given image via /facedetect first and blur all of them later via /mogrify.
# https://pixlab.io/cmd?id=facedetect and https://pixlab.io/cmd?id=mogrify for additional information.
req = requests.get('https://api.pixlab.io/facedetect',params={
'img': imgUrl,
'key':'PIXLAB_API_KEY',
})
reply = req.json()
if reply['status'] != 200:
print (reply['error'])
exit();
total = len(reply['faces']) # Total detected faces
print(str(total)+" faces were detected")
if total < 1:
# No faces were detected, exit immediately
exit()
# Pass the facial coordinates for each detected face untouched to mogrify
coordinates = reply['faces']
# Call mogrify & blur the face(s)
req = requests.post('https://api.pixlab.io/mogrify',headers={'Content-Type':'application/json'},data=json.dumps({
'img': imgUrl,
'key':'PIXLAB_API_KEY',
'cord': coordinates # The field of interest
}))
reply = req.json()
if reply['status'] != 200:
print (reply['error'])
else:
print ("Blurred Picture URL: "+ reply['ssl_link'])
| import requests
import json
imgUrl = 'https://pixlab.io/images/m3.jpg' # Target picture we want to blur any face on
# Detect all human faces in a given image via /facedetect first and blur all of them later via /mogrify.
# https://pixlab.io/cmd?id=facedetect and https://pixlab.io/cmd?id=mogrify for additional information.
req = requests.get('https://api.pixlab.io/facedetect',params={
'img': imgUrl,
'key':'PIXLAB_API_KEY',
})
reply = req.json()
if reply['status'] != 200:
print (reply['error'])
exit();
total = len(reply['faces']) # Total detected faces
print(str(total)+" faces were detected")
if total < 1:
# No faces were detected, exit immediately
exit()
# Pass the detected faces coordinates untouched to mogrify
coordinates = reply['faces']
# Call mogrify & blur the face(s)
req = requests.post('https://api.pixlab.io/mogrify',headers={'Content-Type':'application/json'},data=json.dumps({
'img': imgUrl,
'key':'PIXLAB_API_KEY',
'cord': coordinates # The field of interest
}))
reply = req.json()
if reply['status'] != 200:
print (reply['error'])
else:
print ("Blurred Picture URL: "+ reply['ssl_link'])
|
Remove comment line / add whitespace. | <?php
namespace ADesigns\CalendarBundle\Tests\Fixtures\EventListener;
use ADesigns\CalendarBundle\Entity\EventEntity;
use ADesigns\CalendarBundle\Event\CalendarEvent;
/**
* Loads a fake event for testing purposes.
*
* @package ADesigns\CalendarBundle\Tests\Fixtures\EventListener
*/
class CalendarEventListener
{
const TEST_START_TIME = "2016-01-15 13:00";
const TEST_END_TIME = "2016-01-15 14:00";
public function loadEvents(CalendarEvent $calendarEvent)
{
$startTime = new \DateTime(self::TEST_START_TIME);
$endTime = new \DateTime(self::TEST_END_TIME);
if ($calendarEvent->getStartDatetime()->getTimestamp() === $startTime->getTimestamp()
&& $calendarEvent->getEndDatetime()->getTimestamp() === $endTime->getTimestamp()) {
$event = new EventEntity("Fake Event Title", new \DateTime(), null, true);
$calendarEvent->addEvent($event);
}
}
} | <?php
namespace ADesigns\CalendarBundle\Tests\Fixtures\EventListener;
use ADesigns\CalendarBundle\Entity\EventEntity;
use ADesigns\CalendarBundle\Event\CalendarEvent;
/**
* Loads a fake event for testing purposes.
*
* @package ADesigns\CalendarBundle\Tests\Fixtures\EventListener
*/
class CalendarEventListener
{
const TEST_START_TIME = "2016-01-15 13:00";
const TEST_END_TIME = "2016-01-15 14:00";
public function loadEvents(CalendarEvent $calendarEvent)
{
// these
$startTime = new \DateTime(self::TEST_START_TIME);
$endTime = new \DateTime(self::TEST_END_TIME);
if ($calendarEvent->getStartDatetime()->getTimestamp() === $startTime->getTimestamp()
&& $calendarEvent->getEndDatetime()->getTimestamp() === $endTime->getTimestamp()) {
$event = new EventEntity("Fake Event Title", new \DateTime(), null, true);
$calendarEvent->addEvent($event);
}
}
} |
Fix float diff comparison in dict differ function. | # coding=utf-8
__all__ = ['UTC']
from datetime import timedelta, tzinfo
_ZERO = timedelta(0)
def is_dict_different(d1, d2, epsilon=0.00000000001):
s1 = set(d1.keys())
s2 = set(d2.keys())
intersect = s1.intersection(s2)
added = s1 - intersect
removed = s2 - intersect
changed = []
for o in intersect:
if isinstance(d2[o], float):
if abs(d2[o] - d1[o]) > epsilon:
changed.append(o)
elif d2[o] != d1[o]:
changed.append(o)
return (0 < len(added) or 0 < len(removed) or 0 < len(set(changed)))
class UTC(tzinfo):
def utcoffset(self, dt):
return _ZERO
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return _ZERO
| # coding=utf-8
__all__ = ['UTC']
from datetime import timedelta, tzinfo
_ZERO = timedelta(0)
def is_dict_different(d1, d2, epsilon=0.00000000001):
s1 = set(d1.keys())
s2 = set(d2.keys())
intersect = s1.intersection(s2)
added = s1 - intersect
removed = s2 - intersect
changed = []
for o in intersect:
if isinstance(s2, float) and abs(d2[o] - d1[o]) > epsilon:
changed.append(o)
elif d2[o] != d1[o]:
changed.append(o)
return (0 < len(added) or 0 < len(removed) or 0 < len(set(changed)))
class UTC(tzinfo):
def utcoffset(self, dt):
return _ZERO
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return _ZERO
|
Revert "Hackily unblock the build"
This reverts commit ea8a58282545fe8fbf7700ad05f50aeb6b492294. | /*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.api.tasks;
import org.gradle.api.Action;
import org.gradle.api.Incubating;
import org.gradle.api.Task;
import org.gradle.api.provider.Provider;
/**
* Providers a task of the given type.
*
* @param <T> Task type
* @since 4.8
*/
@Incubating
public interface TaskProvider<T extends Task> extends Provider<T> {
/**
* Configures the task with the given action. Actions are run in the order added.
*
* @param action A {@link Action} that can configure the task when required.
* @since 4.8
*/
void configure(Action<? super T> action);
/**
* The task name referenced by this provider.
* <p>
* Must be constant for the life of the object.
*
* @return The task name. Never null.
* @since 4.9
*/
String getName();
}
| /*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.api.tasks;
import org.gradle.api.Action;
import org.gradle.api.Incubating;
import org.gradle.api.Task;
import org.gradle.api.provider.Provider;
/**
* Providers a task of the given type.
*
* @param <T> Task type
* @since 4.8
*/
@Incubating
public interface TaskProvider<T extends Task> extends Provider<T> {
/**
* Configures the task with the given action. Actions are run in the order added.
*
* @param action A {@link Action} that can configure the task when required.
* @since 4.8
*/
void configure(Action<? super T> action);
/**
* The task name referenced by this provider.
* <p>
* Must be constant for the life of the object.
*
* @return The task name. Never null.
* @since 4.10
*/
String getName();
}
|
Move protocol matcher in arg list | <?php
namespace Icicle\WebSocket\Server;
use Icicle\Http\Server\Server as HttpServer;
use Icicle\Http\Server\RequestHandler;
use Icicle\Log\Log;
use Icicle\Socket\Server\ServerFactory;
use Icicle\WebSocket\Driver\Driver;
use Icicle\WebSocket\Driver\WebSocketDriver;
use Icicle\WebSocket\Protocol\DefaultProtocolMatcher;
use Icicle\WebSocket\Protocol\ProtocolMatcher;
class Server extends HttpServer
{
/**
* @param \Icicle\Http\Server\RequestHandler $handler
* @param \Icicle\Log\Log|null $log
* @param \Icicle\WebSocket\Protocol\ProtocolMatcher|null $matcher
* @param \Icicle\WebSocket\Driver\Driver|null $driver
* @param \Icicle\Socket\Server\ServerFactory|null $factory
*/
public function __construct(
RequestHandler $handler,
Log $log = null,
ProtocolMatcher $matcher = null,
Driver $driver = null,
ServerFactory $factory = null
) {
$handler = new Internal\WebSocketRequestHandler($matcher ?: new DefaultProtocolMatcher(), $handler);
$driver = $driver ?: new WebSocketDriver();
parent::__construct($handler, $log, $driver, $factory);
}
}
| <?php
namespace Icicle\WebSocket\Server;
use Icicle\Http\Server\Server as HttpServer;
use Icicle\Http\Server\RequestHandler;
use Icicle\Log\Log;
use Icicle\Socket\Server\ServerFactory;
use Icicle\WebSocket\Driver\Driver;
use Icicle\WebSocket\Driver\WebSocketDriver;
use Icicle\WebSocket\Protocol\DefaultProtocolMatcher;
use Icicle\WebSocket\Protocol\ProtocolMatcher;
class Server extends HttpServer
{
/**
* @param \Icicle\Http\Server\RequestHandler $handler
* @param \Icicle\Log\Log|null $log
* @param \Icicle\WebSocket\Driver\Driver|null $driver
* @param \Icicle\Socket\Server\ServerFactory|null $factory
* @param \Icicle\WebSocket\Protocol\ProtocolMatcher|null $matcher
*/
public function __construct(
RequestHandler $handler,
Log $log = null,
Driver $driver = null,
ServerFactory $factory = null,
ProtocolMatcher $matcher = null
) {
$handler = new Internal\WebSocketRequestHandler($matcher ?: new DefaultProtocolMatcher(), $handler);
$driver = $driver ?: new WebSocketDriver();
parent::__construct($handler, $log, $driver, $factory);
}
}
|
Remove restricted modifier for header
Co-Authored-By: Gagah Pangeran Rosfatiputra <46f1a0bd5592a2f9244ca321b129902a06b53e03@gagahpangeran.com> | {{--
Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
See the LICENCE file in the repository root for full licence text.
--}}
@include('layout._header_mobile')
<div
class="
js-pinned-header
hidden-xs
no-print
nav2-header
">
<div class="nav2-header__body">
<div class="nav2-header__menu-bg js-nav2--menu-bg" data-visibility="hidden"></div>
<div class="nav2-header__triangles"></div>
<div class="nav2-header__transition-overlay"></div>
<div class="osu-page">
@include('layout._nav2')
</div>
</div>
@include('layout._sticky_header')
</div>
@if (Auth::user() === null)
@include('layout._popup_login')
@endif
<div class="js-user-verification--reference"></div>
@include('layout._user_verification_popup')
| {{--
Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
See the LICENCE file in the repository root for full licence text.
--}}
@include('layout._header_mobile')
<div
class="
js-pinned-header
hidden-xs
no-print
nav2-header
{{ optional(Auth::user())->isRestricted() ? 'nav2-header--restricted' : '' }}
">
<div class="nav2-header__body">
<div class="nav2-header__menu-bg js-nav2--menu-bg" data-visibility="hidden"></div>
<div class="nav2-header__triangles"></div>
<div class="nav2-header__transition-overlay"></div>
<div class="osu-page">
@include('layout._nav2')
</div>
</div>
@include('layout._sticky_header')
</div>
@if (Auth::user() === null)
@include('layout._popup_login')
@endif
<div class="js-user-verification--reference"></div>
@include('layout._user_verification_popup')
|
Fix list not loading on second open
Closes #3369 | import { takeLatest, delay } from 'redux-saga';
import { fork, select, put, take } from 'redux-saga/effects';
import * as actions from '../screens/List/constants';
import updateParams from './updateParams';
import { loadItems } from '../screens/List/actions';
/**
* Load the items
*/
function * loadTheItems () {
yield put(loadItems());
}
/**
* Debounce the search loading new items by 500ms
*/
function * debouncedSearch () {
const searchString = yield select((state) => state.active.search);
if (searchString) {
yield delay(500);
}
yield updateParams();
}
function * rootSaga () {
// Block loading on all items until the first load comes in
yield take(actions.INITIAL_LIST_LOAD);
yield put(loadItems());
// Search debounced
yield fork(takeLatest, actions.SET_ACTIVE_SEARCH, debouncedSearch);
// If one of the other active properties changes, update the query params and load the new items
yield fork(takeLatest, [actions.SET_ACTIVE_SORT, actions.SET_ACTIVE_COLUMNS, actions.SET_CURRENT_PAGE], updateParams);
// Whenever the filters change or another list is loaded, load the items
yield fork(takeLatest, [actions.INITIAL_LIST_LOAD, actions.ADD_FILTER, actions.CLEAR_FILTER, actions.CLEAR_ALL_FILTERS], loadTheItems);
}
export default rootSaga;
| import { takeLatest, delay } from 'redux-saga';
import { fork, select, put, take } from 'redux-saga/effects';
import * as actions from '../screens/List/constants';
import updateParams from './updateParams';
import { loadItems } from '../screens/List/actions';
/**
* Load the items
*/
function * loadTheItems () {
yield put(loadItems());
}
/**
* Debounce the search loading new items by 500ms
*/
function * debouncedSearch () {
const searchString = yield select((state) => state.active.search);
if (searchString) {
yield delay(500);
}
yield updateParams();
}
function * rootSaga () {
yield take(actions.INITIAL_LIST_LOAD);
yield put(loadItems());
yield fork(takeLatest, actions.SET_ACTIVE_SEARCH, debouncedSearch);
yield fork(takeLatest, [actions.SET_ACTIVE_SORT, actions.SET_ACTIVE_COLUMNS, actions.SET_CURRENT_PAGE], updateParams);
yield fork(takeLatest, [actions.ADD_FILTER, actions.CLEAR_FILTER, actions.CLEAR_ALL_FILTERS], loadTheItems);
}
export default rootSaga;
|
Fix farmland blocks being trampled by any entity | package com.ptsmods.morecommands.mixin.compat.compat17.plus;
import com.ptsmods.morecommands.api.IMoreGameRules;
import net.minecraft.block.BlockState;
import net.minecraft.block.FarmlandBlock;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
@Mixin(FarmlandBlock.class)
public class MixinFarmlandBlock {
@Redirect(at = @At(value = "INVOKE", target = "Lnet/minecraft/block/FarmlandBlock;setToDirt(Lnet/minecraft/block/BlockState;Lnet/minecraft/world/World;Lnet/minecraft/util/math/BlockPos;)V"), method = "onLandedUpon")
private void onLandedUpon_setToDirt(BlockState state, World world, BlockPos pos) {
if (world.getGameRules().getBoolean(IMoreGameRules.get().doFarmlandTrampleRule())) FarmlandBlock.setToDirt(state, world, pos);
}
}
| package com.ptsmods.morecommands.mixin.compat.compat17.plus;
import com.ptsmods.morecommands.api.IMoreGameRules;
import net.minecraft.block.BlockState;
import net.minecraft.block.FarmlandBlock;
import net.minecraft.entity.Entity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(FarmlandBlock.class)
public class MixinFarmlandBlock {
@Inject(at = @At("HEAD"), method = "onLandedUpon")
private void onLandedUpon_setToDirt(World world, BlockState state, BlockPos pos, Entity entity, float fallDistance, CallbackInfo cbi) {
if (world.getGameRules().getBoolean(IMoreGameRules.get().doFarmlandTrampleRule())) FarmlandBlock.setToDirt(state, world, pos);
}
}
|
Add second author for testing purposes | from elsapy import *
conFile = open("config.json")
config = json.load(conFile)
myCl = elsClient(config['apikey'])
myAuth = elsAuthor('http://api.elsevier.com/content/author/AUTHOR_ID:7004367821') ## author with more than 25 docs
##myAuth = elsAuthor('http://api.elsevier.com/content/author/AUTHOR_ID:55934026500') ## author with less than 25 docs
myAuth.read(myCl)
print ("myAuth.fullName: ", myAuth.fullName)
myAff = elsAffil('http://api.elsevier.com/content/affiliation/AFFILIATION_ID:60016849')
myAff.read(myCl)
print ("myAff.name: ", myAff.name)
myDoc = elsDoc('http://api.elsevier.com/content/abstract/SCOPUS_ID:84872135457')
myDoc.read(myCl)
print ("myDoc.title: ", myDoc.title)
myAuth.readDocs(myCl)
print ("myAuth.docList: ")
i = 0
for doc in myAuth.docList:
i += 1
print (i, ' - ', doc['dc:title'])
| from elsapy import *
conFile = open("config.json")
config = json.load(conFile)
myCl = elsClient(config['apikey'])
myAuth = elsAuthor('http://api.elsevier.com/content/author/AUTHOR_ID:7004367821')
myAuth.read(myCl)
print ("myAuth.fullName: ", myAuth.fullName)
myAff = elsAffil('http://api.elsevier.com/content/affiliation/AFFILIATION_ID:60016849')
myAff.read(myCl)
print ("myAff.name: ", myAff.name)
myDoc = elsDoc('http://api.elsevier.com/content/abstract/SCOPUS_ID:84872135457')
myDoc.read(myCl)
print ("myDoc.title: ", myDoc.title)
myAuth.readDocs(myCl)
print ("myAuth.docList: ")
i = 0
for doc in myAuth.docList:
i += 1
print (i, ' - ', doc['dc:title'])
|
refactor: Add the program name to error messages | #!/usr/bin/env node
const co = require('co');
const util = require('./lib/util');
const runCommand = require('./lib/run.cmd');
const initCommand = require('./lib/init.cmd');
const constants = require('./lib/constants');
const main = function* (argv) {
if (argv.help) {
return util.writeLn(yield util.help());
}
if (argv.version) {
return util.writeLn(yield util.version());
}
if (argv._.length && argv._[0] === 'init') {
return yield initCommand();
}
const config = yield util.findConf(process.cwd(), constants.CONFIG_FILE_NAME);
if (!config) {
util.writeErrLn(`ssh-seed:Error: ${constants.CONFIG_FILE_NAME} is not found.`);
process.exit(1);
}
config.config = util.setDefaultConf(config.config);
for (const key in config.config.keys) {
yield runCommand(key, config);
}
};
if (!module.parent) {
co(function* () {
const argv = util.parseArg();
yield main(argv);
});
}
| #!/usr/bin/env node
const co = require('co');
const util = require('./lib/util');
const runCommand = require('./lib/run.cmd');
const initCommand = require('./lib/init.cmd');
const constants = require('./lib/constants');
const main = function* (argv) {
if (argv.help) {
return util.writeLn(yield util.help());
}
if (argv.version) {
return util.writeLn(yield util.version());
}
if (argv._.length && argv._[0] === 'init') {
return yield initCommand();
}
const config = yield util.findConf(process.cwd(), constants.CONFIG_FILE_NAME);
if (!config) {
util.writeErrLn(`Error: ${constants.CONFIG_FILE_NAME} is not found`);
process.exit(1);
}
config.config = util.setDefaultConf(config.config);
for (const key in config.config.keys) {
yield runCommand(key, config);
}
};
if (!module.parent) {
co(function* () {
const argv = util.parseArg();
yield main(argv);
});
}
|
Add default value to channels | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMusicSettings extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('music_settings', function (Blueprint $table) {
$table->string('id')->primary();
$table->boolean('enabled')->default(true);
$table->enum('mode', ['OFF','WHITELIST', 'BLACKLIST'])->default('OFF');
$table->text('channels')->default('');
$table->text('blacklist_songs')->default('')->nullable();
$table->integer('max_queue_length')->default(-1);
$table->integer('max_song_length')->default(-1);
$table->integer('skip_cooldown')->default(0);
$table->integer('skip_timer')->default(30);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('music_settings');
}
}
| <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMusicSettings extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('music_settings', function (Blueprint $table) {
$table->string('id')->primary();
$table->boolean('enabled')->default(true);
$table->enum('mode', ['OFF','WHITELIST', 'BLACKLIST'])->default('OFF');
$table->text('channels');
$table->text('blacklist_songs')->nullable();
$table->integer('max_queue_length')->default(-1);
$table->integer('max_song_length')->default(-1);
$table->integer('skip_cooldown')->default(0);
$table->integer('skip_timer')->default(30);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('music_settings');
}
}
|
Use async patterns for set-region command. | const {Command} = require('./index.js');
const {wotblitz: {default_region}} = require('../../blitzbot.json');
const options = {
argCount: 1,
description: 'Update your personal default region.',
signatures: ['@BOTNAME set-region [region]']
};
const command = new Command(setRegion, options, 'set-region');
module.exports = command;
async function setRegion(msg, region) {
switch (region && region.toLowerCase()) {
case 'asia':
case 'a':
region = 'asia';
break;
case 'eu':
case 'e':
region = 'eu';
break;
case 'ru':
case 'r':
region = 'ru';
break;
case 'na':
case 'n':
region = 'na';
break;
default:
region = default_region;
break;
}
const sent = await msg.reply('Region set to "' + region + '".');
return {
sentMsg: sent,
master: true,
updateFields: {
region: region
}
};
}
| const {Command} = require('./index.js');
const {wotblitz: {default_region}} = require('../../blitzbot.json');
const options = {
argCount: 1,
description: 'Update your personal default region.',
signatures: ['@BOTNAME set-region [region]']
};
const command = new Command(setRegion, options, 'set-region');
module.exports = command;
function setRegion(msg, region) {
switch (region && region.toLowerCase()) {
case 'asia':
case 'a':
region = 'asia';
break;
case 'eu':
case 'e':
region = 'eu';
break;
case 'ru':
case 'r':
region = 'ru';
break;
case 'na':
case 'n':
region = 'na';
break;
default:
region = default_region;
break;
}
return msg.reply('Region set to "' + region + '".').then(sent => {
return {
sentMsg: sent,
master: true,
updateFields: {
region: region
}
};
});
}
|
[CHORE] Update relative path to static files. | var express = require('express')
var expressValidator = require('express-validator')
var passport = require('./passport.js');
module.exports = (function(){
function configure(app) {
app.use(function(req,res,next) {
res.header("Access-Control-Allow-Origin", "*")
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
next()
})
app.use(express.bodyParser())
app.use(expressValidator());
app.use(express.cookieParser())
app.use(express.session({secret: 'oi09ajsdf09fwlkej33lkjpx'}))
app.use(express.methodOverride())
app.use(express.static(__dirname + '/../../public'))
app.use(passport.initialize())
app.use(function(err, req, res, next) {
res.send({ error: err })
});
}
return { configure: configure }
})()
| var express = require('express')
var expressValidator = require('express-validator')
var passport = require('./passport.js');
module.exports = (function(){
function configure(app) {
app.use(express.static(__dirname + '/public'))
app.use(passport.initialize())
app.use(express.static(__dirname + '/public'))
app.use(function(req,res,next) {
res.header("Access-Control-Allow-Origin", "*")
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
next()
})
app.use(express.bodyParser())
app.use(expressValidator());
app.use(express.cookieParser())
app.use(express.session({secret: 'oi09ajsdf09fwlkej33lkjpx'}))
app.use(express.methodOverride())
app.use(function(err, req, res, next) {
res.send({ error: err })
});
}
return { configure: configure }
})()
|
Use callbacks for run schedule script (node exit before resolve) | const initialize = require('../src/util/initialization.js')
const connectDatabase = require('../src/util/connectDatabase.js')
const ScheduleRun = require('../src/structs/ScheduleRun.js')
const setConfig = require('../src/config.js').set
async function testScheduleRun (userConfig, callback) {
let config = setConfig(userConfig)
config = setConfig({
...config,
log: {
...config.log,
level: 'debug'
}
})
const con = await connectDatabase(config.database.uri, config.database.connection)
try {
console.log('Connected to database')
await initialize.setupModels(con)
console.log('Models set up')
const schedule = {
name: 'default',
refreshRateMinutes: 999
}
console.log('Running...')
const scheduleRun = new ScheduleRun(schedule, 0, {}, {}, true)
scheduleRun.on('finish', () => {
callback(undefined, scheduleRun)
con.close()
})
await scheduleRun.run(new Set())
} catch (err) {
callback(err)
} finally {
con.close()
}
}
module.exports = testScheduleRun
| const initialize = require('../src/util/initialization.js')
const connectDatabase = require('../src/util/connectDatabase.js')
const ScheduleRun = require('../src/structs/ScheduleRun.js')
const setConfig = require('../src/config.js').set
async function testScheduleRun (userConfig) {
let config = setConfig(userConfig)
config = setConfig({
...config,
log: {
...config.log,
level: 'debug'
}
})
const con = await connectDatabase(config.database.uri, config.database.connection)
try {
console.log('Connected to database')
await initialize.setupModels(con)
console.log('Models set up')
const schedule = {
name: 'default',
refreshRateMinutes: 999
}
console.log('Running...')
const scheduleRun = new ScheduleRun(schedule, 0, {}, {}, true)
scheduleRun.on('finish', () => {
con.close()
})
await scheduleRun.run(new Set())
return scheduleRun
} finally {
con.close()
}
}
module.exports = testScheduleRun
|
Fix check on wrong variable | import os
from django.core.management.base import BaseCommand
from ...settings import create_saml_settings, get_settings_dir_and_path
class Command(BaseCommand):
"""
Command to create the saml_settings.json file.
"""
help = "Create the saml_settings.json settings file."
def add_arguments(self, parser):
parser.add_argument(
"-d",
"--dir",
default=None,
help="Directory for the saml_settings.json file.",
)
def handle(self, *args, **options):
settings_dir = options.get("dir")
if settings_dir is not None:
settings_path = os.path.join(settings_dir, "saml_settings.json")
if not os.path.isdir(settings_dir):
print(f"The directory '{settings_dir}' does not exist. Aborting...")
return
else:
_, settings_path = get_settings_dir_and_path()
create_saml_settings(settings_path)
| import os
from django.core.management.base import BaseCommand
from ...settings import create_saml_settings, get_settings_dir_and_path
class Command(BaseCommand):
"""
Command to create the saml_settings.json file.
"""
help = "Create the saml_settings.json settings file."
def add_arguments(self, parser):
parser.add_argument(
"-d",
"--dir",
default=None,
help="Directory for the saml_settings.json file.",
)
def handle(self, *args, **options):
settings_dir = options.get("dir")
if settings_dir is not None:
settings_path = os.path.join(settings_dir, "saml_settings.json")
if not os.path.isdir(settings_path):
print(f"The directory '{settings_dir}' does not exist. Aborting...")
return
else:
_, settings_path = get_settings_dir_and_path()
create_saml_settings(settings_path)
|
Remove counter data when it's removed |
import React from "react";
import {connectLean} from "../src/lean";
import {range} from "lodash/fp";
import Counter from "./Counter";
var DynamicCounters = ({counterCount, scope, addCounter, removeCounter}) => (
<div>
<button onClick={addCounter} >add counter</button>
<button onClick={removeCounter} >remove counter</button>
{range(0, counterCount).map(i => <Counter key={i} scope={[scope, "counters", i]} />)}
</div>
);
DynamicCounters = connectLean({
scope: "dynamicCounters",
defaultProps: {
counterCount: 1,
},
handlers: {
addCounter(e) {
e.preventDefault();
// Instead of accessing the props from the arguments you can also
// return a object of functions to get the previus value in the
// key.
return {counterCount: i => i + 1};
},
removeCounter(e) {
e.preventDefault();
return {
counterCount: i => Math.max(i - 1, 0),
counters: a => a.slice(0, -1), // Remove last from the counters array
};
},
},
})(DynamicCounters);
export default DynamicCounters;
|
import React from "react";
import {connectLean} from "../src/lean";
import {range} from "lodash/fp";
import Counter from "./Counter";
var DynamicCounters = ({counterCount, scope, addCounter, removeCounter}) => (
<div>
<button onClick={addCounter} >add counter</button>
<button onClick={removeCounter} >remove counter</button>
{range(0, counterCount).map(i => <Counter key={i} scope={[scope, "counters", i]} />)}
</div>
);
DynamicCounters = connectLean({
scope: "dynamicCounters",
defaultProps: {
counterCount: 1,
},
handlers: {
addCounter(e) {
e.preventDefault();
// Instead of accessing the props from the arguments you can also
// return a object of functions to get the previus value in the
// key.
return {counterCount: i => i + 1};
},
removeCounter(e) {
e.preventDefault();
return {counterCount: i => Math.max(i - 1, 0)};
},
},
})(DynamicCounters);
export default DynamicCounters;
|
[change] Remove need to set up properties. | 'use strict';
const events = require('events');
const utils = require('util');
const base = require('./base.js');
const protos = require('./proto.js');
const statics = require('./static.js');
const validators = require('./validator.js');
exports.createModel = createModel;
function createModel (name, properties) {
if (typeof name !== 'string') throw new TypeError('Model name required');
function Model(attrs) {
if (!(this instanceof Model)) {
return new Model(attrs);
}
events.EventEmitter.call(this);
if (attrs) {
let self = this;
Object.keys(attrs).forEach(function (key) {
self[key] = attrs[key];
});
self.model.emit('construct', this, attrs);
}
}
inherits(Model, name, properties);
return Model;
}
function inherits(Model, name, properties) {
Model.modelName = name;
utils.inherits(Model, events.EventEmitter);
base.setProperties(Model);
statics.setProperties(Model);
if (properties) protos.setProperties(Model, properties);
}
| 'use strict';
const events = require('events');
const utils = require('util');
const base = require('./base.js');
const protos = require('./proto.js');
const statics = require('./static.js');
const validators = require('./validator.js');
exports.createModel = createModel;
function createModel (name, properties) {
if (typeof name !== 'string') throw new TypeError('Model name required');
function Model(attrs) {
if (!(this instanceof Model)) {
return new Model(attrs);
}
events.EventEmitter.call(this);
if (properties && attrs) {
let self = this;
Object.keys(attrs).forEach(function (key) {
self[key] = attrs[key];
});
self.model.emit('construct', this, attrs);
}
}
inherits(Model, name, properties);
return Model;
}
function inherits(Model, name, properties) {
Model.modelName = name;
utils.inherits(Model, events.EventEmitter);
base.setProperties(Model);
statics.setProperties(Model);
if (properties) protos.setProperties(Model, properties);
}
|
Add note about required additional packages installation |
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
#
# From https://twistedmatrix.com/documents/current/_downloads/simpleserv.py
# NOTE: pyrollbar requires both `Twisted` and `treq` packages to be installed
from twisted.internet import reactor, protocol
import rollbar
def bar(p):
# These local variables will be sent to Rollbar and available in the UI
a = 33
b = a * 5
baz()
def foo():
hello = 'world'
bar(hello)
class Echo(protocol.Protocol):
"""This is just about the simplest possible protocol"""
def dataReceived(self, data):
"As soon as any data is received, write it back."
# Cause an uncaught exception to be sent to Rollbar
foo()
self.transport.write(data)
def main():
rollbar.init('ACCESS_TOKEN', environment='test', handler='twisted')
"""This runs the protocol on port 8000"""
factory = protocol.ServerFactory()
factory.protocol = Echo
reactor.listenTCP(8000, factory)
reactor.run()
# this only runs if the module was *not* imported
if __name__ == '__main__':
main()
|
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
#
# From https://twistedmatrix.com/documents/current/_downloads/simpleserv.py
from twisted.internet import reactor, protocol
import rollbar
def bar(p):
# These local variables will be sent to Rollbar and available in the UI
a = 33
b = a * 5
baz()
def foo():
hello = 'world'
bar(hello)
class Echo(protocol.Protocol):
"""This is just about the simplest possible protocol"""
def dataReceived(self, data):
"As soon as any data is received, write it back."
# Cause an uncaught exception to be sent to Rollbar
foo()
self.transport.write(data)
def main():
rollbar.init('ACCESS_TOKEN', environment='test', handler='twisted')
"""This runs the protocol on port 8000"""
factory = protocol.ServerFactory()
factory.protocol = Echo
reactor.listenTCP(8000, factory)
reactor.run()
# this only runs if the module was *not* imported
if __name__ == '__main__':
main()
|
BB-4056: Add or adjust implementation of the SKU filters from the grid. Both use StringFilter in the ORM version
- namespace fix | <?php
namespace Oro\Bundle\SearchBundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Oro\Bundle\SearchBundle\DependencyInjection\Compiler\FilterTypesPass;
use Oro\Bundle\SearchBundle\DependencyInjection\Compiler\ListenerExcludeSearchConnectionPass;
use Oro\Component\DependencyInjection\ExtendedContainerBuilder;
class OroSearchBundle extends Bundle
{
/** {@inheritdoc} */
public function build(ContainerBuilder $container)
{
if ($container instanceof ExtendedContainerBuilder) {
$container->addCompilerPass(new ListenerExcludeSearchConnectionPass());
$container->moveCompilerPassBefore(
'Oro\Bundle\SearchBundle\DependencyInjection\Compiler\ListenerExcludeSearchConnectionPass',
'Oro\Bundle\PlatformBundle\DependencyInjection\Compiler\UpdateDoctrineEventHandlersPass'
);
}
$container->addCompilerPass(new FilterTypesPass());
}
}
| <?php
namespace Oro\Bundle\SearchBundle;
use Oro\Bundle\SearchBundle\DependencyInjection\Compiler\FilterTypesPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Oro\Bundle\SearchBundle\DependencyInjection\Compiler\ListenerExcludeSearchConnectionPass;
use Oro\Component\DependencyInjection\ExtendedContainerBuilder;
class OroSearchBundle extends Bundle
{
/** {@inheritdoc} */
public function build(ContainerBuilder $container)
{
if ($container instanceof ExtendedContainerBuilder) {
$container->addCompilerPass(new ListenerExcludeSearchConnectionPass());
$container->moveCompilerPassBefore(
'Oro\Bundle\SearchBundle\DependencyInjection\Compiler\ListenerExcludeSearchConnectionPass',
'Oro\Bundle\PlatformBundle\DependencyInjection\Compiler\UpdateDoctrineEventHandlersPass'
);
}
$container->addCompilerPass(new FilterTypesPass());
}
}
|
Update error message for zero hash change. | // Copyright (c) 2013 Conformal Systems LLC.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package ldb_test
import (
"github.com/conformal/btcdb"
"github.com/conformal/btcwire"
"os"
"testing"
)
// we need to test for empty databas and make certain it returns proper value
func TestEmptyDB(t *testing.T) {
dbname := "tstdbempty"
_ = os.RemoveAll(dbname)
db, err := btcdb.CreateDB("leveldb", dbname)
if err != nil {
t.Errorf("Failed to open test database %v", err)
return
}
defer os.RemoveAll(dbname)
// This is a reopen test
db.Close()
db, err = btcdb.OpenDB("leveldb", dbname)
if err != nil {
t.Errorf("Failed to open test database %v", err)
return
}
defer db.Close()
sha, height, err := db.NewestSha()
if !sha.IsEqual(&btcwire.ShaHash{}) {
t.Errorf("sha not zero hash")
}
if height != -1 {
t.Errorf("height not -1 %v", height)
}
}
| // Copyright (c) 2013 Conformal Systems LLC.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package ldb_test
import (
"github.com/conformal/btcdb"
"github.com/conformal/btcwire"
"os"
"testing"
)
// we need to test for empty databas and make certain it returns proper value
func TestEmptyDB(t *testing.T) {
dbname := "tstdbempty"
_ = os.RemoveAll(dbname)
db, err := btcdb.CreateDB("leveldb", dbname)
if err != nil {
t.Errorf("Failed to open test database %v", err)
return
}
defer os.RemoveAll(dbname)
// This is a reopen test
db.Close()
db, err = btcdb.OpenDB("leveldb", dbname)
if err != nil {
t.Errorf("Failed to open test database %v", err)
return
}
defer db.Close()
sha, height, err := db.NewestSha()
if !sha.IsEqual(&btcwire.ShaHash{}) {
t.Errorf("sha not nil")
}
if height != -1 {
t.Errorf("height not -1 %v", height)
}
}
|
Remove print statement about number of bins | #! /usr/bin/python3
import sys
import os
import math
from astropy.io import fits
inputFolder = sys.argv[1]
outputFolder = sys.argv[2]
eLo = int(sys.argv[3])
eHi = int(sys.argv[4])
binSize = int(sys.argv[5])
fnames = os.listdir(inputFolder)
for fname in fnames:
print(fname)
hdulist = fits.open(inputFolder+"/"+fname)
for i in range(1,5):
timeRange = hdulist[i].header["TSTOP"] - hdulist[i].header["TSTART"]
nBins = math.ceil(timeRange/binSize)
count = [0]*nBins
for event in hdulist[i].data:
if(event["ENERGY"]>=eLo or event["ENERGY"]<=eHi):
index = math.floor( nBins*(event["Time"] - hdulist[i].header["TSTART"])/timeRange )
count[index] += 1
sigClass = 1
with open(outputFolder+"/{0}_{1}".format(fname,i),'w') as f:
f.write("{0} {1}\n".format(nBins,sigClass))
for j in range(nBins):
f.write("{0}\n".format(count[j]))
| #! /usr/bin/python3
import sys
import os
import math
from astropy.io import fits
inputFolder = sys.argv[1]
outputFolder = sys.argv[2]
eLo = int(sys.argv[3])
eHi = int(sys.argv[4])
binSize = int(sys.argv[5])
fnames = os.listdir(inputFolder)
for fname in fnames:
print(fname)
hdulist = fits.open(inputFolder+"/"+fname)
for i in range(1,5):
timeRange = hdulist[i].header["TSTOP"] - hdulist[i].header["TSTART"]
nBins = math.ceil(timeRange/binSize)
count = [0]*nBins
print(nBins)
for event in hdulist[i].data:
if(event["ENERGY"]>=eLo or event["ENERGY"]<=eHi):
index = math.floor( nBins*(event["Time"] - hdulist[i].header["TSTART"])/timeRange )
count[index] += 1
sigClass = 1
with open(outputFolder+"/{0}_{1}".format(fname,i),'w') as f:
f.write("{0} {1}\n".format(nBins,sigClass))
for j in range(nBins):
f.write("{0}\n".format(count[j]))
|
Fix bug in format suffix patterns | from django.conf.urls.defaults import url
from rest_framework.settings import api_settings
def format_suffix_patterns(urlpatterns, suffix_required=False, suffix_kwarg=None):
"""
Supplement existing urlpatterns with corrosponding patterns that also
include a '.format' suffix. Retains urlpattern ordering.
"""
suffix_kwarg = suffix_kwarg or api_settings.FORMAT_SUFFIX_KWARG
suffix_pattern = r'\.(?P<%s>[a-z]+)$' % suffix_kwarg
ret = []
for urlpattern in urlpatterns:
# Form our complementing '.format' urlpattern
regex = urlpattern.regex.pattern.rstrip('$') + suffix_pattern
view = urlpattern._callback or urlpattern._callback_str
kwargs = urlpattern.default_args
name = urlpattern.name
# Add in both the existing and the new urlpattern
if not suffix_required:
ret.append(urlpattern)
ret.append(url(regex, view, kwargs, name))
return ret
| from django.conf.urls.defaults import url
from rest_framework.settings import api_settings
def format_suffix_patterns(urlpatterns, suffix_required=False, suffix_kwarg=None):
"""
Supplement existing urlpatterns with corrosponding patterns that also
include a '.format' suffix. Retains urlpattern ordering.
"""
suffix_kwarg = suffix_kwarg or api_settings.FORMAT_SUFFIX_KWARG
suffix_pattern = '\.(?P<%s>[a-z]+)$' % suffix_kwarg
ret = []
for urlpattern in urlpatterns:
# Form our complementing '.format' urlpattern
regex = urlpattern.regex.pattern.rstrip('$') + suffix_pattern
view = urlpattern._callback or urlpattern._callback_str
kwargs = urlpattern.default_args
name = urlpattern.name
# Add in both the existing and the new urlpattern
if not suffix_required:
ret.append(urlpattern)
ret.append(url(regex, view, kwargs, name))
return ret
|
FIX compilation of node_modules & dist | import { includePaths } from '../config/utils';
export default () => ({
test: /\.(mjs|tsx?|jsx?)$/,
use: [
{
loader: 'babel-loader',
options: {
sourceType: 'unambiguous',
presets: [
['@babel/preset-env', { shippedProposals: true, useBuiltIns: 'usage', corejs: '3' }],
'@babel/preset-typescript',
'@babel/preset-react',
],
plugins: [
['@babel/plugin-proposal-class-properties', { loose: true }],
'@babel/plugin-proposal-export-default-from',
'@babel/plugin-syntax-dynamic-import',
['@babel/plugin-proposal-object-rest-spread', { loose: true, useBuiltIns: true }],
'babel-plugin-macros',
],
},
},
],
include: includePaths,
exclude: [/node_module/, /dist/],
});
| import { includePaths } from '../config/utils';
export default () => ({
test: /\.(mjs|tsx?|jsx?)$/,
use: [
{
loader: 'babel-loader',
options: {
presets: [
['@babel/preset-env', { shippedProposals: true, useBuiltIns: 'usage', corejs: '3' }],
'@babel/preset-typescript',
'@babel/preset-react',
],
plugins: [
['@babel/plugin-proposal-class-properties', { loose: true }],
'@babel/plugin-proposal-export-default-from',
'@babel/plugin-syntax-dynamic-import',
['@babel/plugin-proposal-object-rest-spread', { loose: true, useBuiltIns: true }],
'babel-plugin-macros',
],
},
},
],
include: includePaths,
exclude: /\/node_module\/|\/dist\//,
});
|
Use slate-core-data for people model/proxy | Ext.define('SlateAdmin.store.progress.interims.Students', {
extend: 'Ext.data.Store',
requires: [
'Slate.proxy.Records'
],
model: 'Slate.model.person.Person',
config: {
pageSize: false,
proxy: 'slate-records',
sorters: [
{
property: 'LastName',
direction: 'ASC'
},
{
property: 'FirstName',
direction: 'ASC'
}
]
}
}); | Ext.define('SlateAdmin.store.progress.interims.Students', {
extend: 'Ext.data.Store',
requires: [
'SlateAdmin.proxy.Records'
],
model: 'SlateAdmin.model.person.Person',
config: {
pageSize: false,
proxy: {
type: 'slaterecords'
},
sorters: [
{
property: 'LastName',
direction: 'ASC'
},
{
property: 'FirstName',
direction: 'ASC'
}
]
}
}); |
Revert "temp stop twitter scraping"
This reverts commit 21db824f3b2a544fa38547bb1fd6c6271f861354. | import os
import sys
from .new_news_check import is_new_flash_news
from .news_flash_crawl import news_flash_crawl
from ..mda_twitter.mda_twitter import mda_twitter
# from sys import exit
# import time
def scrap_flash_news(site_name, maps_key):
"""
init scraping for a site
:param site_name: name of the site to scrap
:param maps_key: google maps key path
"""
if site_name == 'ynet':
rss_link = 'https://www.ynet.co.il/Integration/StoryRss1854.xml'
if is_new_flash_news(rss_link):
news_flash_crawl(rss_link, site_name, maps_key)
if site_name == 'twitter':
mda_twitter()
def main(google_maps_key_path):
"""
main function for beginning of the news flash process
:param google_maps_key_path: path to google maps key
"""
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
scrap_flash_news('ynet',google_maps_key_path)
scrap_flash_news('twitter',google_maps_key_path) | import os
import sys
from .new_news_check import is_new_flash_news
from .news_flash_crawl import news_flash_crawl
from ..mda_twitter.mda_twitter import mda_twitter
# from sys import exit
# import time
def scrap_flash_news(site_name, maps_key):
"""
init scraping for a site
:param site_name: name of the site to scrap
:param maps_key: google maps key path
"""
if site_name == 'ynet':
rss_link = 'https://www.ynet.co.il/Integration/StoryRss1854.xml'
if is_new_flash_news(rss_link):
news_flash_crawl(rss_link, site_name, maps_key)
if site_name == 'twitter':
mda_twitter()
def main(google_maps_key_path):
"""
main function for beginning of the news flash process
:param google_maps_key_path: path to google maps key
"""
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
scrap_flash_news('ynet',google_maps_key_path)
#scrap_flash_news('twitter',google_maps_key_path)
|
Resolve race condition with the clock tests | var test = require('tap').test;
var Clock = require('../../src/io/clock');
var Runtime = require('../../src/engine/runtime');
test('spec', function (t) {
var rt = new Runtime();
var c = new Clock(rt);
t.type(Clock, 'function');
t.type(c, 'object');
t.type(c.projectTimer, 'function');
t.type(c.pause, 'function');
t.type(c.resume, 'function');
t.type(c.resetProjectTimer, 'function');
t.end();
});
test('cycle', function (t) {
var rt = new Runtime();
var c = new Clock(rt);
t.ok(c.projectTimer() <= 0.001);
setTimeout(function () {
c.resetProjectTimer();
setTimeout(function () {
t.ok(c.projectTimer() > 0);
c.pause();
t.ok(c.projectTimer() > 0);
c.resume();
t.ok(c.projectTimer() > 0);
t.end();
}, 100);
}, 100);
});
| var test = require('tap').test;
var Clock = require('../../src/io/clock');
var Runtime = require('../../src/engine/runtime');
test('spec', function (t) {
var rt = new Runtime();
var c = new Clock(rt);
t.type(Clock, 'function');
t.type(c, 'object');
t.type(c.projectTimer, 'function');
t.type(c.pause, 'function');
t.type(c.resume, 'function');
t.type(c.resetProjectTimer, 'function');
t.end();
});
test('cycle', function (t) {
var rt = new Runtime();
var c = new Clock(rt);
t.strictEqual(c.projectTimer(), 0);
setTimeout(function () {
c.resetProjectTimer();
setTimeout(function () {
t.ok(c.projectTimer() > 0);
c.pause();
t.ok(c.projectTimer() > 0);
c.resume();
t.ok(c.projectTimer() > 0);
t.end();
}, 100);
}, 100);
});
|
Stop button should only stop. | chrome.runtime.onMessage.addListener( function(request, sender, sendResponse){
var click_event = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true
});
switch(request.action){
case 'NEXT-MK':
document.getElementsByClassName('control-next')[0].dispatchEvent(click_event);
break;
case 'PREV-MK':
document.getElementsByClassName('control-prev')[0].dispatchEvent(click_event);
break;
case 'STOP-MK':
if ( document.getElementsByClassName('control-pause').length > 0 )
document.getElementsByClassName('control-pause')[0].dispatchEvent(click_event);
case 'PLAY-PAUSE-MK':
if ( document.getElementsByClassName('control-play').length > 0 )
document.getElementsByClassName('control-play')[0].dispatchEvent(click_event);
else
document.getElementsByClassName('control-pause')[0].dispatchEvent(click_event);
break;
}
}); | chrome.runtime.onMessage.addListener( function(request, sender, sendResponse){
var click_event = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true
});
switch(request.action){
case 'NEXT-MK':
document.getElementsByClassName('control-next')[0].dispatchEvent(click_event);
break;
case 'PREV-MK':
document.getElementsByClassName('control-prev')[0].dispatchEvent(click_event);
break;
case 'PLAY-PAUSE-MK':
case 'STOP-MK':
if ( document.getElementsByClassName('control-play').length > 0 )
document.getElementsByClassName('control-play')[0].dispatchEvent(click_event);
else
document.getElementsByClassName('control-pause')[0].dispatchEvent(click_event);
break;
}
}); |
Disable flaky dataExport e2e test | const config = require('config')
describe('/#/privacy-security/data-export', () => {
xdescribe('challenge "dataExportChallenge"', () => {
beforeEach(() => {
browser.get('/#/register')
element(by.id('emailControl')).sendKeys('admun@' + config.get('application.domain'))
element(by.id('passwordControl')).sendKeys('admun123')
element(by.id('repeatPasswordControl')).sendKeys('admun123')
element(by.name('securityQuestion')).click()
element.all(by.cssContainingText('mat-option', 'Your eldest siblings middle name?')).click()
element(by.id('securityAnswerControl')).sendKeys('admun')
element(by.id('registerButton')).click()
})
protractor.beforeEach.login({ email: 'admun@' + config.get('application.domain'), password: 'admun123' })
it('should be possible to steal admin user data by causing email clash during export', () => {
browser.get('/#/privacy-security/data-export')
element(by.id('formatControl')).all(by.tagName('mat-radio-button')).get(0).click()
element(by.id('submitButton')).click()
})
protractor.expect.challengeSolved({ challenge: 'GDPR Compliance Tier 2' })
})
})
| const config = require('config')
describe('/#/privacy-security/data-export', () => {
describe('challenge "dataExportChallenge"', () => {
beforeEach(() => {
browser.get('/#/register')
element(by.id('emailControl')).sendKeys('admun@' + config.get('application.domain'))
element(by.id('passwordControl')).sendKeys('admun123')
element(by.id('repeatPasswordControl')).sendKeys('admun123')
element(by.name('securityQuestion')).click()
element.all(by.cssContainingText('mat-option', 'Your eldest siblings middle name?')).click()
element(by.id('securityAnswerControl')).sendKeys('admun')
element(by.id('registerButton')).click()
})
protractor.beforeEach.login({ email: 'admun@' + config.get('application.domain'), password: 'admun123' })
it('should be possible to steal admin user data by causing email clash during export', () => {
browser.get('/#/privacy-security/data-export')
element(by.id('formatControl')).all(by.tagName('mat-radio-button')).get(0).click()
element(by.id('submitButton')).click()
})
protractor.expect.challengeSolved({ challenge: 'GDPR Compliance Tier 2' })
})
})
|
Fix resizing issues with iframed pages | import React, { Component } from 'react'
import Helmet from 'react-helmet'
import { NavBar } from '../../components'
const styles = {
iframe: {
width: '100%',
}
}
class TeamPage extends Component {
componentDidMount() {
var iframe = this.refs.iframe
window.addEventListener('resize', () => {
var iframeScrollHeight = iframe.contentWindow.document.body.scrollHeight + 'px'
iframe.height = iframeScrollHeight
})
iframe.addEventListener('load', () => {
var iframeScrollHeight = iframe.contentWindow.document.body.scrollHeight + 'px'
iframe.height = iframeScrollHeight
})
}
render() {
return(
<div>
<Helmet title="Team" />
<NavBar />
<iframe ref="iframe" style={styles.iframe} src="/staticPage/team/index.html" />
</div>
)
}
}
export default TeamPage
| import React, { Component } from 'react'
import Helmet from 'react-helmet'
import { NavBar } from '../../components'
const styles = {
iframe: {
width: '100%',
}
}
class TeamPage extends Component {
componentDidMount() {
var iframe = this.refs.iframe
iframe.addEventListener('load', () => {
var iframeScrollHeight = iframe.contentWindow.document.body.scrollHeight + 'px'
iframe.height = iframeScrollHeight
})
}
render() {
return(
<div>
<Helmet title="Team" />
<NavBar />
<iframe ref="iframe" style={styles.iframe} src="/staticPage/team/index.html" />
</div>
)
}
}
export default TeamPage
|
Fix TabStore to ensure that an object is always loaded | (function (h) {
'use strict';
/* The tab store ensures that the current state of the browser action
* is persisted between browser sessions. To do this it uses an external
* storage object that conforms to the localStorage API.
*
* Examples
*
* var store = new TabStore(window.localStorage);
*/
function TabStore(storage) {
var key = 'state';
var local;
this.get = function (tabId) {
var value = local[tabId];
if (!value) {
throw new Error('TabStateStore could not find entry for tab: ' + tabId);
}
return value;
};
this.set = function (tabId, value) {
local[tabId] = value;
storage.setItem(key, JSON.stringify(local));
};
this.unset = function (tabId) {
delete local[tabId];
storage.setItem(key, JSON.stringify(local));
};
this.all = function () {
return local;
};
this.reload = function () {
try {
local = JSON.parse(storage.getItem(key));
} catch (e) {
local = null;
}
local = local || {};
};
this.reload();
}
h.TabStore = TabStore;
})(window.h || (window.h = {}));
| (function (h) {
'use strict';
/* The tab store ensures that the current state of the browser action
* is persisted between browser sessions. To do this it uses an external
* storage object that conforms to the localStorage API.
*
* Examples
*
* var store = new TabStore(window.localStorage);
*/
function TabStore(storage) {
var key = 'state';
var local;
this.get = function (tabId) {
var value = local[tabId];
if (!value) {
throw new Error('TabStateStore could not find entry for tab: ' + tabId);
}
return value;
};
this.set = function (tabId, value) {
local[tabId] = value;
storage.setItem(key, JSON.stringify(local));
};
this.unset = function (tabId) {
delete local[tabId];
storage.setItem(key, JSON.stringify(local));
};
this.all = function () {
return local;
};
this.reload = function () {
try {
local = JSON.parse(storage.getItem(key));
} catch (e) {
local = {};
}
};
this.reload();
}
h.TabStore = TabStore;
})(window.h || (window.h = {}));
|
Add a print when running pulseaudio | #!/usr/bin/env python3
import bot as chat_bot
from intercom import Intercom
import logging
from facerecognition import FaceRecognition
import nodered
import subprocess
from sys import platform
icom = Intercom()
facerec = FaceRecognition()
doorBellServer = nodered.NodeRedDoorbellServerThread(icom)
doorBellServer.start()
if platform == "linux" or platform == "linux2":
# linux
print("Starting PulseAudio")
subprocess.call(["pulseaudio", "-D"])
def onBellPressed():
if chat_bot.chat_id is None:
logging.warning('Bell is pressed but we have no user in the chat')
chat_bot.verify_image(chat_bot.updater, icom.takePicture())
def onTakeSnap():
pic = icom.takePicture()
chat_bot.uploadSnap(chat_bot.updater, pic)
icom.registerOnBellPressedCallback(onBellPressed)
chat_bot.registerOnSnapButtonCallback(onTakeSnap)
chat_bot.run_bot()
| #!/usr/bin/env python3
import bot as chat_bot
from intercom import Intercom
import logging
from facerecognition import FaceRecognition
import nodered
import subprocess
from sys import platform
icom = Intercom()
facerec = FaceRecognition()
doorBellServer = nodered.NodeRedDoorbellServerThread(icom)
doorBellServer.start()
if platform == "linux" or platform == "linux2":
# linux
subprocess.call(["pulseaudio", "-D"])
def onBellPressed():
if chat_bot.chat_id is None:
logging.warning('Bell is pressed but we have no user in the chat')
chat_bot.verify_image(chat_bot.updater, icom.takePicture())
def onTakeSnap():
pic = icom.takePicture()
chat_bot.uploadSnap(chat_bot.updater, pic)
icom.registerOnBellPressedCallback(onBellPressed)
chat_bot.registerOnSnapButtonCallback(onTakeSnap)
chat_bot.run_bot()
|
Use babel polyfill on frontend | import '@babel/polyfill';
import React from 'react';
import { AppContainer } from 'react-hot-loader';
import { render } from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import store from './store';
import Root from '~client/containers/Root';
import './images/favicon.png';
function renderApp(RootComponent = Root) {
render(
<AppContainer>
<BrowserRouter>
<RootComponent store={store} />
</BrowserRouter>
</AppContainer>,
document.getElementById('root'),
);
}
if (process.env.NODE_ENV !== 'test') {
renderApp();
}
if (module.hot) {
module.hot.accept(
'./containers/Root',
// eslint-disable-next-line global-require
() => renderApp(require('./containers/Root').default),
);
}
| /**
* Main entry point for budget web app
*/
import React from 'react';
import { AppContainer } from 'react-hot-loader';
import { render } from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import store from './store';
import Root from '~client/containers/Root';
import './images/favicon.png';
function renderApp(RootComponent = Root) {
render(
<AppContainer>
<BrowserRouter>
<RootComponent store={store} />
</BrowserRouter>
</AppContainer>,
document.getElementById('root'),
);
}
if (process.env.NODE_ENV !== 'test') {
renderApp();
}
if (module.hot) {
module.hot.accept(
'./containers/Root',
// eslint-disable-next-line global-require
() => renderApp(require('./containers/Root').default),
);
}
|
Fix oreientation bug causing levers not being able to place. | package net.minecraftforge.common;
public enum Orientation
{
/** -Y */
DOWN,
/** +Y */
UP,
/** -Z */
NORTH,
/** +Z */
SOUTH,
/** -X */
WEST,
/** +X */
EAST,
/**
* Used only by getOrientation, for invalid inputs
*/
UNKNOWN;
public static Orientation getOrientation(int id)
{
if (id < Orientation.values().length)
{
return Orientation.values()[id];
}
return UNKNOWN;
}
}
| package net.minecraftforge.common;
public enum Orientation
{
/** -Y */
DOWN,
/** +Y */
UP,
/** -Z */
NORTH,
/** +Z */
SOUTH,
/** -X */
WEST,
/** +X */
EAST,
/**
* Used only by getOrientation, for invalid inputs
*/
UNKNOWN;
public static Orientation getOrientation(int id)
{
if (Orientation.values().length < id)
{
return Orientation.values()[id];
}
return UNKNOWN;
}
}
|
Refactor emit action into its own method | var LogEmitter = function (source) {
this.source = source;
};
LogEmitter.prototype.info = function (message) {
this.emit({ level: "info", message: message, source: this.source });
};
LogEmitter.prototype.warn = function (message) {
this.emit({ level: "warn", message: message, source: this.source });
};
LogEmitter.prototype.error = function (message) {
var data = {
level: "error",
message: message,
source: this.source
};
if (message instanceof Error) {
data.message = message.message;
data.error = message;
}
this.emit(data);
};
LogEmitter.prototype.debug = function (message) {
this.emit({ level: "debug", message: message, source: this.source });
};
LogEmitter.prototype.emit = function (data) {
process.emit("gulp:log", data);
};
module.exports = {
Logger: function (source) {
return new LogEmitter(source);
}
};
// var log = require('gulp-logemitter').Logger('my plugin');
// log.info("This is something to say"); | var LogEmitter = function (source) {
this.source = source;
};
LogEmitter.prototype.info = function (message) {
process.emit("gulp:log", { level: "info", message: message, source: this.source });
};
LogEmitter.prototype.warn = function (message) {
process.emit("gulp:log", { level: "warn", message: message, source: this.source });
};
LogEmitter.prototype.error = function (message) {
var data = {
level: "error",
message: message,
source: this.source
};
if (message instanceof Error) {
data.message = message.message;
data.error = message;
}
process.emit("gulp:log", data);
};
LogEmitter.prototype.debug = function (message) {
process.emit("gulp:log", { level: "debug", message: message, source: this.source });
};
module.exports = {
Logger: function (source) {
return new LogEmitter(source);
}
};
// var log = require('gulp-logemitter').Logger('my plugin');
// log.info("This is something to say"); |
Use hypothesis setting load_profile to setup health check
Fixes #779 | '''
General-purpose fixtures for vdirsyncer's testsuite.
'''
import logging
import os
import click_log
from hypothesis import HealthCheck, Verbosity, settings
import pytest
@pytest.fixture(autouse=True)
def setup_logging():
click_log.basic_config('vdirsyncer').setLevel(logging.DEBUG)
try:
import pytest_benchmark
except ImportError:
@pytest.fixture
def benchmark():
return lambda x: x()
else:
del pytest_benchmark
settings.register_profile("ci", settings(
max_examples=1000,
verbosity=Verbosity.verbose,
suppress_health_check=[HealthCheck.too_slow],
))
settings.register_profile("deterministic", settings(
derandomize=True,
suppress_health_check=HealthCheck.all(),
))
settings.register_profile("dev", settings(
suppress_health_check=[HealthCheck.too_slow]
))
if os.environ.get('DETERMINISTIC_TESTS', 'false').lower() == 'true':
settings.load_profile("deterministic")
elif os.environ.get('CI', 'false').lower() == 'true':
settings.load_profile("ci")
else:
settings.load_profile("dev")
| '''
General-purpose fixtures for vdirsyncer's testsuite.
'''
import logging
import os
import click_log
from hypothesis import HealthCheck, Verbosity, settings
import pytest
@pytest.fixture(autouse=True)
def setup_logging():
click_log.basic_config('vdirsyncer').setLevel(logging.DEBUG)
try:
import pytest_benchmark
except ImportError:
@pytest.fixture
def benchmark():
return lambda x: x()
else:
del pytest_benchmark
settings.register_profile("ci", settings(
max_examples=1000,
verbosity=Verbosity.verbose,
suppress_health_check=[HealthCheck.too_slow],
))
settings.register_profile("deterministic", settings(
derandomize=True,
suppress_health_check=HealthCheck.all(),
))
if os.environ.get('DETERMINISTIC_TESTS', 'false').lower() == 'true':
settings.load_profile("deterministic")
elif os.environ.get('CI', 'false').lower() == 'true':
settings.load_profile("ci")
|
Fix string formatting for NotRegistered exception | import logging
from django.conf import settings
from django.utils.importlib import import_module
__all__ = ('events', 'register', 'unregister')
logger = logging.getLogger('webhooks')
class AlreadyRegistered(Exception):
pass
class NotRegistered(Exception):
pass
class Events(dict):
def register(self, event, handler):
if event in self:
raise AlreadyRegistered('handler {0} already registered for event {1}'.format(handler, event))
self[event] = handler
def unregister(self, event):
if event not in self:
raise NotRegistered('event {0} not registered'.format(event))
del self[event]
events = Events()
register = events.register
unregister = events.unregister
# Autodiscover apps for webhook handlers. Modules can import webhooks and
# and do webhooks.register.
for app in settings.INSTALLED_APPS:
module_path = '{0}.{1}'.format(app, 'webhooks')
try:
import_module(module_path)
except Exception as e:
logger.debug('failed to import module', extra={
'module_path': module_path,
'error': repr(e),
})
| import logging
from django.conf import settings
from django.utils.importlib import import_module
__all__ = ('events', 'register', 'unregister')
logger = logging.getLogger('webhooks')
class AlreadyRegistered(Exception):
pass
class NotRegistered(Exception):
pass
class Events(dict):
def register(self, event, handler):
if event in self:
raise AlreadyRegistered('handler {0} already registered for event {1}'.format(handler, event))
self[event] = handler
def unregister(self, event):
if event not in self:
raise NotRegistered('event {0} not registered')
del self[event]
events = Events()
register = events.register
unregister = events.unregister
# Autodiscover apps for webhook handlers. Modules can import webhooks and
# and do webhooks.register.
for app in settings.INSTALLED_APPS:
module_path = '{0}.{1}'.format(app, 'webhooks')
try:
import_module(module_path)
except Exception as e:
logger.debug('failed to import module', extra={
'module_path': module_path,
'error': repr(e),
})
|
Upgrade hvac to have latest fix on the consul secret engine
Signed-off-by: Damien Goldenberg <153f528c345216f3d6a78cf62c6dd7299da883e1@gmail.com> | #!/usr/bin/env python
from setuptools import setup
py_files = [
"ansible/module_utils/hashivault",
"ansible/plugins/lookup/hashivault",
"ansible/plugins/action/hashivault_read_to_file",
"ansible/plugins/action/hashivault_write_from_file",
]
files = [
"ansible/modules/hashivault",
]
long_description = open('README.rst', 'r').read()
setup(
name='ansible-modules-hashivault',
version='4.0.0',
description='Ansible Modules for Hashicorp Vault',
long_description=long_description,
long_description_content_type='text/x-rst',
author='Terry Howe',
author_email='terrylhowe@example.com',
url='https://github.com/TerryHowe/ansible-modules-hashivault',
py_modules=py_files,
packages=files,
install_requires=[
'ansible>=2.0.0',
'hvac>=0.9.5',
'requests',
],
)
| #!/usr/bin/env python
from setuptools import setup
py_files = [
"ansible/module_utils/hashivault",
"ansible/plugins/lookup/hashivault",
"ansible/plugins/action/hashivault_read_to_file",
"ansible/plugins/action/hashivault_write_from_file",
]
files = [
"ansible/modules/hashivault",
]
long_description = open('README.rst', 'r').read()
setup(
name='ansible-modules-hashivault',
version='4.0.0',
description='Ansible Modules for Hashicorp Vault',
long_description=long_description,
long_description_content_type='text/x-rst',
author='Terry Howe',
author_email='terrylhowe@example.com',
url='https://github.com/TerryHowe/ansible-modules-hashivault',
py_modules=py_files,
packages=files,
install_requires=[
'ansible>=2.0.0',
'hvac>=0.9.2',
'requests',
],
)
|
Implement rounds in Sha512Sum func | package codeutilsShared
import (
"crypto/sha512"
"encoding/hex"
"os"
)
// GlobalFileMode as a file mode we'll use for "global" operations such as when doing IO as root
var GlobalFileMode os.FileMode
// UniversalFileMode as a file mode we'll wherever we can
var UniversalFileMode os.FileMode
func init() {
GlobalFileMode = 0777 // Set to global read/write/executable
UniversalFileMode = 0744 // Only read/write/executable by owner, readable by group and others
}
// Sha512Sum will create a sha512sum of the string
func Sha512Sum(content string, rounds int) string {
var hashString string
sha512Hasher := sha512.New() // Create a new Hash struct
sha512Hasher.Write([]byte(content)) // Write the byte array of the content
hashString = hex.EncodeToString(sha512Hasher.Sum(nil)) // Return string encoded sum of sha512sum
if (rounds != 0) && (rounds > 1) { // If we are cycling more than one rounds
for currentRound := 0; currentRound < rounds; currentRound++ {
hashString = Sha512Sum(hashString, 1) // Rehash the new hashString
}
}
return hashString
}
| package codeutilsShared
import (
"crypto/sha512"
"encoding/hex"
"os"
)
// GlobalFileMode as a file mode we'll use for "global" operations such as when doing IO as root
var GlobalFileMode os.FileMode
// UniversalFileMode as a file mode we'll wherever we can
var UniversalFileMode os.FileMode
func init() {
GlobalFileMode = 0777 // Set to global read/write/executable
UniversalFileMode = 0744 // Only read/write/executable by owner, readable by group and others
}
// Sha512Sum will create a sha512sum of the string
func Sha512Sum(content string) string {
sha512Hasher := sha512.New() // Create a new Hash struct
sha512Hasher.Write([]byte(content)) // Write the byte array of the content
return hex.EncodeToString(sha512Hasher.Sum(nil)) // Return string encoded sum of sha512sum
}
|
Use onewWay instead of readOnly | import Ember from 'ember';
import Qs from 'qs';
const { computed } = Ember;
export default Ember.Component.extend({
tagName: '',
parsedURL: computed('url', function() {
const link = document.createElement('a');
link.href = this.get('url');
return link;
}),
id: computed('parsedURL', function() {
return this.get('parsedURL.pathname')
.split('/')
.reject(part => !part)
.get('lastObject');
}),
blockID: computed.oneWay('query.block'),
filter: computed.oneWay('query.filter'),
query: computed('parsedURL', function() {
return Qs.parse(this.get('parsedURL.search').slice(1));
})
});
| import Ember from 'ember';
import Qs from 'qs';
const { computed } = Ember;
export default Ember.Component.extend({
tagName: '',
parsedURL: computed('url', function() {
const link = document.createElement('a');
link.href = this.get('url');
return link;
}),
id: computed('parsedURL', function() {
return this.get('parsedURL.pathname')
.split('/')
.reject(part => !part)
.get('lastObject');
}),
blockID: computed.readOnly('query.block'),
filter: computed.readOnly('query.filter'),
query: computed('parsedURL', function() {
return Qs.parse(this.get('parsedURL.search').slice(1));
})
});
|
Remove duplication, reuse the universes knowledge. | import assert from 'assert';
describe('test setup works?', function() {
it('i hope', function() {
assert.equal(1, 1);
});
});
function tick() {
return {};
}
describe('universe', function() {
describe('next generation', function() {
it('of empty universe is empty', function() {
let universe = {
};
let nextGeneration = tick();
assert.deepEqual(nextGeneration, {});
});
it('of one cell is empty', function() {
let universe = {
pos1: {}
};
let nextGeneration = tick();
assert.deepEqual(nextGeneration, {});
});
it('of three diagonal cells contains middle cell', function() {
let universe = {
pos1: {x: 1, y: 1},
pos2: { x:0, y:0 },
pos3: { x:2, y:2 }
};
let nextGeneration = {pos1: universe.pos1};
assert.deepEqual(nextGeneration, {pos1: {x: 1, y: 1}});
});
});
}); | import assert from 'assert';
describe('test setup works?', function() {
it('i hope', function() {
assert.equal(1, 1);
});
});
function tick() {
return {};
}
describe('universe', function() {
describe('next generation', function() {
it('of empty universe is empty', function() {
let universe = {
};
let nextGeneration = tick();
assert.deepEqual(nextGeneration, {});
});
it('of one cell is empty', function() {
let universe = {
pos1: {}
};
let nextGeneration = tick();
assert.deepEqual(nextGeneration, {});
});
it('of three diagonal cells contains middle cell', function() {
let universe = {
pos1: { x:1, y:1 },
pos2: { x:0, y:0 },
pos3: { x:2, y:2}
};
let nextGeneration = {pos1: {x: 1, y: 1}};
assert.deepEqual(nextGeneration, {
pos1: {x: 1, y: 1}
});
});
});
}); |
Fix index check in `removeDefaultCapability`. | import Oasis from "oasis";
import { services } from "conductor/services";
import { copy } from "conductor/lang";
import { a_indexOf } from "oasis/shims";
function ConductorCapabilities() {
this.capabilities = [
'xhr', 'metadata', 'render', 'data', 'lifecycle', 'height',
'nestedWiretapping' ];
this.services = copy(services);
}
ConductorCapabilities.prototype = {
defaultCapabilities: function () {
return this.capabilities;
},
defaultServices: function () {
return this.services;
},
addDefaultCapability: function (capability, service) {
if (!service) { service = Oasis.Service; }
this.capabilities.push(capability);
this.services[capability] = service;
},
removeDefaultCapability: function (capability) {
var index = a_indexOf.call(this.capabilities, capability);
if (index !== -1) {
return this.capabilities.splice(index, 1);
}
}
};
export default ConductorCapabilities;
| import Oasis from "oasis";
import { services } from "conductor/services";
import { copy } from "conductor/lang";
import { a_indexOf } from "oasis/shims";
function ConductorCapabilities() {
this.capabilities = [
'xhr', 'metadata', 'render', 'data', 'lifecycle', 'height',
'nestedWiretapping' ];
this.services = copy(services);
}
ConductorCapabilities.prototype = {
defaultCapabilities: function () {
return this.capabilities;
},
defaultServices: function () {
return this.services;
},
addDefaultCapability: function (capability, service) {
if (!service) { service = Oasis.Service; }
this.capabilities.push(capability);
this.services[capability] = service;
},
removeDefaultCapability: function (capability) {
var index = a_indexOf.call(this.capabilities, capability);
if (index) {
return this.capabilities.splice(index, 1);
}
}
};
export default ConductorCapabilities;
|
Add TODO to remove console.log from non-dump functions | var Util = require('util');
var Packet = require('../packet');
var capture = require('../capture');
module.exports = function(options) {
var self = this; // ZongJi instance
var Sequence = capture(self.connection).Sequence;
var BinlogHeader = Packet.initBinlogHeader.call(self, options);
function Binlog(callback) {
Sequence.call(this, callback);
}
Util.inherits(Binlog, Sequence);
Binlog.prototype.start = function() {
this.emit('packet', new Packet.ComBinlog(options));
};
Binlog.prototype.determinePacket = function(firstByte) {
switch (firstByte) {
case 0xfe:
return Packet.Eof;
case 0xff:
return Packet.Error;
default:
return BinlogHeader;
}
};
Binlog.prototype['OkPacket'] = function(packet) {
// TODO: Remove console statements to make module ready for widespread use
console.log('Received one OkPacket ...');
};
Binlog.prototype['BinlogHeader'] = function(packet) {
if (this._callback) {
var event, error;
try{
event = packet.getEvent();
}catch(err){
error = err;
}
this._callback.call(this, error, event);
}
};
return Binlog;
};
| var Util = require('util');
var Packet = require('../packet');
var capture = require('../capture');
module.exports = function(options) {
var self = this; // ZongJi instance
var Sequence = capture(self.connection).Sequence;
var BinlogHeader = Packet.initBinlogHeader.call(self, options);
function Binlog(callback) {
Sequence.call(this, callback);
}
Util.inherits(Binlog, Sequence);
Binlog.prototype.start = function() {
this.emit('packet', new Packet.ComBinlog(options));
};
Binlog.prototype.determinePacket = function(firstByte) {
switch (firstByte) {
case 0xfe:
return Packet.Eof;
case 0xff:
return Packet.Error;
default:
return BinlogHeader;
}
};
Binlog.prototype['OkPacket'] = function(packet) {
console.log('Received one OkPacket ...');
};
Binlog.prototype['BinlogHeader'] = function(packet) {
if (this._callback) {
var event, error;
try{
event = packet.getEvent();
}catch(err){
error = err;
}
this._callback.call(this, error, event);
}
};
return Binlog;
};
|
Fix the presence validator test | describe('validator.presence', function() {
var presence = validate.validators.presence;
it("doesn't allow empty values", function() {
expect(presence('', {})).toBeDefined();
expect(presence(' ', {})).toBeDefined();
expect(presence(null, {})).toBeDefined();
expect(presence(undefined, {})).toBeDefined();
expect(presence([], {})).toBeDefined();
expect(presence({}, {})).toBeDefined();
});
it("allows non empty values", function() {
expect(presence('foo', {})).not.toBeDefined();
expect(presence(0, {})).not.toBeDefined();
expect(presence(false, {})).not.toBeDefined();
expect(presence([null], {})).not.toBeDefined();
expect(presence({foo: null}, {})).not.toBeDefined();
expect(presence(function(){return null;}, {})).not.toBeDefined();
});
it("has a nice default message", function() {
var msg = presence(null, {});
expect(msg).toEqual("can't be blank");
});
it("also allows to specify your own nice message", function() {
var options = {message: "my message"};
var msg = presence(null, options);
expect(msg).toEqual(options.message);
});
});
| describe('validator.presence', function() {
var presence = validate.validators.presence;
it("doesn't allow empty values", function() {
expect(presence('', {})).toBeDefined();
expect(presence(' ', {})).toBeDefined();
expect(presence(null, {})).toBeDefined();
expect(presence(undefined, {})).toBeDefined();
expect(presence([], {})).toBeDefined();
expect(presence({}, {})).toBeDefined();
});
it("allows non empty values", function() {
expect(presence('foo', {})).not.toBeDefined();
expect(presence(0, {})).not.toBeDefined();
expect(presence(false, {})).not.toBeDefined();
expect(presence([null], {})).not.toBeDefined();
expect(presence({foo: null}, {})).not.toBeDefined();
expect(presence({foo: function(){return null;}}, {})).not.toBeDefined();
});
it("has a nice default message", function() {
var msg = presence(null, {});
expect(msg).toEqual("can't be blank");
});
it("also allows to specify your own nice message", function() {
var options = {message: "my message"};
var msg = presence(null, options);
expect(msg).toEqual(options.message);
});
});
|
Add globals to build output | var filterES6Modules = require('broccoli-es6-module-filter'),
concat = require('broccoli-concat'),
pkg = require('./package');
module.exports = function(broccoli) {
var global = 'Ember',
namespace = 'DeviseSimpleAuth';
var appTree = broccoli.makeTree('app'),
configTree = broccoli.makeTree('config');
var amdTree = filterES6Modules(appTree, {
moduleType: 'amd',
main: 'index',
packageName: 'app',
anonymous: false
});
var pluginTree = filterES6Modules(configTree, {
moduleType: 'amd',
main: 'plugin',
packageName: pkg.name,
anonymous: false
});
var globalTree = filterES6Modules(new broccoli.MergedTree([appTree, configTree]), {
moduleType: 'globals',
global: global,
namespace: namespace,
anonymous: false
});
globalTree = concat(globalTree, {
inputFiles: ['**/*.js'],
outputFile: '/globals/index.js'
});
amdTree = concat(new broccoli.MergedTree([amdTree, pluginTree]), {
inputFiles: ['**/*.js'],
outputFile: '/appkit/index.js'
});
return [globalTree, amdTree];
};
| var filterES6Modules = require('broccoli-es6-module-filter'),
concat = require('broccoli-concat'),
pkg = require('./package');
module.exports = function(broccoli) {
var global = 'Ember',
namespace = 'DeviseSimpleAuth';
var appTree = broccoli.makeTree('app'),
configTree = broccoli.makeTree('config');
var amdTree = filterES6Modules(appTree, {
moduleType: 'amd',
main: 'index',
packageName: 'app',
anonymous: false
});
var pluginTree = filterES6Modules(configTree, {
moduleType: 'amd',
main: 'plugin',
packageName: pkg.name,
anonymous: false
});
return concat(new broccoli.MergedTree([amdTree, pluginTree]), {
inputFiles: ['**/*.js'],
outputFile: '/index.js'
});
};
|
Make sure to close the file afterwards | import web
import cPickle as pickle
import json
urls = (
'/latest', 'latest',
'/history', 'history'
)
class latest:
def GET(self):
try:
with open("latest.p", 'r') as f:
latest = pickle.load(f)
return json.dumps(latest)
except:
return "Could not read latest data"
class history:
def GET(self):
try:
with open("history.p", 'r') as f:
history = pickle.load(f)
return json.dumps(history)
except:
return "Could not read historic data"
if __name__ == "__main__":
app = web.application(urls, globals())
app.run()
| import web
import cPickle as pickle
import json
urls = (
'/latest', 'latest',
'/history', 'history'
)
class latest:
def GET(self):
try:
latest = pickle.load(open("latest.p", "r"))
return json.dumps(latest)
except:
return "Could not read latest data"
class history:
def GET(self):
try:
history = pickle.load(open("history.p", "r"))
return json.dumps(history)
except:
return "Could not read historic data"
if __name__ == "__main__":
app = web.application(urls, globals())
app.run()
|
Allow { unused, ...rest } in ESLint rules | module.exports = {
"parser": "babel-eslint",
"env": {
"browser": true,
"jest": true,
"node": true,
"es6": true
},
"extends": ["eslint:recommended", "plugin:react/recommended"],
"parserOptions": {
"ecmaFeatures": {
"experimentalObjectRestSpread": true,
"jsx": true
},
"sourceType": "module"
},
"plugins": [
"react", "flowtype"
],
"settings": {
"react": {
"version": "16.5",
"flowVersion": "0.81"
}
},
"rules": {
"flowtype/define-flow-type": 1,
"flowtype/require-valid-file-annotation": ["error", "always"],
"indent": ["error", 2],
"linebreak-style": ["error", "unix"],
"quotes": ["error", "single", "avoid-escape"],
"semi": ["error", "always"],
"no-var": ["error"],
"brace-style": ["error"],
"array-bracket-spacing": ["error", "never"],
"block-spacing": ["error", "always"],
"no-spaced-func": ["error"],
"no-whitespace-before-property": ["error"],
"space-before-blocks": ["error", "always"],
"keyword-spacing": ["error"],
"no-unused-vars": ["error", {"args": "none", "ignoreRestSiblings": true}]
}
};
| module.exports = {
"parser": "babel-eslint",
"env": {
"browser": true,
"jest": true,
"node": true,
"es6": true
},
"extends": ["eslint:recommended", "plugin:react/recommended"],
"parserOptions": {
"ecmaFeatures": {
"experimentalObjectRestSpread": true,
"jsx": true
},
"sourceType": "module"
},
"plugins": [
"react", "flowtype"
],
"settings": {
"react": {
"version": "16.5",
"flowVersion": "0.81"
}
},
"rules": {
"flowtype/define-flow-type": 1,
"flowtype/require-valid-file-annotation": ["error", "always"],
"indent": ["error", 2],
"linebreak-style": ["error", "unix"],
"quotes": ["error", "single", "avoid-escape"],
"semi": ["error", "always"],
"no-var": ["error"],
"brace-style": ["error"],
"array-bracket-spacing": ["error", "never"],
"block-spacing": ["error", "always"],
"no-spaced-func": ["error"],
"no-whitespace-before-property": ["error"],
"space-before-blocks": ["error", "always"],
"keyword-spacing": ["error"],
"no-unused-vars": ["error", {"args": "none"}]
}
};
|
Revert discovery images used to the 3.13.0-32-generic kernel | // Copyright 2015, EMC, Inc.
module.exports = {
friendlyName: 'Bootstrap Ubuntu',
injectableName: 'Task.Linux.Bootstrap.Ubuntu',
implementsTask: 'Task.Base.Linux.Bootstrap',
options: {
kernelFile: 'vmlinuz-3.13.0-32-generic',
initrdFile: 'initrd.img-3.13.0-32-generic',
kernelUri: '{{ api.server }}/common/{{ options.kernelFile }}',
initrdUri: '{{ api.server }}/common/{{ options.initrdFile }}',
basefs: 'common/base.trusty.3.13.0-32-generic.squashfs.img.tiny',
overlayfs: 'common/discovery.overlay.cpio.gz.tiny',
profile: 'linux.ipxe',
comport: 'ttyS0'
},
properties: {
os: {
linux: {
distribution: 'ubuntu',
release: 'trusty',
kernel: '3.13.0-32-generic'
}
}
}
};
| // Copyright 2015, EMC, Inc.
module.exports = {
friendlyName: 'Bootstrap Ubuntu',
injectableName: 'Task.Linux.Bootstrap.Ubuntu',
implementsTask: 'Task.Base.Linux.Bootstrap',
options: {
kernelFile: 'vmlinuz-3.16.0-25-generic',
initrdFile: 'initrd.img-3.16.0-25-generic',
kernelUri: '{{ api.server }}/common/{{ options.kernelFile }}',
initrdUri: '{{ api.server }}/common/{{ options.initrdFile }}',
basefs: 'common/base.trusty.3.16.0-25-generic.squashfs.img',
overlayfs: 'common/discovery.overlay.cpio.gz',
profile: 'linux.ipxe',
comport: 'ttyS0'
},
properties: {
os: {
linux: {
distribution: 'ubuntu',
release: 'trusty',
kernel: '3.16.0-25-generic'
}
}
}
};
|
Put the session factory in threadLocal, not the session | """
Interact with your school website with telegram!
Copyright (c) 2016-2017 Paolo Barbolini <paolo@paolo565.org>
Released under the MIT license
"""
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
import threading
# Temporary logging
"""
import logging
logging.basicConfig()
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
"""
threadLocal = threading.local()
class Database:
def __init__(self, config):
self.config = config
def Session(self):
engine = getattr(threadLocal, "engine", None)
if engine is None:
threadLocal.engine = create_engine(self.config["database_url"])
session_factory = getattr(threadLocal, "session_factory", None)
if session_factory is None:
session_factory = sessionmaker(bind=threadLocal.engine)
threadLocal.session_factory = session_factory
return session_factory()
| """
Interact with your school website with telegram!
Copyright (c) 2016-2017 Paolo Barbolini <paolo@paolo565.org>
Released under the MIT license
"""
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
import threading
# Temporary logging
"""
import logging
logging.basicConfig()
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
"""
threadLocal = threading.local()
class Database:
def __init__(self, config):
self.config = config
def Session(self):
engine = getattr(threadLocal, "engine", None)
if engine is None:
threadLocal.engine = create_engine(self.config["database_url"])
session = getattr(threadLocal, "session", None)
if session is None:
session_factory = sessionmaker(bind=threadLocal.engine)
threadLocal.session = scoped_session(session_factory)
return threadLocal.session()
|
Add numeric time column (hour) that respects editions. | from __future__ import print_function
import sys
from pyspark.sql import SparkSession
from pyspark.sql.functions import lit, col, datediff
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: c19.py <input> <output>", file=sys.stderr)
exit(-1)
spark = SparkSession.builder.appName('Select c19').getOrCreate()
raw = spark.read.option('mergeSchema','true').load(sys.argv[1])
df = raw.filter(col('date') < '1900')
opens = df.filter(col('open') == 'true')\
.select('series', 'date', lit(1).alias('inopen')).distinct()
df.join(opens, ['series', 'date'], 'left_outer')\
.filter((col('open') == 'true') | col('inopen').isNull())\
.drop('inopen')\
.dropDuplicates(['id'])\
.withColumn('ednum', col('ed').cast('int')).na.fill(1, ['ednum']) \
.withColumn('hour', datediff(col('date'), lit('1970-01-01')) * 24 + col('ednum') - 1) \
.drop('ednum') \
.write.save(sys.argv[2])
spark.stop()
| from __future__ import print_function
import sys
from pyspark.sql import SparkSession
from pyspark.sql.functions import lit, col
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: c19.py <input> <output>", file=sys.stderr)
exit(-1)
spark = SparkSession.builder.appName('Select c19').getOrCreate()
raw = spark.read.option('mergeSchema','true').load(sys.argv[1])
df = raw.filter(col('date') < '1900')
opens = df.filter(col('open') == 'true')\
.select('series', 'date', lit(1).alias('inopen')).distinct()
df.join(opens, ['series', 'date'], 'left_outer')\
.filter((col('open') == 'true') | col('inopen').isNull())\
.drop('inopen')\
.dropDuplicates(['id'])\
.write.save(sys.argv[2])
spark.stop()
|
Update after forum views now is class based | from django import template
register = template.Library()
def paginator(context, adjacent_pages=4):
"""
To be used in conjunction with the object_list generic view.
Adds pagination context variables for use in displaying first, adjacent and
last page links in addition to those created by the object_list generic
view.
"""
paginator = context["paginator"]
page_obj = context["page_obj"]
page_numbers = [n for n in range(context["page"] - adjacent_pages, context["page"] + adjacent_pages + 1) if n > 0 and n <= paginator.num_pages]
return {
"hits": paginator.count,
"page": context["page"],
"pages": paginator.num_pages,
"page_numbers": page_numbers,
"next": page_obj.next_page_number,
"previous": page_obj.previous_page_number,
"has_next": page_obj.has_next,
"has_previous": page_obj.has_previous,
"show_first": 1 not in page_numbers,
"show_last": paginator.num_pages not in page_numbers,
}
register.inclusion_tag("navigation/paginator.html", takes_context=True)(paginator)
| from django import template
register = template.Library()
def paginator(context, adjacent_pages=4):
"""
To be used in conjunction with the object_list generic view.
Adds pagination context variables for use in displaying first, adjacent and
last page links in addition to those created by the object_list generic
view.
"""
page_numbers = [n for n in range(context["page"] - adjacent_pages, context["page"] + adjacent_pages + 1) if n > 0 and n <= context["pages"]]
return {
"hits": context["hits"],
"results_per_page": context["results_per_page"],
"page": context["page"],
"pages": context["pages"],
"page_numbers": page_numbers,
"next": context["next"],
"previous": context["previous"],
"has_next": context["has_next"],
"has_previous": context["has_previous"],
"show_first": 1 not in page_numbers,
"show_last": context["pages"] not in page_numbers,
}
register.inclusion_tag("navigation/paginator.html", takes_context=True)(paginator)
|
Rename variable to suit what it does
The name variable was used only as the path for the local root | <?php
namespace Config;
class Environment {
private $localRootPath;
private $isRemoteServer;
private $debug;
public function __construct(\Utils\Request $request, $localRootPath) {
$this->localRootPath = $localRootPath;
// If the document root is not windows then it must be remote
$this->isRemoteServer = strpos($request->server('DOCUMENT_ROOT'), 'C:') !== 0;
// If it is local or a test site then debug
$this->debug = (strpos($request->server('SERVER_NAME'), 'test') === 0 || !$this->isRemoteServer);
}
public function getLocalRootPath() {
return $this->localRootPath;
}
public function getIsOnline() {
return $this->isRemoteServer;
}
public function getDebug() {
return $this->debug;
}
public function getRoot() {
if (!$this->isRemoteServer) return '/' . $this->localRootPath . '/';
else return DIRECTORY_SEPARATOR;
}
}
| <?php
namespace Config;
class Environment {
private $name;
private $isRemoteServer;
private $debug;
public function __construct(\Utils\Request $request, $name) {
$this->name = $name;
// If the document root is not windows then it must be remote
$this->isRemoteServer = strpos($request->server('DOCUMENT_ROOT'), 'C:') !== 0;
// If it is local or a test site then debug
$this->debug = (strpos($request->server('SERVER_NAME'), 'test') === 0 || !$this->isRemoteServer);
}
public function getName() {
return $this->name;
}
public function getIsOnline() {
return $this->isRemoteServer;
}
public function getDebug() {
return $this->debug;
}
public function getRoot() {
if (!$this->isRemoteServer) return '/' . $this->name . '/';
else return DIRECTORY_SEPARATOR;
}
}
|
Allow class names starting with digits | <?php
namespace Phug\Lexer\Scanner;
use Phug\Lexer\ScannerInterface;
use Phug\Lexer\State;
use Phug\Lexer\Token\ClassToken;
class ClassScanner implements ScannerInterface
{
public function scan(State $state)
{
foreach ($state->scanToken(ClassToken::class, '\.(?<name>[a-z0-9\-_]+)', 'i') as $token) {
yield $token;
//Before any sub-tokens (e.g. just '.' to enter a text block), we scan for further classes
foreach ($state->scan(self::class) as $subToken) {
yield $subToken;
}
foreach ($state->scan(IdScanner::class) as $subToken) {
yield $subToken;
}
foreach ($state->scan(AutoCloseScanner::class) as $subToken) {
yield $subToken;
}
foreach ($state->scan(SubScanner::class) as $subToken) {
yield $subToken;
}
}
}
}
| <?php
namespace Phug\Lexer\Scanner;
use Phug\Lexer\ScannerInterface;
use Phug\Lexer\State;
use Phug\Lexer\Token\ClassToken;
class ClassScanner implements ScannerInterface
{
public function scan(State $state)
{
foreach ($state->scanToken(ClassToken::class, '\.(?<name>[a-z\-_][a-z0-9\-_]*)', 'i') as $token) {
yield $token;
//Before any sub-tokens (e.g. just '.' to enter a text block), we scan for further classes
foreach ($state->scan(self::class) as $subToken) {
yield $subToken;
}
foreach ($state->scan(IdScanner::class) as $subToken) {
yield $subToken;
}
foreach ($state->scan(AutoCloseScanner::class) as $subToken) {
yield $subToken;
}
foreach ($state->scan(SubScanner::class) as $subToken) {
yield $subToken;
}
}
}
}
|
Fix travis? It was referencing the old /components folder which has since been renamed. | var config = module.exports;
config['development'] = {
env: 'browser'
, rootPath: '../'
, deps: [
'bower_components/jquery/jquery.js'
]
, sources: ['src/js/aviso.js']
, specs: ['test/buster-jquery-assertions.js', 'test/spec/**/*.js']
// , extensions: [ require('buster-coverage') ]
// , "buster-coverage": {
// outputDirectory: "test/coverage"
// , format: "lcov"
// , combinedResultsOnly: true
// }
};
// @TODO Add tests for the /dist files
//
//config['core'] = {
// env: 'browser'
// , rootPath: '../'
// , deps: [
// 'components/jquery/jquery.js'
// ]
// , sources: ['dist/aviso.js']
// , specs: ['test/buster-jquery-assertions.js', 'test/spec/**/*.js']
//};
//
//config['amd'] = {
// env: 'browser'
// , rootPath: '../'
// , deps: [
// 'components/jquery/jquery.js'
// ]
// , sources: ['dist/amd/aviso.js']
// , specs: ['test/buster-jquery-assertions.js', 'test/spec/**/*.js']
//};
| var config = module.exports;
config['development'] = {
env: 'browser'
, rootPath: '../'
, deps: [
'components/jquery/jquery.js'
]
, sources: ['src/js/aviso.js']
, specs: ['test/buster-jquery-assertions.js', 'test/spec/**/*.js']
// , extensions: [ require('buster-coverage') ]
// , "buster-coverage": {
// outputDirectory: "test/coverage"
// , format: "lcov"
// , combinedResultsOnly: true
// }
};
// @TODO Add tests for the /dist files
//
//config['core'] = {
// env: 'browser'
// , rootPath: '../'
// , deps: [
// 'components/jquery/jquery.js'
// ]
// , sources: ['dist/aviso.js']
// , specs: ['test/buster-jquery-assertions.js', 'test/spec/**/*.js']
//};
//
//config['amd'] = {
// env: 'browser'
// , rootPath: '../'
// , deps: [
// 'components/jquery/jquery.js'
// ]
// , sources: ['dist/amd/aviso.js']
// , specs: ['test/buster-jquery-assertions.js', 'test/spec/**/*.js']
//};
|
Upgrade dependency python-slugify to ==1.2.3 | import os
from setuptools import setup
from withtool import __version__
def read(fname):
path = os.path.join(os.path.dirname(__file__), fname)
with open(path, encoding='utf-8') as f:
return f.read()
setup(
name='with',
version=__version__,
description='A shell context manager',
long_description=read('README.rst'),
author='Renan Ivo',
author_email='renanivom@gmail.com',
url='https://github.com/renanivo/with',
keywords='context manager shell command line repl',
scripts=['bin/with'],
install_requires=[
'appdirs==1.4.3',
'docopt==0.6.2',
'prompt-toolkit==1.0',
'python-slugify==1.2.3',
],
packages=['withtool'],
classifiers=[
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
| import os
from setuptools import setup
from withtool import __version__
def read(fname):
path = os.path.join(os.path.dirname(__file__), fname)
with open(path, encoding='utf-8') as f:
return f.read()
setup(
name='with',
version=__version__,
description='A shell context manager',
long_description=read('README.rst'),
author='Renan Ivo',
author_email='renanivom@gmail.com',
url='https://github.com/renanivo/with',
keywords='context manager shell command line repl',
scripts=['bin/with'],
install_requires=[
'appdirs==1.4.3',
'docopt==0.6.2',
'prompt-toolkit==1.0',
'python-slugify==1.2.2',
],
packages=['withtool'],
classifiers=[
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
|
Fix active tab bottom border | exports.decorateConfig = (config) => {
return Object.assign({}, config, {
foregroundColor: '#ECEFF1',
backgroundColor: '#263238',
borderColor: '#222d32',
cursorColor: 'rgba(0, 150, 136, .5)',
colors: [
'#263238',
'#FF5252',
'#9CCC65',
'#fee94e',
'#2b98f0',
'#b38bfc',
'#68b6f3',
'#ECEFF1',
'#617d8a',
'#fc625d',
'#9CCC65',
'#fee94e',
'#2b98f0',
'#b38bfc',
'#68b6f3',
'#ffffff'
],
css: `
${config.css || ''}
.hyperterm_main {
border: none !important;
}
.header_header {
background: #222d32 !important;
}
.tab_tab {
border: 0;
}
.tab_textActive {
border-bottom: 2px solid #009688;
}
`
})
}
| exports.decorateConfig = (config) => {
return Object.assign({}, config, {
foregroundColor: '#ECEFF1',
backgroundColor: '#263238',
borderColor: '#222d32',
cursorColor: 'rgba(0, 150, 136, .5)',
colors: [
'#263238',
'#FF5252',
'#9CCC65',
'#fee94e',
'#2b98f0',
'#b38bfc',
'#68b6f3',
'#ECEFF1',
'#617d8a',
'#fc625d',
'#9CCC65',
'#fee94e',
'#2b98f0',
'#b38bfc',
'#68b6f3',
'#ffffff'
],
css: `
${config.css || ''}
.hyperterm_main {
border: none !important;
}
.header_header {
background: #222d32 !important;
}
.tab_tab {
border: 0;
}
.tab_active::before {
border-bottom: 2px solid #009688;
}
`
})
}
|
Add getContent method to loader | <?php
namespace Exedra\Application;
class Loader
{
private $loaded;
public $structure;
public function __construct(\Exedra\Application\Structure $structure)
{
$this->structure = $structure;
}
public function isLoadable($file)
{
return strpos($file, ":") !== false;
}
private function refinePath($file)
{
if(($colonPos = strpos($file, ":")) !== false)
{
list($structure,$file) = explode(":",$file);
$file = $this->structure->get($structure)."/".$file;
}
return $file;
}
public function load($file,$data = null)
{
$file = $this->refinePath($file);
if(isset($loaded[$file])) return false;
if(!file_exists($file))
throw new \Exception("File not found : $file");
if($data && is_array($data))
extract($data);
return require_once $file;
}
public function getContent($file)
{
$file = $this->refinePath($file);
if(!file_exists($file))
throw new \Exception("File not found : $file");
return file_get_contents($file);
}
}
?> | <?php
namespace Exedra\Application;
class Loader
{
private $loaded;
public $structure;
public function __construct(\Exedra\Application\Structure $structure)
{
$this->structure = $structure;
}
public function isLoadable($file)
{
return strpos($file, ":") !== false;
}
public function load($file,$data = null, $subapp = null)
{
if(($colonPos = strpos($file, ":")) !== false)
{
list($structure,$file) = explode(":",$file);
$file = $this->structure->get($structure)."/".$file;
}
if(isset($loaded[$file])) return false;
if(!file_exists($file))
throw new \Exception("File not found : $file", 1);
if($data && is_array($data))
extract($data);
return require_once $file;
}
}
?> |
Update dodge.py for better support for versions of Python other than 2.7 | #!/usr/bin/env python
import os
import sys
from setuptools import setup
extra = {}
if sys.version_info >= (3, 0):
extra["use_2to3"] = True
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='whack',
version='0.7.0',
description='Utility for installing binaries from source with a single command',
long_description=read("README"),
author='Michael Williamson',
url='http://github.com/mwilliamson/whack',
scripts=["scripts/whack"],
packages=['whack'],
install_requires=[
'mayo>=0.2.1,<0.3',
'requests>=1,<2',
"catchy>=0.2.0,<0.3",
"beautifulsoup4>=4.1.3,<5",
"spur.local>=0.3.6,<0.4",
"dodge>=0.1.5,<0.2",
"six>=1.4.1,<2.0"
],
**extra
)
| #!/usr/bin/env python
import os
import sys
from setuptools import setup
extra = {}
if sys.version_info >= (3, 0):
extra["use_2to3"] = True
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='whack',
version='0.7.0',
description='Utility for installing binaries from source with a single command',
long_description=read("README"),
author='Michael Williamson',
url='http://github.com/mwilliamson/whack',
scripts=["scripts/whack"],
packages=['whack'],
install_requires=[
'mayo>=0.2.1,<0.3',
'requests>=1,<2',
"catchy>=0.2.0,<0.3",
"beautifulsoup4>=4.1.3,<5",
"spur.local>=0.3.6,<0.4",
"dodge>=0.1.4,<0.2",
"six>=1.4.1,<2.0"
],
**extra
)
|
Add background and title to the configuration | import webpack from 'webpack'
import FaviconsWebpackPlugin from 'favicons-webpack-plugin'
exports.modifyWebpackConfig = ({ config, stage }, { logo, icons, title, background }) => {
if (stage === 'develop-html' || stage === 'build-html') {
config.plugin(`Favicon`, FaviconsWebpackPlugin, [
{
logo: logo || './src/favicon.png',
prefix: 'favicons/',
title,
background: background || '#fff',
icons: {
android: true,
appleIcon: true,
appleStartup: true,
coast: true,
favicons: true,
yandex: true,
windows: true,
...icons,
},
},
])
}
}
| import webpack from 'webpack'
import FaviconsWebpackPlugin from 'favicons-webpack-plugin'
exports.modifyWebpackConfig = ({ config, stage }, { logo, icons }) => {
if (stage === 'develop-html' || stage === 'build-html') {
config.plugin(`Favicon`, FaviconsWebpackPlugin, [
{
logo: logo || './src/favicon.png',
prefix: 'favicons/',
icons: {
android: true,
appleIcon: true,
appleStartup: true,
coast: true,
favicons: true,
yandex: true,
windows: true,
...icons,
},
},
])
}
}
|
INSERT a NULL value and SELECT it back out | package main
import (
"database/sql"
"log"
_ "github.com/mattn/go-sqlite3"
)
var createUsers = `
CREATE TABLE users (
id INTEGER,
name VARCHAR
);
`
var insertUser = `INSERT INTO users (id, name) VALUES (?, ?)`
var selectUser = `SELECT id, name FROM users`
type User struct {
ID int64
Name sql.NullString
}
func (u User) String() string {
if u.Name.Valid {
return u.Name.String
}
return "No name"
}
func main() {
// Connect to an in-memory sqlite3 instance
db, err := sql.Open("sqlite3", ":memory:")
if err != nil {
panic(err)
}
defer db.Close()
// Create the table
if _, err := db.Exec(createUsers); err != nil {
panic(err)
}
// Insert a user without a name
if _, err := db.Exec(insertUser, 1, nil); err != nil {
panic(err)
}
// Select a user
var user User
row := db.QueryRow(selectUser)
if err = row.Scan(&user.ID, &user.Name); err != nil {
panic(err)
}
log.Println(user)
}
| package main
import (
"database/sql"
"log"
_ "github.com/mattn/go-sqlite3"
)
var createUsers = `
CREATE TABLE users (
id INTEGER PRIMARY KEY,
name VARCHAR
);
`
var insertUser = `INSERT INTO users (id, name) VALUES (?, ?)`
var selectUser = `SELECT id, name FROM users`
func main() {
db, err := sql.Open("sqlite3", ":memory:")
if err != nil {
panic(err)
}
defer db.Close()
if _, err := db.Exec(createUsers); err != nil {
panic(err)
}
if _, err := db.Exec(insertUser, 23, "skidoo"); err != nil {
panic(err)
}
var id int64
var name string
row := db.QueryRow(selectUser)
if err = row.Scan(&id, &name); err != nil {
panic(err)
}
log.Println(id, name)
} |
Allow it to configure side | # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from libqtile.bar import CALCULATED
from libqtile.widget import TextBox
from powerline import Powerline
class QTilePowerline(Powerline):
def do_setup(self, obj):
obj.powerline = self
class PowerlineTextBox(TextBox):
def __init__(self, timeout=2, text=' ', width=CALCULATED, side='right', **config):
super(PowerlineTextBox, self).__init__(text, width, **config)
self.timeout_add(timeout, self.update)
self.side = side
powerline = QTilePowerline(ext='wm', renderer_module='pango_markup')
powerline.setup(self)
def update(self):
if not self.configured:
return True
self.text = self.powerline.render(side=self.side)
self.bar.draw()
return True
def cmd_update(self, text):
self.update(text)
def cmd_get(self):
return self.text
def _configure(self, qtile, bar):
super(PowerlineTextBox, self)._configure(qtile, bar)
self.layout = self.drawer.textlayout(
self.text,
self.foreground,
self.font,
self.fontsize,
self.fontshadow,
markup=True,
)
# TODO: Remove this at next major release
Powerline = PowerlineTextBox
| # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from libqtile.bar import CALCULATED
from libqtile.widget import TextBox
from powerline import Powerline
class QTilePowerline(Powerline):
def do_setup(self, obj):
obj.powerline = self
class PowerlineTextBox(TextBox):
def __init__(self, timeout=2, text=' ', width=CALCULATED, **config):
super(PowerlineTextBox, self).__init__(text, width, **config)
self.timeout_add(timeout, self.update)
powerline = QTilePowerline(ext='wm', renderer_module='pango_markup')
powerline.setup(self)
def update(self):
if not self.configured:
return True
self.text = self.powerline.render(side='right')
self.bar.draw()
return True
def cmd_update(self, text):
self.update(text)
def cmd_get(self):
return self.text
def _configure(self, qtile, bar):
super(PowerlineTextBox, self)._configure(qtile, bar)
self.layout = self.drawer.textlayout(
self.text,
self.foreground,
self.font,
self.fontsize,
self.fontshadow,
markup=True,
)
# TODO: Remove this at next major release
Powerline = PowerlineTextBox
|
Remove unneeded trim in float parsing | var sizeUnits = ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'];
function formatSize(value) {
if (value === 0) {
return '0';
}
var index = parseInt(Math.log(Math.abs(value)) / Math.log(1024), 10);
value /= Math.pow(1024, index);
return (Math.round(value * 100) / 100) + (index > 0 ? sizeUnits[index] : '');
}
var timeUnits = {
d: 86400000,
h: 3600000,
m: 60000,
s: 1000
};
function timeToRange(duration) {
var seconds = Math.abs(duration),
chunks = [];
for (var unit in timeUnits) {
var count = Math.floor(seconds / timeUnits[unit]);
if (count > 0) {
chunks.push(count + unit);
seconds %= timeUnits[unit];
}
}
var result = chunks.join(' ');
if (duration < 0) {
result = '-' + result;
}
return result;
}
function slugify(input) {
return input.toLowerCase()
.replace(/[^\w ]+/g, '')
.replace(/ +/g, '-');
}
function parseFloatList(input) {
return $.map(input, function (x) { return parseFloat(x); });
}
| var sizeUnits = ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'];
function formatSize(value) {
if (value === 0) {
return '0';
}
var index = parseInt(Math.log(Math.abs(value)) / Math.log(1024), 10);
value /= Math.pow(1024, index);
return (Math.round(value * 100) / 100) + (index > 0 ? sizeUnits[index] : '');
}
var timeUnits = {
d: 86400000,
h: 3600000,
m: 60000,
s: 1000
};
function timeToRange(duration) {
var seconds = Math.abs(duration),
chunks = [];
for (var unit in timeUnits) {
var count = Math.floor(seconds / timeUnits[unit]);
if (count > 0) {
chunks.push(count + unit);
seconds %= timeUnits[unit];
}
}
var result = chunks.join(' ');
if (duration < 0) {
result = '-' + result;
}
return result;
}
function slugify(input) {
return input.toLowerCase()
.replace(/[^\w ]+/g, '')
.replace(/ +/g, '-');
}
function parseFloatList(input) {
return $.map(input, function (x) { return parseFloat(x.trim()); });
}
|
Set default Db to inmemory storage | class DefaultConfig(object):
SECRET_KEY = '%^!@@*!&$8xdfdirunb52438#(&^874@#^&*($@*(@&^@)(&*)Y_)((+'
SQLALCHEMY_DATABASE_URI = 'sqlite://'
class DevelopmentConfig(DefaultConfig):
AUTHY_KEY = 'your_authy_key'
TWILIO_ACCOUNT_SID = 'your_twilio_account_sid'
TWILIO_AUTH_TOKEN = 'your_twilio_auth_token'
TWILIO_NUMBER = 'your_twilio_phone_number'
SQLALCHEMY_DATABASE_URI = 'sqlite://'
DEBUG = True
class TestConfig(DefaultConfig):
SQLALCHEMY_ECHO = True
DEBUG = True
TESTING = True
WTF_CSRF_ENABLED = False
config_env_files = {
'test': 'account_verification_flask.config.TestConfig',
'development': 'account_verification_flask.config.DevelopmentConfig',
}
| class DefaultConfig(object):
SECRET_KEY = '%^!@@*!&$8xdfdirunb52438#(&^874@#^&*($@*(@&^@)(&*)Y_)((+'
SQLALCHEMY_DATABASE_URI = 'sqlite://'
class DevelopmentConfig(DefaultConfig):
AUTHY_KEY = 'your_authy_key'
TWILIO_ACCOUNT_SID = 'your_twilio_account_sid'
TWILIO_AUTH_TOKEN = 'your_twilio_auth_token'
TWILIO_NUMBER = 'your_twilio_phone_number'
SQLALCHEMY_DATABASE_URI = 'sqlite:////Work/account_verification.db'
DEBUG = True
class TestConfig(DefaultConfig):
SQLALCHEMY_ECHO = True
DEBUG = True
TESTING = True
WTF_CSRF_ENABLED = False
config_env_files = {
'test': 'account_verification_flask.config.TestConfig',
'development': 'account_verification_flask.config.DevelopmentConfig',
}
|
Add task version to BuildgenBase.
Debugging a break after a refactor, I wanted to invalidate
just the buildgen caches.
(sapling split of c73dc81f2af0cdc87d21519b032ae3f6213c932c) | # coding=utf-8
# Copyright 2016 Foursquare Labs Inc. All Rights Reserved.
from __future__ import (
absolute_import,
division,
generators,
nested_scopes,
print_function,
unicode_literals,
with_statement,
)
from pants.task.task import Task
from pants.util.memo import memoized_property
from fsqio.pants.buildgen.core.subsystems.buildgen_subsystem import BuildgenSubsystem
class BuildgenBase(Task):
""""A base task that provides the buildgen subsystem to its implementers."""
@classmethod
def global_subsystems(cls):
return super(BuildgenBase, cls).global_subsystems() + (BuildgenSubsystem.Factory,)
@classmethod
def implementation_version(cls):
return super(BuildgenBase, cls).implementation_version() + [('BuildgenBase', 1)]
@memoized_property
def buildgen_subsystem(self):
# TODO(pl): When pants is a proper library dep, remove this ignore.
# pylint: disable=no-member
return BuildgenSubsystem.Factory.global_instance().create()
| # coding=utf-8
# Copyright 2016 Foursquare Labs Inc. All Rights Reserved.
from __future__ import (
absolute_import,
division,
generators,
nested_scopes,
print_function,
unicode_literals,
with_statement,
)
from pants.task.task import Task
from pants.util.memo import memoized_property
from fsqio.pants.buildgen.core.subsystems.buildgen_subsystem import BuildgenSubsystem
class BuildgenBase(Task):
""""A base task that provides the buildgen subsystem to its implementers."""
@classmethod
def global_subsystems(cls):
return super(BuildgenBase, cls).global_subsystems() + (BuildgenSubsystem.Factory,)
@memoized_property
def buildgen_subsystem(self):
# TODO(pl): When pants is a proper library dep, remove this ignore.
# pylint: disable=no-member
return BuildgenSubsystem.Factory.global_instance().create()
|
Fix join condition and remove QueryDriver::free statement | <?php
class MigrationRunnerTest extends PHPUnit_Framework_TestCase
{
function testRunner()
{
$connm = LazyRecord\ConnectionManager::getInstance();
$connm->addDataSource('default',array( 'dsn' => 'sqlite::memory:' ));
$runner = new LazyRecord\Migration\MigrationRunner('default');
ok($runner);
$runner->load('tests/migrations');
return $runner;
}
/**
* @depends testRunner
*/
function testUpgrade($runner)
{
$this->expectOutputRegex('#CreateUser_1346436136#');
$this->expectOutputRegex('#QueryOK#');
$runner->runUpgrade();
return $runner;
}
/**
* @depends testUpgrade
*/
function testDowngrade($runner)
{
$this->expectOutputRegex('#Running downgrade migration script#');
$runner->runDowngrade();
}
}
| <?php
class MigrationRunnerTest extends PHPUnit_Framework_TestCase
{
function testRunner()
{
LazyRecord\QueryDriver::free();
$connm = LazyRecord\ConnectionManager::getInstance();
$connm->addDataSource('default',array( 'dsn' => 'sqlite::memory:' ));
$runner = new LazyRecord\Migration\MigrationRunner('default');
ok($runner);
$runner->load('tests/migrations');
return $runner;
}
/**
* @depends testRunner
*/
function testUpgrade($runner)
{
$this->expectOutputRegex('#CreateUser_1346436136#');
$this->expectOutputRegex('#QueryOK#');
$runner->runUpgrade();
return $runner;
}
/**
* @depends testUpgrade
*/
function testDowngrade($runner)
{
$this->expectOutputRegex('#Running downgrade migration script#');
$runner->runDowngrade();
}
}
|
Support replyWithFile() in the faux Nock | /**
* Copyright (c) 2015 IBM Cloudant, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
function noop() {
return this;
}
function nock_noop() {
// Return a completely inert nock-compatible object.
return {head:noop, get:noop, post:noop, put:noop, 'delete':noop, reply:noop, filteringPath:noop, done:noop, query:noop, replyWithFile:noop};
}
if (process.env.NOCK_OFF) {
var nock = nock_noop;
} else {
var nock = require('nock');
}
module.exports = nock;
| /**
* Copyright (c) 2015 IBM Cloudant, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
function noop() {
return this;
}
function nock_noop() {
// Return a completely inert nock-compatible object.
return {head:noop, get:noop, post:noop, put:noop, 'delete':noop, reply:noop, filteringPath:noop, done:noop, query:noop};
}
if (process.env.NOCK_OFF) {
var nock = nock_noop;
} else {
var nock = require('nock');
}
module.exports = nock;
|
Add null fields to action-item-distribution config for consistency | export default {
"prime-directive": {
alert: null,
confirmationMessage: "Are you sure want to proceed to the Idea Generation stage? This will commence the retro in earnest.",
nextStage: "idea-generation",
button: {
copy: "Proceed to Idea Generation",
iconClass: "arrow right",
},
},
"idea-generation": {
alert: null,
confirmationMessage: "Are you sure you would like to proceed to the action items stage?",
nextStage: "action-items",
button: {
copy: "Proceed to Action Items",
iconClass: "arrow right",
},
},
"action-items": {
alert: null,
confirmationMessage: null,
nextStage: "action-item-distribution",
button: {
copy: "Send Action Items",
iconClass: "send",
},
},
"action-item-distribution": {
alert: {
headerText: "Retro Closed!",
bodyText: "The facilitator has closed this retrospective. You will receive an email containing the retrospective's action items shortly.",
},
confirmationMessage: null,
nextStage: null,
button: null,
},
}
| export default {
"prime-directive": {
alert: null,
confirmationMessage: "Are you sure want to proceed to the Idea Generation stage? This will commence the retro in earnest.",
nextStage: "idea-generation",
button: {
copy: "Proceed to Idea Generation",
iconClass: "arrow right",
},
},
"idea-generation": {
alert: null,
confirmationMessage: "Are you sure you would like to proceed to the action items stage?",
nextStage: "action-items",
button: {
copy: "Proceed to Action Items",
iconClass: "arrow right",
},
},
"action-items": {
alert: null,
confirmationMessage: null,
nextStage: "action-item-distribution",
button: {
copy: "Send Action Items",
iconClass: "send",
},
},
"action-item-distribution": {
alert: {
headerText: "Retro Closed!",
bodyText: "The facilitator has closed this retrospective. You will receive an email containing the retrospective's action items shortly.",
},
},
}
|
Test new transaction class with network | <?php
/**
* Created by PhpStorm.
* User: thomas
* Date: 15/11/14
* Time: 05:15
*/
namespace Bitcoin;
class TransactionTest extends \PHPUnit_Framework_TestCase
{
protected $network = null;
protected $transaction = null;
public function __construct()
{
$this->network = new Network('00', '05', '80');
}
public function setUp()
{
$this->transaction = new Transaction();
}
public function testGetNetworkEmpty()
{
$this->assertNull($this->transaction->getNetwork());
}
public function testSetNetwork()
{
$this->transaction->setNetwork($this->network);
$this->assertSame($this->transaction->getNetwork(), $this->network);
}
public function testNewTransactionWithNetwork()
{
$transaction = new Transaction($this->network);
$this->assertSame($this->transaction->getNetwork(), $this->network)
}
public function testGetVersionEmpty()
{
$this->assertNull($this->transaction->getVersion());
}
/**
* @depends testGetVersionEmpty
*/
public function testSetVersion()
{
$this->transaction->setVersion('1');
$this->assertSame($this->transaction->getVersion(), '1');
}
} | <?php
/**
* Created by PhpStorm.
* User: thomas
* Date: 15/11/14
* Time: 05:15
*/
namespace Bitcoin;
class TransactionTest extends \PHPUnit_Framework_TestCase
{
protected $network = null;
protected $transaction = null;
public function __construct()
{
$this->network = new Network('00', '05', '80');
}
public function setUp()
{
$this->transaction = new Transaction($this->network);
}
public function testGetNetwork()
{
$this->assertSame($this->transaction->getNetwork(), $this->network);
}
public function testGetVersionEmpty()
{
$this->assertNull($this->transaction->getVersion());
}
/**
* @depends testGetVersionEmpty
*/
public function testSetVersion()
{
$this->transaction->setVersion('1');
$this->assertSame($this->transaction->getVersion(), '1');
}
} |
Initialize _owned during buildRendering to prevent shared _owned | define([
"dojo/_base/declare"
], function (declare) {
return declare(null, {
// summary:
// Adds functionality for creating relationships between destroyable or removable objects and this object
// where they should all be destroyed together.
// _owned: Object[]
// Items that are owned by this object.
_owned: null,
buildRendering: function () {
this._owned = [];
},
own: function () {
// summary:
// Creates a relationship where this object is the owner of provided items.
// Items should have either destroyRecursive, destroy, or remove method.
this._owned = this._owned.concat(Array.prototype.slice.call(arguments, 0));
},
destroy: function () {
// summary:
// Removes all owned items before this object is destroyed.
var owned = this._owned,
i = 0,
peon;
while (peon = owned[i++]) {
if (peon.destroyRecursive) {
peon.destroyRecursive();
} else if (peon.destroy) {
peon.destroy();
} else if (peon.remove) {
peon.remove();
}
}
this.inherited(arguments);
}
});
}); | define([
"dojo/_base/declare"
], function (declare) {
return declare(null, {
// summary:
// Adds functionality for creating relationships between destroyable or removable objects and this object
// where they should all be destroyed together.
// _owned: Object[]
// Items that are owned by this object.
_owned: [],
own: function () {
// summary:
// Creates a relationship where this object is the owner of provided items.
// Items should have either destroyRecursive, destroy, or remove method.
this._owned = this._owned.concat(Array.prototype.slice.call(arguments, 0));
},
destroy: function () {
// summary:
// Removes all owned items before this object is destroyed.
var owned = this._owned,
i = 0,
peon;
while (peon = owned[i++]) {
if (peon.destroyRecursive) {
peon.destroyRecursive();
} else if (peon.destroy) {
peon.destroy();
} else if (peon.remove) {
peon.remove();
}
}
this.inherited(arguments);
}
});
}); |
Rename the config file config -> pb-config | 'use strict';
var PhonegapBoilerplate = function() {
this.loadConfig();
};
PhonegapBoilerplate.prototype = {
constructor: PhonegapBoilerplate,
options: {
repository: 'https://github.com/dorian-marchal/phonegap-boilerplate',
branch: 'master',
},
/**
* Load the configuration from the config file.
* Prompt the user to fill the configuration file if it's missing.
*/
loadConfig: function() {
this.options = require('./pb-config.json');
},
/**
* Check that the cli is used in a phonegap boilerplate project
* @return {bool} true if we are in a pb project, else otherwise
*/
checkWorkingDirectory: function() {
},
fetch: function() {
},
update: function() {
},
merge: function() {
},
push: function() {
},
};
module.exports = new PhonegapBoilerplate();
| 'use strict';
var PhonegapBoilerplate = function() {
this.loadConfig();
};
PhonegapBoilerplate.prototype = {
constructor: PhonegapBoilerplate,
options: {
repository: 'https://github.com/dorian-marchal/phonegap-boilerplate',
branch: 'master',
},
/**
* Load the configuration from the config file.
* Prompt the user to fill the configuration file if it's missing.
*/
loadConfig: function() {
this.options = require('./config.json');
},
/**
* Check that the cli is used in a phonegap boilerplate project
* @return {bool} true if we are in a pb project, else otherwise
*/
checkWorkingDirectory: function() {
},
fetch: function() {
},
update: function() {
},
merge: function() {
},
push: function() {
},
};
module.exports = new PhonegapBoilerplate();
|
Refactor to make more wrapper based. | /**
* The basic content data type.
*/
const _ = require('lodash')
// Basic content data type.
const contentTemplate = {
// If truthy there is an error.
error: {
// Errors are non-zero codes.
code: 0,
// Errors must produce a non-falsey message.
message: ''
},
// Content either being retrieved or previously retrieved.
content: {
// name of transformer used to modify the content.
transformer: '',
// url content was retrieved from.
url: '',
// Type of the content: html, markdown, plain, etc.
type: '',
// the marked up text of the content.
text: '',
},
}
/**
* Returns an instance of the contentTemplate.
*
* @param {object} overrides Overrides for content. Assumes correct format.
* @return {object} Basic content object.
*/
const create = function (overrides) {
return _.merge({}, contentTemplate, overrides || {})
}
module.exports = {
create,
}
| /**
* The basic content data type.
*/
const lodash = require('lodash')
// Basic content data type.
const contentTemplate = {
// If truthy there is an error.
error: {
// Errors are non-zero codes.
code: 0,
// Errors must produce a non-falsey message.
message: ''
},
// Content either being retrieved or previously retrieved.
content: {
// name of transformer used to modify the content.
transformer: '',
// url content was retrieved from.
url: '',
// Type of the content: html, markdown, plain, etc.
type: '',
// the marked up text of the content.
text: '',
},
}
/**
* Returns an instance of the contentTemplate.
*
* @param {object} overrides Overrides for content. Assumes correct format.
* @return {object} Basic content object.
*/
const content = function (overrides) {
return lodash.merge({}, contentTemplate, overrides || {})
}
module.exports.content = content
|
Fix composer setup for tests | <?php
/*
* This file is part of the HWIOAuthBundle package.
*
* (c) Hardware.Info <opensource@hardware.info>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
if (file_exists($file = __DIR__.'/../vendor/autoload.php')) {
$autoload = require_once $file;
} else {
throw new RuntimeException('Install dependencies to run test suite.');
}
spl_autoload_register(function($class) {
if (0 === strpos($class, 'HWI\\Bundle\\OAuthBundle')) {
$path = __DIR__.'/../'.implode('/', array_slice(explode('\\', $class), 3)).'.php';
if (!stream_resolve_include_path($path)) {
return false;
}
require_once $path;
return true;
}
});
| <?php
/*
* This file is part of the HWIOAuthBundle package.
*
* (c) Hardware.Info <opensource@hardware.info>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
if (file_exists($file = __DIR__.'/../vendor/.composer/autoload.php')) {
$autoload = require_once $file;
} else {
throw new RuntimeException('Install dependencies to run test suite.');
}
spl_autoload_register(function($class) {
if (0 === strpos($class, 'HWI\\Bundle\\OAuthBundle')) {
$path = __DIR__.'/../'.implode('/', array_slice(explode('\\', $class), 3)).'.php';
if (!stream_resolve_include_path($path)) {
return false;
}
require_once $path;
return true;
}
});
|
Add horizontal line element to header | <hr class="govuk-section-break govuk-section-break--l govuk-section-break--visible">
<h2 class="govuk-heading-l">Search results for <?php the_search_query(); ?> </h2>
<?php if (have_posts()) { ?>
<?php while (have_posts()) : the_post() ?>
<article <?php post_class() ?>>
<header>
<h3 class=govuk-heading-m"><a href="<?php the_permalink() ?>"><?php the_title() ?></a></h3>
<?php get_template_part('templates/entry-meta') ?>
<?php if (has_post_thumbnail()) {
the_post_thumbnail('large');
} ?>
</header>
<?php the_excerpt() ?>
<?php get_template_part('templates/entry-footer') ?>
</article>
<?php endwhile ?>
<?php } else { ?>
<article>
<p>No results found on <strong><?php echo get_bloginfo('name'); ?></strong>.</p>
<p>Please try searching again using different words or try this search on <a href="https://www.gov.uk/">GOV.UK</a>.</p>
</article>
<?php } ?>
| <h2 class="govuk-heading-l">Search results for <?php the_search_query(); ?> </h2>
<?php if (have_posts()) { ?>
<?php while (have_posts()) : the_post() ?>
<article <?php post_class() ?>>
<header>
<h3 class=govuk-heading-m"><a href="<?php the_permalink() ?>"><?php the_title() ?></a></h3>
<?php get_template_part('templates/entry-meta') ?>
<?php if (has_post_thumbnail()) {
the_post_thumbnail('large');
} ?>
</header>
<?php the_excerpt() ?>
<?php get_template_part('templates/entry-footer') ?>
</article>
<?php endwhile ?>
<?php } else { ?>
<article>
<p>No results found on <strong><?php echo get_bloginfo('name'); ?></strong>.</p>
<p>Please try searching again using different words or try this search on <a href="https://www.gov.uk/">GOV.UK</a>.</p>
</article>
<?php } ?>
|
Add comments and documentation to definitions. | package schema
import "time"
// A Service is a named service that has a set of templates associated with it.
type Service struct {
ID string `gorethink:"id"`
Name string `gorethink:"name"`
Type string `gorethink:"_type"` // The type of service.
Current bool `gorethink:"current"` // Is this the current service definition.
CTime time.Time `gorethink:"ctime"`
}
// Service2Template is a join table that maps a service to templates.
type Service2Template struct {
ID string `gorethink:"id"`
ServiceID string `gorethink:"service_id"`
TemplateID string `gorethink:"template_id"`
}
// Template is a consul-template for service configuration/monitoring.
type Template struct {
ID string `gorethink:"id"`
Name string `gorethink:"name"`
Path string `gorethink:"path"` // Path to template definition
Body string `gorethink:"body"` // The body of the template (same as Path at point in time)
Version int `gorethink:"version"` // Version of template. A template can change over time.
}
// ChangeLog tracks the changes to service and template definitions. It allows
// a user to see the difference across definitions.
type ChangeLog struct {
ID string `gorethink:"id"`
OtherID string `gorethink:"other_id"`
Who string `gorethink:"who"`
When time.Time `gorethink:"when"`
}
| package schema
import "time"
type Service struct {
ID string `gorethink:"id"`
Name string `gorethink:"name"`
Type string `gorethink:"_type"`
Current bool `gorethink:"current"`
CTime time.Time `gorethink:"ctime"`
}
type Service2Template struct {
ID string `gorethink:"id"`
ServiceID string `gorethink:"service_id"`
TemplateID string `gorethink:"template_id"`
}
type Template struct {
ID string `gorethink:"id"`
Name string `gorethink:"name"`
Body string `gorethink:"body"`
Version int `gorethink:"version"`
}
type ChangeLog struct {
ID string `gorethink:"id"`
OtherID string `gorethink:"other_id"`
Who string `gorethink:"who"`
When time.Time `gorethink:"when"`
}
|
Fix the accidental removal of IS_PY26 | """
Compatibility shims for different Python versions and platforms.
"""
try:
import json
except ImportError:
try:
import simplejson as json
except ImportError:
import django.utils.simplejson as json
import sys
IS_PY26 = sys.version[:2] == (2, 6)
IS_PY3 = sys.version_info[0] == 3
import platform
IS_PYPY = platform.python_implementation() == 'PyPy'
unichr = chr if IS_PY3 else unichr
xrange = range if IS_PY3 else xrange
if IS_PY3:
ifilter = filter
imap = map
izip = zip
from itertools import (
zip_longest as izip_longest,
filterfalse as ifilterfalse,
)
else:
from itertools import ifilter, ifilterfalse, imap, izip, izip_longest
| """
Compatibility shims for different Python versions and platforms.
"""
try:
import json
except ImportError:
try:
import simplejson as json
except ImportError:
import django.utils.simplejson as json
import sys
IS_PY3 = sys.version_info[0] == 3
import platform
IS_PYPY = platform.python_implementation() == 'PyPy'
unichr = chr if IS_PY3 else unichr
xrange = range if IS_PY3 else xrange
if IS_PY3:
ifilter = filter
imap = map
izip = zip
from itertools import (
zip_longest as izip_longest,
filterfalse as ifilterfalse,
)
else:
from itertools import ifilter, ifilterfalse, imap, izip, izip_longest
|
Insert new files, Alura, Projeto de Algoritmos 1, Aula 10 | public class TestaMenorPreco {
public static void main(String[] args) {
Produto produtos[] = {
new Produto("Lamborghini", 1000000),
new Produto("Jipe", 46000),
new Produto("Brasília", 16000),
new Produto("Smart", 46000),
new Produto("Fusca", 17000)
};
int maisBarato = 0;
for(int atual = 0; atual <= 4; atual++) {
if(produtos[atual].getPreco() < produtos[maisBarato].getPreco()) {
maisBarato = atual;
}
}
System.out.println(maisBarato);
System.out.println("O carro " + produtos[maisBarato].getNome()
+ " é o mais barato, e custa "
+ produtos[maisBarato].getPreco());
}
}
| public class TestaMenorPreco {
public static void main(String[] args) {
Produto produtos[] = new Produto[5];
produtos[0] = new Produto("Lamborghini", 1000000);
produtos[1] = new Produto("Jipe", 46000);
produtos[2] = new Produto("Brasília", 16000);
produtos[3] = new Produto("Smart", 46000);
produtos[4] = new Produto("Fusca", 17000);
int maisBarato = 0;
for(int atual = 0; atual <= 4; atual++) {
if(produtos[atual].getPreco() < produtos[maisBarato].getPreco()) {
maisBarato = atual;
}
}
System.out.println(maisBarato);
System.out.println("O carro " + produtos[maisBarato].getNome()
+ " é o mais barato, e custa "
+ produtos[maisBarato].getPreco());
}
}
|
Change android tests from selendroid → appium | // Test runner
var runTests = require('./affixing-header-specs'),
browsers = [
{browserName: 'chrome'},
{browserName: 'firefox'}
];
// var browserConfig = require('./helpers/browser-config');
if (process.env.TRAVIS_JOB_NUMBER) {
browsers.push(
{browserName: 'Safari', version: '7'},
{browserName: 'Safari', deviceName: 'iPhone Simulator', platformName: 'iOS', platformVersion: '8.2', appiumVersion: '1.3.7'},
{browserName: 'Safari', deviceName: 'iPad Simulator', platformName: 'iOS', platformVersion: '8.2', appiumVersion: '1.3.7'},
{browserName: 'Browser', deviceName: 'Samsung Galaxy S4 Emulator', platformName: 'Android', platformVersion: '4.4', appiumVersion: '1.3.7'},
{browserName: 'internet explorer'}
);
}
browsers.forEach(function(browser) {
runTests(browser);
});
| // Test runner
var runTests = require('./affixing-header-specs'),
browsers = [
{browserName: 'chrome'},
{browserName: 'firefox'}
];
// var browserConfig = require('./helpers/browser-config');
if (process.env.TRAVIS_JOB_NUMBER) {
browsers.push(
{browserName: 'Safari', version: '7'},
{browserName: 'Safari', deviceName: 'iPhone Simulator', platformName: 'iOS', platformVersion: '8.2', appiumVersion: '1.3.7'},
{browserName: 'Safari', deviceName: 'iPad Simulator', platformName: 'iOS', platformVersion: '8.2', appiumVersion: '1.3.7'},
{browserName: 'Android', deviceName: 'Android Emulator', platform: 'Linux', version: '5.1'},
{browserName: 'internet explorer'}
);
}
browsers.forEach(function(browser) {
runTests(browser);
});
|
Fix typo in CD server. | // Continuous delivery server
const { spawn } = require('child_process')
const { resolve } = require('path')
const { createServer } = require('http')
const { urlencoded } = require('body-parser')
const hostname = '127.0.0.1'
const port = 80
const server = createServer((req, res) => {
const { headers, method, url } = req
// When a successful build has happened, kill the process, triggering a restart
if (req.method === 'POST' && req.url === '/webhook') {
// Send response
res.statusCode = 200
res.end()
let body = []
request
.on('error', err => {
console.error(err)
})
.on('data', chunk => {
body.push(chunk)
})
.on('end', () => {
body = Buffer.concat(body).toString()
const data = urlencoded(body)
console.log(data)
})
}
res.statusCode = 404
res.end()
}).listen(port)
| // Continuous delivery server
const { spawn } = require('child_process')
const { resolve } = require('path')
const { createServer } = require('http')
const { urlencoded } = require('body-parser')
const hostname = '127.0.0.1'
const port = 80
const server = createServer((req, res) => {
const { headers, method, url } = request
// When a successful build has happened, kill the process, triggering a restart
if (req.method === 'POST' && req.url === '/webhook') {
// Send response
res.statusCode = 200
res.end()
let body = []
request
.on('error', err => {
console.error(err)
})
.on('data', chunk => {
body.push(chunk)
})
.on('end', () => {
body = Buffer.concat(body).toString()
const data = urlencoded(body)
console.log(data)
})
}
res.statusCode = 404
res.end()
}).listen(port)
|
Define warning message from CW | /*
* Copyright 2016 The CodeWorld Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
goog.provide('Blockly.Init');
goog.require('Blockly');
goog.require('Blockly.Blocks.cwEvent');
// Initialize Blockly logic specific to CodeWorld
// Top level program blocks, only allow one of each
Blockly.Flyout.programBlockList = ["cwAnimationOf", "cwDrawingOf", "cwSimulationOf","cwInteractionOf" ];
// Automatically generate a type block for each of these
Blockly.UserTypes.builtinsStatic = ["Truth", "Number", "Color", "Picture", "Text"];
// Add a these blockTypes to the toolbox
Blockly.UserTypes.builtinsDynamic = ["type_list"];
// Enable the Event drawer
Blockly.Flyout.customDrawers["EVENT"] = Blockly.cwEvent.eventFlyoutCategory;
Blockly.Events.orphanWarning = "This block is disabled because it is isolated from the main program.";
Blockly.Events.disconnectedWarning = "There's a block missing";
| /*
* Copyright 2016 The CodeWorld Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
goog.provide('Blockly.Init');
goog.require('Blockly');
goog.require('Blockly.Blocks.cwEvent');
// Initialize Blockly logic specific to CodeWorld
// Top level program blocks, only allow one of each
Blockly.Flyout.programBlockList = ["cwAnimationOf", "cwDrawingOf", "cwSimulationOf","cwInteractionOf" ];
// Automatically generate a type block for each of these
Blockly.UserTypes.builtinsStatic = ["Truth", "Number", "Color", "Picture", "Text"];
// Add a these blockTypes to the toolbox
Blockly.UserTypes.builtinsDynamic = ["type_list"];
// Enable the Event drawer
Blockly.Flyout.customDrawers["EVENT"] = Blockly.cwEvent.eventFlyoutCategory;
|
Remove unnecessary comments and add javadoc | package kernitus.plugin.OldCombatMechanics.module;
import kernitus.plugin.OldCombatMechanics.OCMMain;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.event.EventHandler;
import org.bukkit.event.entity.ProjectileLaunchEvent;
import org.bukkit.projectiles.ProjectileSource;
import org.bukkit.util.Vector;
/**
* Prevents the noise introduced when shooting with a bow to make arrows go straight.
*/
public class ModuleDisableProjectileRandomness extends Module {
public ModuleDisableProjectileRandomness(OCMMain plugin){
super(plugin, "disable-projectile-randomness");
}
@EventHandler
public void onProjectileLaunch(ProjectileLaunchEvent e){
Projectile projectile = e.getEntity();
ProjectileSource shooter = projectile.getShooter();
if(shooter instanceof Player){
Player player = (Player) shooter;
if(!isEnabled(player.getWorld())) return;
debug("Making projectile go straight", player);
Vector playerDirection = player.getLocation().getDirection().normalize();
// keep original speed
Vector arrowVelocity = playerDirection.multiply(projectile.getVelocity().length());
projectile.setVelocity(arrowVelocity);
}
}
} | package kernitus.plugin.OldCombatMechanics.module;
import kernitus.plugin.OldCombatMechanics.OCMMain;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.event.EventHandler;
import org.bukkit.event.entity.ProjectileLaunchEvent;
import org.bukkit.projectiles.ProjectileSource;
public class ModuleDisableProjectileRandomness extends Module {
public ModuleDisableProjectileRandomness(OCMMain plugin){
super(plugin, "disable-projectile-randomness");
}
@EventHandler
public void onProjectileLaunch(ProjectileLaunchEvent e){
Projectile projectile = e.getEntity(); //Getting the projectile
ProjectileSource shooter = projectile.getShooter(); //Getting the shooter
if(shooter instanceof Player){ //If the shooter was a player
Player player = (Player) shooter;
if(!isEnabled(player.getWorld())) return; //If this module is enabled in this world
debug("Making projectile go straight", player);
//Here we get a unit vector of the direction the player is looking in and multiply it by the projectile's vector's magnitude
//We then assign this to the projectile as its new velocity
projectile.setVelocity(player.getLocation().getDirection().normalize().multiply(projectile.getVelocity().length()));
}
}
} |
Remove exception eating from dispatch_hook. | # -*- coding: utf-8 -*-
"""
requests.hooks
~~~~~~~~~~~~~~
This module provides the capabilities for the Requests hooks system.
Available hooks:
``args``:
A dictionary of the arguments being sent to Request().
``pre_request``:
The Request object, directly after being created.
``pre_send``:
The Request object, directly before being sent.
``post_request``:
The Request object, directly after being sent.
``response``:
The response generated from a Request.
"""
HOOKS = ('args', 'pre_request', 'pre_send', 'post_request', 'response')
def dispatch_hook(key, hooks, hook_data):
"""Dispatches a hook dictionary on a given piece of data."""
hooks = hooks or dict()
if key in hooks:
hooks = hooks.get(key)
if hasattr(hooks, '__call__'):
hooks = [hooks]
for hook in hooks:
_hook_data = hook(hook_data)
if _hook_data is not None:
hook_data = _hook_data
return hook_data
| # -*- coding: utf-8 -*-
"""
requests.hooks
~~~~~~~~~~~~~~
This module provides the capabilities for the Requests hooks system.
Available hooks:
``args``:
A dictionary of the arguments being sent to Request().
``pre_request``:
The Request object, directly after being created.
``pre_send``:
The Request object, directly before being sent.
``post_request``:
The Request object, directly after being sent.
``response``:
The response generated from a Request.
"""
import traceback
HOOKS = ('args', 'pre_request', 'pre_send', 'post_request', 'response')
def dispatch_hook(key, hooks, hook_data):
"""Dispatches a hook dictionary on a given piece of data."""
hooks = hooks or dict()
if key in hooks:
hooks = hooks.get(key)
if hasattr(hooks, '__call__'):
hooks = [hooks]
for hook in hooks:
try:
_hook_data = hook(hook_data)
if _hook_data is not None:
hook_data = _hook_data
except Exception:
traceback.print_exc()
return hook_data
|
Fix scrollLeft/scrollTop warning in latest Chrome
Chrome gives the warnings
```
body.scrollLeft is deprecated in strict mode. Please use 'documentElement.scrollLeft' if in strict mode and 'body.scrollLeft' only if in quirks mode.
body.scrollTop is deprecated in strict mode. Please use 'documentElement.scrollTop' if in strict mode and 'body.scrollTop' only if in quirks mode.
```
the first time getUnboundedScrollPosition is invoked. This fixes it. (All modern browsers support `pageYOffset`; IE 8 doesn't but works properly with `document.documentElement.scrollTop` except in quirks mode which React doesn't support.) | /**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule getUnboundedScrollPosition
* @typechecks
*/
"use strict";
/**
* Gets the scroll position of the supplied element or window.
*
* The return values are unbounded, unlike `getScrollPosition`. This means they
* may be negative or exceed the element boundaries (which is possible using
* inertial scrolling).
*
* @param {DOMWindow|DOMElement} scrollable
* @return {object} Map with `x` and `y` keys.
*/
function getUnboundedScrollPosition(scrollable) {
if (scrollable === window) {
return {
x: window.pageXOffset || document.documentElement.scrollLeft,
y: window.pageYOffset || document.documentElement.scrollTop
};
}
return {
x: scrollable.scrollLeft,
y: scrollable.scrollTop
};
}
module.exports = getUnboundedScrollPosition;
| /**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule getUnboundedScrollPosition
* @typechecks
*/
"use strict";
/**
* Gets the scroll position of the supplied element or window.
*
* The return values are unbounded, unlike `getScrollPosition`. This means they
* may be negative or exceed the element boundaries (which is possible using
* inertial scrolling).
*
* @param {DOMWindow|DOMElement} scrollable
* @return {object} Map with `x` and `y` keys.
*/
function getUnboundedScrollPosition(scrollable) {
if (scrollable === window) {
return {
x: document.documentElement.scrollLeft || document.body.scrollLeft,
y: document.documentElement.scrollTop || document.body.scrollTop
};
}
return {
x: scrollable.scrollLeft,
y: scrollable.scrollTop
};
}
module.exports = getUnboundedScrollPosition;
|
build(algolia): Add objects *after* clearing index | import algolia from 'algoliasearch';
import icons from '../dist/icons.json';
import tags from '../src/tags.json';
const ALGOLIA_APP_ID = '5EEOG744D0';
if (
process.env.TRAVIS_PULL_REQUEST === 'false' &&
process.env.TRAVIS_BRANCH === 'master'
) {
console.log('Syncing Algolia records...');
syncAlgolia();
} else {
console.log('Skipped Algolia sync.');
}
function syncAlgolia() {
const client = algolia(ALGOLIA_APP_ID, process.env.ALGOLIA_ADMIN_KEY);
const index = client.initIndex('icons');
const records = Object.keys(icons).map(name => ({
name,
tags: tags[name] || [],
}));
index.clearIndex((err, content) => {
if (err) throw err;
console.log(content);
index.addObjects(records, (err, content) => {
if (err) throw err;
console.log(content);
});
});
}
| import algolia from 'algoliasearch';
import icons from '../dist/icons.json';
import tags from '../src/tags.json';
const ALGOLIA_APP_ID = '5EEOG744D0';
if (
process.env.TRAVIS_PULL_REQUEST === 'false' &&
process.env.TRAVIS_BRANCH === 'master'
) {
console.log('Syncing Algolia records...');
syncAlgolia();
} else {
console.log('Skipped Algolia sync.');
}
function syncAlgolia() {
const client = algolia(ALGOLIA_APP_ID, process.env.ALGOLIA_ADMIN_KEY);
const index = client.initIndex('icons');
const records = Object.keys(icons).map(name => ({
name,
tags: tags[name] || [],
}));
index.clearIndex((err, content) => {
if (err) throw err;
console.log(content);
});
index.addObjects(records, (err, content) => {
if (err) throw err;
console.log(content);
});
}
|
Add test for empty string | package fortunereader
import (
"testing"
"reflect"
)
func TestFortunes(t *testing.T) {
var tests = []struct {
input string
expected []string
} {
{ "", []string{} },
{ "fortune", []string{"fortune"} },
{ "fortune\n", []string{"fortune\n"} },
{ "fortune\n%\n", []string{"fortune\n"} },
{ "fortune1\n%\nfortune2", []string{"fortune1\n", "fortune2"}},
{ "fortune1\n%\nfortune2\n%\n", []string{"fortune1\n", "fortune2\n"}},
}
for _, tt := range tests {
actual := parseFortunes(tt.input)
if !reflect.DeepEqual(actual, tt.expected) {
t.Errorf("parseFortune(%v): expected %d, got %d", tt.input, tt.expected, actual)
}
}
}
| package fortunereader
import (
"testing"
"reflect"
)
func TestFortunes(t *testing.T) {
var tests = []struct {
input string
expected []string
} {
{ "fortune", []string{"fortune"} },
{ "fortune\n", []string{"fortune\n"} },
{ "fortune\n%\n", []string{"fortune\n"} },
{ "fortune1\n%\nfortune2", []string{"fortune1\n", "fortune2"}},
{ "fortune1\n%\nfortune2\n%\n", []string{"fortune1\n", "fortune2\n"}},
}
for _, tt := range tests {
actual := parseFortunes(tt.input)
if !reflect.DeepEqual(actual, tt.expected) {
t.Errorf("parseFortune(%v): expected %d, got %d", tt.input, tt.expected, actual)
}
}
}
|
[build] Use print instead of Seed.printf during doc build, as it doesn't depend on an installed version of seed | #!/usr/bin/env seed
Seed.include(Seed.argv[2]);
function output_param (param){
print("<varlistentry><term><parameter>" + param.name +
"</parameter></term>" + "<listitem><simpara>" +
param.descripton + "</simpara></listitem></varlistentry>");
}
function output_function (func){
var start = print("<refsect2 id=" + func.id + " role=\"function\">" +
"<title>" + func.title + "</title>" +
"<para>" + func.description + "</para>");
if (func.params || func.returns)
print("<variablelist role=\"params\">");
if (func.params != null){
for (var i = 0; i < func.params.length; i++){
output_param (func.params[i]);
}
}
if (func.returns != null){
print("<varlistentry><term><emphasis>Returns</emphasis></term>" +
"<listitem><simpara>" + func.returns +
"</simpara></listitem></varlistentry>");
}
if (func.params || func.returns)
print("</variablelist>");
print("</refsect2>");
}
print("<para>");
for (var i = 0; i < funcs.length; i++)
{
output_function (funcs[i]);
}
print("</para>");
| #!/usr/bin/env seed
Seed.include(Seed.argv[2]);
function output_param (param){
Seed.printf("<varlistentry><term><parameter>%s</parameter></term>"+
"<listitem><simpara>%s</simpara></listitem></varlistentry>",
param.name,
param.description);
}
function output_function (func){
var start = Seed.printf("<refsect2 id=\"%s\" role=\"function\">"+
"<title>%s</title>"+
"<para>%s</para>",
func.id, func.title, func.description);
if (func.params || func.returns)
print("<variablelist role=\"params\">");
if (func.params != null){
for (var i = 0; i < func.params.length; i++){
output_param (func.params[i]);
}
}
if (func.returns != null){
Seed.printf("<varlistentry><term><emphasis>Returns</emphasis></term>"+
"<listitem><simpara>%s</simpara></listitem></varlistentry>",
func.returns);
}
if (func.params || func.returns)
print("</variablelist>");
print("</refsect2>");
}
print("<para>");
for (var i = 0; i < funcs.length; i++){
output_function (funcs[i]);
}
print("</para>");
|
Fix broken diagnostic dashboard with new sync progress values | from django import template
import json
register = template.Library()
@register.filter(name="format_meters")
def meters_to_kms(value):
try:
return round(value / 1000)
except:
return "NaN"
@register.filter(name='json')
def jsonit(obj):
return json.dumps(obj)
@register.filter(name='dict_get')
def dict_get(tdict, key):
if type(tdict) is not dict:
tdict = tdict.__dict__
return tdict.get(key, None)
@register.filter(name='format')
def format(format, var):
return format.format(var)
@register.simple_tag
def stringformat(value, *args):
return value.format(*args)
@register.filter(name="percentage")
def percentage(value, *args):
if not value:
return "NaN"
try:
return str(round(float(value) * 100)) + "%"
except ValueError:
return value
| from django import template
import json
register = template.Library()
@register.filter(name="format_meters")
def meters_to_kms(value):
try:
return round(value / 1000)
except:
return "NaN"
@register.filter(name='json')
def jsonit(obj):
return json.dumps(obj)
@register.filter(name='dict_get')
def dict_get(tdict, key):
if type(tdict) is not dict:
tdict = tdict.__dict__
return tdict.get(key, None)
@register.filter(name='format')
def format(format, var):
return format.format(var)
@register.simple_tag
def stringformat(value, *args):
return value.format(*args)
@register.filter(name="percentage")
def percentage(value, *args):
if not value:
return "NaN"
return str(round(float(value) * 100)) + "%"
|
Correct test to catch SystemExit on normal exit. | """Usage: prog [-vqr] [FILE]
prog INPUT OUTPUT
prog --help
Options:
-v print status messages
-q report only file names
-r show all occurrences of the same error
--help
"""
from docopt import docopt, Options, Arguments, DocoptExit
from pytest import raises
def test_docopt():
o, a = docopt(__doc__, '-v file.py')
assert o == Options(v=True, q=False, r=False, help=False)
assert a == Arguments(file='file.py', input=None, output=None)
o, a = docopt(__doc__, '-v')
assert o == Options(v=True, q=False, r=False, help=False)
assert a == Arguments(file=None, input=None, output=None)
with raises(DocoptExit): # does not match
docopt(__doc__, '-v input.py output.py')
with raises(DocoptExit):
docopt(__doc__, '--fake')
with raises(SystemExit):
docopt(__doc__, '--hel')
| """Usage: prog [-vqr] [FILE]
prog INPUT OUTPUT
prog --help
Options:
-v print status messages
-q report only file names
-r show all occurrences of the same error
--help
"""
from docopt import docopt, Options, Arguments, DocoptExit
from pytest import raises
def test_docopt():
o, a = docopt(__doc__, '-v file.py')
assert o == Options(v=True, q=False, r=False, help=False)
assert a == Arguments(file='file.py', input=None, output=None)
o, a = docopt(__doc__, '-v')
assert o == Options(v=True, q=False, r=False, help=False)
assert a == Arguments(file=None, input=None, output=None)
with raises(DocoptExit): # does not match
docopt(__doc__, '-v input.py output.py')
with raises(DocoptExit):
docopt(__doc__, '--fake')
with raises(DocoptExit):
docopt(__doc__, '--hel')
|
[FEATURE] Add function to handle new ripple notifications | var Ripple = require('ripple-lib')
var request = require('request')
var address = process.env.RIPPLE_ADDRESS;
var lastTxId = process.env.LAST_TX_ID;
function getNextNotification() {
base = 'http://simple-ripple-listener.herokuapp.com/api/v1/';
url = base + 'address/' + address + '/next_notification/' + lastTxId;
request.get({ url: url, json: true }, function(err, resp, body) {
if (body.notification) {
lastTxId = body.notification.txHash;
handleNewNotification(body.notification);
getNextNotification();
} else {
setTimeout(getNextNotification, 2000);
}
})
}
function handleNewNotification(notification) {
// Inbound
// -- Create ripple transaction
// Outbound
// -- Find and update ripple transaction
console.log(notification);
}
getNextNotification();
| var Ripple = require('ripple-lib')
var request = require('request')
var address = process.env.RIPPLE_ADDRESS || 'rwqhRo41zXZKooNbDNUqQ5dTRrQPQ1BDF7'
var lastTxId = process.env.LAST_TX_ID || 'E0785E2C6F7A7F84E03B05635A15C4992EA65532D650FF5CB4CE18BA3707DAD8';
function getNextNotification() {
base = 'http://simple-ripple-listener.herokuapp.com/api/v1/';
url = base + 'address/' + address + '/next_notification/' + lastTxId;
request.get({ url: url, json: true }, function(err, resp, body) {
if (body.notification) {
lastTxId = body.notification.txHash;
console.log('got a new notification!');
console.log(body.notification);
handleNewNotification(body.notification);
} else {
console.log('no payments, sleep 2 sec');
setTimeout(getNextNotification, 2000);
}
})
}
function handleNewNotification(notification) {
console.log(notification);
getNextNotification();
}
getNextNotification();
|
Use ceil not floor to get the edges | import ROT from "rot-js";
ROT.Display.prototype.drawWorld = function(world, playerPos) {
this.clear();
let curOpts = this.getOptions();
let top = Math.ceil(playerPos.y - curOpts.height / 2);
let bot = Math.ceil(playerPos.y + curOpts.height / 2);
let left = Math.ceil(playerPos.x - curOpts.width / 2);
let right = Math.ceil(playerPos.x + curOpts.width / 2);
for (let i = 0, y = top; y < bot; y++) {
for (let j = 0, x = left; x < right; x++) {
let chunk = world.getChunkFromTile(x, y);
let tile = chunk.getTileFromWorldCoords(x, y);
let symbol, foreground, background;
if (x === playerPos.x && y === playerPos.y) {
foreground = "#fff";
symbol = "X";
} else if (tile.creatures.length) {
symbol = "@";
} else {
foreground = tile.foreground;
symbol = tile.display;
}
this.draw(j, i, symbol, foreground, background);
j++;
}
i++;
}
}
var display = new ROT.Display({
fg: "#daddd8",
bg: "#1e1e1e",
// bg: "#9e9e9e", // For debugging
forceSquareRatio: true
});
export default display;
| import ROT from "rot-js";
ROT.Display.prototype.drawWorld = function(world, playerPos) {
let curOpts = display.getOptions();
let top = Math.floor(playerPos.y - curOpts.height / 2);
let bot = Math.floor(playerPos.y + curOpts.height / 2);
let left = Math.floor(playerPos.x - curOpts.width / 2);
let right = Math.floor(playerPos.x + curOpts.width / 2);
for (let i = 0, y = top; y < bot; y++) {
for (let j = 0, x = left; x < right; x++) {
let chunk = world.getChunkFromTile(x, y);
let tile = chunk.getTileFromWorldCoords(x, y);
if (x === playerPos.x && y === playerPos.y) {
display.draw(j, i, "X", "#fff");
} else if (tile.creatures.length) {
display.draw(j, i, "@");
} else {
display.draw(j, i, tile.display, "#086623");
}
j++;
}
i++;
}
}
var display = new ROT.Display({
fg: "#daddd8",
bg: "#1e1e1e",
// bg: "#9e9e9e", // For debugging
forceSquareRatio: true
});
export default display;
|
v/b-h/d: Refactor to use timezone() helper
Signed-off-by: Kristofer Rye <1ed31cfd0b53bc3d1689a6fee6dbfc9507dffd22@gmail.com> | // @flow
import * as React from 'react'
import type {BuildingType} from '../types'
import {Timer} from '@frogpond/timer'
import {BuildingDetail} from './building'
import {timezone} from '@frogpond/constants'
import type {TopLevelViewPropsType} from '../../types'
import {ConnectedBuildingFavoriteButton as FavoriteButton} from './toolbar-button'
type Props = TopLevelViewPropsType & {
navigation: {state: {params: {building: BuildingType}}},
}
export class BuildingHoursDetailView extends React.Component<Props> {
static navigationOptions = ({navigation}: any) => {
const building = navigation.state.params.building
return {
title: building.name,
headerRight: <FavoriteButton buildingName={building.name} />,
}
}
reportProblem = () => {
this.props.navigation.navigate('BuildingHoursProblemReportView', {
initialBuilding: this.props.navigation.state.params.building,
})
}
render() {
const info = this.props.navigation.state.params.building
return (
<Timer
interval={60000}
moment={true}
render={({now}) => (
<BuildingDetail
info={info}
now={now}
onProblemReport={this.reportProblem}
/>
)}
timezone={timezone()}
/>
)
}
}
| // @flow
import * as React from 'react'
import type {BuildingType} from '../types'
import {Timer} from '@frogpond/timer'
import {BuildingDetail} from './building'
import {CENTRAL_TZ} from '../lib'
import type {TopLevelViewPropsType} from '../../types'
import {ConnectedBuildingFavoriteButton as FavoriteButton} from './toolbar-button'
type Props = TopLevelViewPropsType & {
navigation: {state: {params: {building: BuildingType}}},
}
export class BuildingHoursDetailView extends React.Component<Props> {
static navigationOptions = ({navigation}: any) => {
const building = navigation.state.params.building
return {
title: building.name,
headerRight: <FavoriteButton buildingName={building.name} />,
}
}
reportProblem = () => {
this.props.navigation.navigate('BuildingHoursProblemReportView', {
initialBuilding: this.props.navigation.state.params.building,
})
}
render() {
const info = this.props.navigation.state.params.building
return (
<Timer
interval={60000}
moment={true}
render={({now}) => (
<BuildingDetail
info={info}
now={now}
onProblemReport={this.reportProblem}
/>
)}
timezone={CENTRAL_TZ}
/>
)
}
}
|
Add the answer ID in | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateDiscussionsTable extends Migration
{
public function up()
{
Schema::create('discussions', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id')->unsigned();
$table->integer('topic_id')->unsigned();
$table->string('title');
$table->longText('body');
//$table->string('slug');
$table->bigInteger('answer_id')->unsigned()->nullable();
$table->timestamps();
$table->softDeletes();
});
}
public function down()
{
Schema::dropIfExists('discussions');
}
}
| <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateDiscussionsTable extends Migration
{
public function up()
{
Schema::create('discussions', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id')->unsigned();
$table->integer('topic_id')->unsigned();
$table->string('title');
$table->longText('body');
//$table->string('slug');
$table->timestamps();
$table->softDeletes();
});
}
public function down()
{
Schema::dropIfExists('discussions');
}
}
|
Make mpi an optional dependency | from distutils.core import setup
setup(name="zutil",
version='0.1.5',
description="Utilities used for generating zCFD control dictionaries",
author="Zenotech",
author_email="support@zenotech.com",
url="https://zcfd.zenotech.com/",
packages=["zutil", "zutil.post", "zutil.analysis", "zutil.plot"],
install_requires=[
'ipython<6.0',
'Fabric',
'ipywidgets',
'matplotlib',
'numpy',
'pandas',
'PyYAML'
],
extras_require={
"mpi": ["mpi4py"]
}
)
| from distutils.core import setup
setup(name="zutil",
version='0.1.4',
description="Utilities used for generating zCFD control dictionaries",
author="Zenotech",
author_email="support@zenotech.com",
url="https://zcfd.zenotech.com/",
packages=["zutil", "zutil.post", "zutil.analysis", "zutil.plot"],
install_requires=[
'mpi4py',
'ipython<6.0',
'Fabric',
'ipywidgets',
'matplotlib',
'numpy',
'pandas',
'PyYAML'
],
) |
Fix crash after inganme chat is used | package main
import (
"github.com/gorilla/websocket"
)
type Message struct {
Name string `json:"name"`
Data interface{} `json:"data"`
}
type FindHandler func(string) (Handler, bool)
type Client struct {
send chan Message
socket *websocket.Conn
findHandler FindHandler
stopChannels map[int]chan bool
id string
}
func (client *Client) Read() {
var message Message
for {
if err := client.socket.ReadJSON(&message); err != nil {
break
}
if handler, found := client.findHandler(message.Name); found {
handler(client, message.Data)
}
}
}
func (client *Client) Write() {
for msg := range client.send {
if err := client.socket.WriteJSON(msg); err != nil {
break
}
}
}
func (client *Client) Close() {
for _, ch := range client.stopChannels {
ch <- true
}
close(client.send)
}
func NewClient(socket *websocket.Conn, findHandler FindHandler) *Client {
return &Client{
send: make(chan Message),
socket: socket,
findHandler: findHandler,
stopChannels: make(map[int]chan bool),
}
}
| package main
import (
"github.com/gorilla/websocket"
)
type Message struct {
Name string `json:"name"`
Data interface{} `json:"data"`
}
type FindHandler func(string) (Handler, bool)
type Client struct {
send chan Message
socket *websocket.Conn
findHandler FindHandler
stopChannels map[int]chan bool
id string
}
func (client *Client) Read() {
var message Message
for {
if err := client.socket.ReadJSON(&message); err != nil {
break
}
if handler, found := client.findHandler(message.Name); found {
handler(client, message.Data)
}
}
client.socket.Close()
}
func (client *Client) Write() {
for msg := range client.send {
if err := client.socket.WriteJSON(msg); err != nil {
break
}
}
client.socket.Close()
}
func (client *Client) Close() {
for _, ch := range client.stopChannels {
ch <- true
}
close(client.send)
}
func NewClient(socket *websocket.Conn, findHandler FindHandler) *Client {
return &Client{
send: make(chan Message),
socket: socket,
findHandler: findHandler,
stopChannels: make(map[int]chan bool),
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.