text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Add None if kwargs can not get. | # -*- coding: utf-8 -*-
"""
mackerel.host
~~~~~~~~~~~~~
Mackerel client implemented by Pyton.
Ported from `mackerel-client-ruby`.
<https://github.com/mackerelio/mackerel-client-ruby>
:copyright: (c) 2014 Hatena, All rights reserved.
:copyright: (c) 2015 Shinya Ohyanagi, All rights reserved.
:license: BSD, see LICENSE for more details.
"""
import re
class Host(object):
MACKEREL_INTERFACE_NAME_PATTERN = re.compile(r'^eth\d')
def __init__(self, **kwargs):
self.args = kwargs
self.name = kwargs.get('name', None)
self.meta = kwargs.get('meta', None)
self.type = kwargs.get('type', None)
self.status = kwargs.get('status', None)
self.memo = kwargs.get('memo', None)
self.is_retired = kwargs.get('isRetired', None)
self.id = kwargs.get('id', None)
self.created_at = kwargs.get('createdAt', None)
self.roles = kwargs.get('roles', None)
self.interfaces = kwargs.get('interfaces', None)
def ip_addr(self):
pass
def mac_addr(self):
pass
| # -*- coding: utf-8 -*-
"""
mackerel.host
~~~~~~~~~~~~~
Mackerel client implemented by Pyton.
Ported from `mackerel-client-ruby`.
<https://github.com/mackerelio/mackerel-client-ruby>
:copyright: (c) 2014 Hatena, All rights reserved.
:copyright: (c) 2015 Shinya Ohyanagi, All rights reserved.
:license: BSD, see LICENSE for more details.
"""
import re
class Host(object):
MACKEREL_INTERFACE_NAME_PATTERN = re.compile(r'^eth\d')
def __init__(self, **kwargs):
self.args = kwargs
self.name = kwargs.get('name')
self.meta = kwargs.get('meta')
self.type = kwargs.get('type')
self.status = kwargs.get('status')
self.memo = kwargs.get('memo')
self.is_retired = kwargs.get('isRetired')
self.id = kwargs.get('id')
self.created_at = kwargs.get('createdAt')
self.roles = kwargs.get('roles')
self.interfaces = kwargs.get('interfaces')
def ip_addr(self):
pass
def mac_addr(self):
pass
|
Use Object.assign in Broccoli plugin | 'use strict';
var assign = Object.assign || require('object.assign');
var Filter = require('broccoli-filter'),
postcss = require('postcss'),
util = require('util');
module.exports = PostCSSFilter;
// -----------------------------------------------------------------------------
function PostCSSFilter(inputTree, options) {
if (!(this instanceof PostCSSFilter)) {
return new PostCSSFilter(inputTree, options);
}
this.inputTree = inputTree;
this.options = assign({processors: []}, options);
}
util.inherits(PostCSSFilter, Filter);
PostCSSFilter.prototype.extensions = ['css'];
PostCSSFilter.prototype.targetExtension = 'css';
PostCSSFilter.prototype.processString = function (css, relPath) {
var processor = postcss();
var options = assign({
from: relPath,
to : relPath
}, this.options);
options.processors.forEach(function (p) {
processor.use(p);
});
return processor.process(css, options).css;
};
| 'use strict';
var Filter = require('broccoli-filter'),
objectAssign = require('object-assign'),
postcss = require('postcss'),
util = require('util');
module.exports = PostCSSFilter;
// -----------------------------------------------------------------------------
function PostCSSFilter(inputTree, options) {
if (!(this instanceof PostCSSFilter)) {
return new PostCSSFilter(inputTree, options);
}
this.inputTree = inputTree;
this.options = objectAssign({processors: []}, options);
}
util.inherits(PostCSSFilter, Filter);
PostCSSFilter.prototype.extensions = ['css'];
PostCSSFilter.prototype.targetExtension = 'css';
PostCSSFilter.prototype.processString = function (css, relPath) {
var processor = postcss();
var options = objectAssign({
from: relPath,
to : relPath
}, this.options);
options.processors.forEach(function (p) {
processor.use(p);
});
return processor.process(css, options).css;
};
|
Remove the code to filter user login.
:) | <?php
/*
* In configuration file
* ...
* 'as AccessBehavior' => [
* 'class' => '\app\components\AccessBehavior'
* ]
* ...
* (c) Artem Voitko <r3verser@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace app\components;
use yii\base\Behavior;
use yii\console\Controller;
use yii\helpers\Url;
/**
* Redirects all users to login page if not logged in
*
* Class AccessBehavior
* @package app\components
* @author Artem Voitko <r3verser@gmail.com>
*/
class AccessBehavior extends Behavior
{
/**
* Subscribe for events
* @return array
*/
public function events()
{
return [
Controller::EVENT_BEFORE_ACTION => 'beforeAction'
];
}
/**
* On event callback
*/
public function beforeAction()
{
// if (\Yii::$app->getUser()->isGuest &&
// \Yii::$app->getRequest()->url !== Url::to(\Yii::$app->getUser()->loginUrl)
// ) {
// \Yii::$app->getResponse()->redirect(\Yii::$app->getUser()->loginUrl);
// }
}
} | <?php
/*
* In configuration file
* ...
* 'as AccessBehavior' => [
* 'class' => '\app\components\AccessBehavior'
* ]
* ...
* (c) Artem Voitko <r3verser@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace app\components;
use yii\base\Behavior;
use yii\console\Controller;
use yii\helpers\Url;
/**
* Redirects all users to login page if not logged in
*
* Class AccessBehavior
* @package app\components
* @author Artem Voitko <r3verser@gmail.com>
*/
class AccessBehavior extends Behavior
{
/**
* Subscribe for events
* @return array
*/
public function events()
{
return [
Controller::EVENT_BEFORE_ACTION => 'beforeAction'
];
}
/**
* On event callback
*/
public function beforeAction()
{
if (\Yii::$app->getUser()->isGuest &&
\Yii::$app->getRequest()->url !== Url::to(\Yii::$app->getUser()->loginUrl)
) {
\Yii::$app->getResponse()->redirect(\Yii::$app->getUser()->loginUrl);
}
}
} |
Fix migration: don't use virtual field scope. | from django.core.exceptions import ObjectDoesNotExist
from django.db import migrations
def fill_tenant_id(apps, schema_editor):
ServiceSettings = apps.get_model('structure', 'ServiceSettings')
Tenant = apps.get_model('openstack', 'Tenant')
for service_settings in ServiceSettings.objects.filter(type='OpenStackTenant'):
if not service_settings.object_id:
continue
try:
tenant = Tenant.objects.get(id=service_settings.object_id)
except ObjectDoesNotExist:
pass
else:
if tenant.backend_id and not service_settings.options.get('tenant_id'):
service_settings.options['tenant_id'] = tenant.backend_id
service_settings.save(update_fields=['options'])
class Migration(migrations.Migration):
dependencies = [
('openstack_tenant', '0003_extend_description_limits'),
]
operations = [
migrations.RunPython(fill_tenant_id),
]
| from django.db import migrations
def fill_tenant_id(apps, schema_editor):
ServiceSettings = apps.get_model('structure', 'ServiceSettings')
for service_settings in ServiceSettings.objects.filter(type='OpenStackTenant'):
tenant = service_settings.scope
if (
tenant
and tenant.backend_id
and not service_settings.options.get('tenant_id')
):
service_settings.options['tenant_id'] = tenant.backend_id
service_settings.save(update_fields=['options'])
class Migration(migrations.Migration):
dependencies = [
('openstack_tenant', '0003_extend_description_limits'),
]
operations = [
migrations.RunPython(fill_tenant_id),
]
|
Fix widget sizes to actually fit a 5x3 grid. | var RCSS = require("rcss");
var _ = require("underscore");
var styleVars = require("./style-vars.js");
var gridSpacing = 15;
var nWide = 5;
var nTall = 3;
var baseComponentWidth = (styleVars.dashboardWidthPx - (nWide + 1) *
gridSpacing)/nWide;
var baseComponentHeight = (styleVars.dashboardHeightPx - (nTall + 1) *
gridSpacing)/nTall;
var widgetStyleBase = {
position: 'relative',
marginTop: gridSpacing + 'px',
marginLeft: gridSpacing + 'px',
float: 'left',
width: baseComponentWidth + 'px',
height: baseComponentHeight + 'px',
overflow: 'hidden',
}
var doubleWideWidget = _.defaults({
width: (2*baseComponentWidth + gridSpacing) + 'px',
}, widgetStyleBase);
var doubleTallWidget = _.defaults({
height: (2*baseComponentHeight + gridSpacing) + 'px',
}, widgetStyleBase);
var doubleDoubleWidget = _.defaults({
width: (2*baseComponentWidth + gridSpacing) + 'px',
height: (2*baseComponentHeight + gridSpacing) + 'px',
}, widgetStyleBase);
module.exports = {
singleSize: RCSS.registerClass(widgetStyleBase),
doubleWide: RCSS.registerClass(doubleWideWidget),
doubleTall: RCSS.registerClass(doubleTallWidget),
doubleDouble: RCSS.registerClass(doubleDoubleWidget),
}
| var RCSS = require("rcss");
var _ = require("underscore");
var styleVars = require("./style-vars.js");
var gridSpacing = 15;
var nWide = 5;
var baseComponentSize = (styleVars.dashboardWidthPx - (nWide + 1) *
gridSpacing)/nWide;
var widgetStyleBase = {
position: 'relative',
marginTop: gridSpacing + 'px',
marginLeft: gridSpacing + 'px',
float: 'left',
width: baseComponentSize + 'px',
height: baseComponentSize + 'px',
overflow: 'hidden',
}
var doubleWideWidget = _.defaults({
width: (2*baseComponentSize + gridSpacing) + 'px',
}, widgetStyleBase);
var doubleTallWidget = _.defaults({
height: (2*baseComponentSize + gridSpacing) + 'px',
}, widgetStyleBase);
var doubleDoubleWidget = _.defaults({
width: (2*baseComponentSize + gridSpacing) + 'px',
height: (2*baseComponentSize + gridSpacing) + 'px',
}, widgetStyleBase);
module.exports = {
singleSize: RCSS.registerClass(widgetStyleBase),
doubleWide: RCSS.registerClass(doubleWideWidget),
doubleTall: RCSS.registerClass(doubleTallWidget),
doubleDouble: RCSS.registerClass(doubleDoubleWidget),
}
|
Add proper default values to config (although hardcoded). | """
This module is responsible for handling configuration and files related to it,
including calibration parameters.
"""
import configparser
import os
"""
Default options
"""
#TODO: more default options...
_CONFIG_DEFAULTS = {
"paths": {
# default database path is ../db/test.db relative to this file
"db_path": os.path.join(
os.path.dirname(os.path.dirname(__file__)),
"db/test.db"),
},
}
"""
Initialize a configparser dictionary with given or default filename and
return it
"""
def get_config_dict(filename = None):
if filename is None:
cfg_path = os.path.dirname(__file__)
filename = os.path.join(cfg_path, "config.ini")
cp = configparser.ConfigParser() #_CONFIG_DEFAULTS)
# read default values from dict
cp.read_dict(_CONFIG_DEFAULTS)
#TODO: use logging instead of print...
print("Using configuration file " + filename)
cp.read(filename)
return cp
#def __getitem__(self, i): self.configparser.
if __name__ == "__main__":
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("-c", "--config",
dest = "config_file",
help = "use CONFIG_FILE as the configuration file instead of the default")
args = ap.parse_args()
cfg = get_config_dict(args.config_file)
print(str(cfg))
| """
This module is responsible for handling configuration and files related to it,
including calibration parameters.
"""
import configparser
import os
"""
Default options
"""
#TODO: format this to match the dicts generated by configparser from files.
#TODO: more default options...
_CONFIG_DEFAULTS = {
# default database path is ../db/test.db relative to this file
"db_path": os.path.join(
os.path.dirname(os.path.dirname(__file__)),
"db/test.db")
}
"""
Initialize a configparser dictionary with given or default filename and
return it
"""
def get_config_dict(filename = None):
if filename is None:
cfg_path = os.path.dirname(__file__)
filename = os.path.join(cfg_path, "config.ini")
cp = configparser.ConfigParser(_CONFIG_DEFAULTS)
#TODO: use logging instead of print...
print("Using configuration file " + filename)
cp.read(filename)
return cp
#def __getitem__(self, i): self.configparser.
if __name__ == "__main__":
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("-c", "--config",
dest = "config_file",
help = "use CONFIG_FILE as the configuration file instead of the default")
args = ap.parse_args()
cfg = get_config_dict(args.config_file)
print(str(cfg))
|
Disable tests on beta/canary builds
These are failing and the code hasn't been updated to support them yet.
When I get time to investigate why they are failing then I will revert
this commit. Till then I will disable them. | module.exports = {
scenarios: [
{
name: 'default',
dependencies: { }
},
{
name: 'ember-release',
dependencies: {
'ember': 'components/ember#release'
},
resolutions: {
'ember': 'release'
}
}
/* TODO: Skipping, Current code does not work on beta/canary builds yet.
{
name: 'ember-beta',
dependencies: {
'ember': 'components/ember#beta'
},
resolutions: {
'ember': 'beta'
}
},
{
name: 'ember-canary',
dependencies: {
'ember': 'components/ember#canary'
},
resolutions: {
'ember': 'canary'
}
}
*/
]
};
| module.exports = {
scenarios: [
{
name: 'default',
dependencies: { }
},
{
name: 'ember-release',
dependencies: {
'ember': 'components/ember#release'
},
resolutions: {
'ember': 'release'
}
},
{
name: 'ember-beta',
dependencies: {
'ember': 'components/ember#beta'
},
resolutions: {
'ember': 'beta'
}
},
{
name: 'ember-canary',
dependencies: {
'ember': 'components/ember#canary'
},
resolutions: {
'ember': 'canary'
}
}
]
};
|
Convert login tab to react-intl | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
class LoginTab extends Component {
static propTypes = {
activeTab: PropTypes.string.isRequired,
label: PropTypes.string.isRequired,
onClick: PropTypes.func.isRequired,
hideOnMobile: PropTypes.string.isRequired,
};
onClick = () => {
const { label, onClick } = this.props;
onClick(label);
};
render() {
const {
onClick,
props: { activeTab, label, hideOnMobile },
} = this;
let className = 'tab-list-item';
if (activeTab === label) {
className += ' tab-list-active';
}
if (hideOnMobile === 'true') {
className += ' d-none d-md-table-cell';
}
return (
<button type="button" className={className} onClick={onClick}>
<FormattedMessage id={label} />
</button>
);
}
}
export default LoginTab;
| import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Message } from 'retranslate';
class LoginTab extends Component {
static propTypes = {
activeTab: PropTypes.string.isRequired,
label: PropTypes.string.isRequired,
onClick: PropTypes.func.isRequired,
hideOnMobile: PropTypes.string.isRequired,
};
onClick = () => {
const { label, onClick } = this.props;
onClick(label);
};
render() {
const {
onClick,
props: { activeTab, label, hideOnMobile },
} = this;
let className = 'tab-list-item';
if (activeTab === label) {
className += ' tab-list-active';
}
if (hideOnMobile === 'true') {
className += ' d-none d-md-table-cell';
}
return (
<button type="button" className={className} onClick={onClick}>
<Message>{label}</Message>
</button>
);
}
}
export default LoginTab;
|
Add TestVarSnap as a TestCase | import unittest
from varsnap import TestVarSnap # noqa: F401
from app import serve
class PageCase(unittest.TestCase):
def setUp(self):
serve.app.config['TESTING'] = True
self.app = serve.app.test_client()
def test_index_load(self):
self.page_test('/', b'')
def test_robots_load(self):
self.page_test('/robots.txt', b'')
def test_sitemap_load(self):
self.page_test('/sitemap.xml', b'')
def test_not_found(self):
response = self.app.get('/asdf')
self.assertEqual(response.status_code, 404)
self.assertIn(b'Not Found', response.get_data())
def page_test(self, path, string):
response = self.app.get(path)
self.assertEqual(response.status_code, 200)
self.assertIn(string, response.get_data())
| import unittest
from app import serve
class PageCase(unittest.TestCase):
def setUp(self):
serve.app.config['TESTING'] = True
self.app = serve.app.test_client()
def test_index_load(self):
self.page_test('/', b'')
def test_robots_load(self):
self.page_test('/robots.txt', b'')
def test_sitemap_load(self):
self.page_test('/sitemap.xml', b'')
def test_not_found(self):
response = self.app.get('/asdf')
self.assertEqual(response.status_code, 404)
self.assertIn(b'Not Found', response.get_data())
def page_test(self, path, string):
response = self.app.get(path)
self.assertEqual(response.status_code, 200)
self.assertIn(string, response.get_data())
|
Remove process.emitWarning because it breaks AppVeyor builds
See Level/leveldown#660 | function testCommon (options) {
var factory = options.factory
var test = options.test
if (typeof factory !== 'function') {
throw new TypeError('factory must be a function')
}
if (typeof test !== 'function') {
throw new TypeError('test must be a function')
}
return {
test: test,
factory: factory,
setUp: options.setUp || noopTest(),
tearDown: options.tearDown || noopTest(),
bufferKeys: options.bufferKeys !== false,
createIfMissing: options.createIfMissing !== false,
errorIfExists: options.errorIfExists !== false,
snapshots: options.snapshots !== false,
seek: options.seek !== false,
clear: !!options.clear
}
}
function noopTest () {
return function (t) {
t.end()
}
}
module.exports = testCommon
| var warned = false
function testCommon (options) {
var factory = options.factory
var test = options.test
var clear = !!options.clear
if (typeof factory !== 'function') {
throw new TypeError('factory must be a function')
}
if (typeof test !== 'function') {
throw new TypeError('test must be a function')
}
if (!clear && !warned) {
warned = true
warn(
'A next major release of abstract-leveldown will make support of ' +
'clear() mandatory. Prepare by enabling the tests and implementing a ' +
'custom _clear() if necessary. See the README for details.'
)
}
return {
test: test,
factory: factory,
setUp: options.setUp || noopTest(),
tearDown: options.tearDown || noopTest(),
bufferKeys: options.bufferKeys !== false,
createIfMissing: options.createIfMissing !== false,
errorIfExists: options.errorIfExists !== false,
snapshots: options.snapshots !== false,
seek: options.seek !== false,
clear: clear
}
}
function warn (msg) {
if (typeof process !== 'undefined' && process && process.emitWarning) {
process.emitWarning(msg)
} else if (typeof console !== 'undefined' && console && console.warn) {
console.warn('Warning: ' + msg)
}
}
function noopTest () {
return function (t) {
t.end()
}
}
module.exports = testCommon
|
Update to just look at ethwe for the example | package main
import (
"bytes"
"fmt"
"github.com/gorilla/mux"
"log"
"net"
"net/http"
)
func main() {
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/", HelloWeave)
router.HandleFunc("/myip", myIp)
log.Fatal(http.ListenAndServe(":80", router))
}
func HelloWeave(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Welcome!")
}
func myIp(w http.ResponseWriter, r *http.Request) {
var theIps bytes.Buffer
ief, _ := net.InterfaceByName("ethwe")
addrs, _ := ief.Addrs()
for _, a := range addrs {
if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
theIps.WriteString(ipnet.IP.String())
}
}
fmt.Fprintln(w, theIps.String())
}
| package main
import (
"bytes"
"fmt"
"github.com/gorilla/mux"
"log"
"net"
"net/http"
)
func main() {
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/", HelloWeave)
router.HandleFunc("/myip", myIp)
log.Fatal(http.ListenAndServe(":80", router))
}
func HelloWeave(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Welcome!")
}
func myIp(w http.ResponseWriter, r *http.Request) {
var theIps bytes.Buffer
addrs, _ := net.InterfaceAddrs()
for _, a := range addrs {
if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
theIps.WriteString(ipnet.IP.String())
theIps.WriteString("\n")
}
}
fmt.Fprintln(w, theIps.String())
}
|
fix(cmds): Fix commands without descriptions causing crash on plugin load | package valandur.webapi.cache;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.spongepowered.api.command.CommandMapping;
import org.spongepowered.api.text.Text;
import valandur.webapi.misc.WebAPICommandSource;
import java.util.Optional;
public class CachedCommand extends CachedObject {
@JsonProperty
public String name;
@JsonProperty
public String description;
public Object[] aliases;
public String usage;
public String help;
public static CachedCommand copyFrom(CommandMapping cmd) {
CachedCommand cache = new CachedCommand();
cache.name = cmd.getPrimaryAlias();
cache.aliases = cmd.getAllAliases().toArray();
cache.usage = cmd.getCallable().getUsage(WebAPICommandSource.instance).toPlain();
cache.description = cmd.getCallable().getShortDescription(WebAPICommandSource.instance).orElse(Text.EMPTY).toPlain();
cache.help = cmd.getCallable().getHelp(WebAPICommandSource.instance).orElse(Text.EMPTY).toPlain();
return cache;
}
@Override
@JsonProperty
public String getLink() {
return "/api/cmd/" + name;
}
}
| package valandur.webapi.cache;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.spongepowered.api.command.CommandMapping;
import valandur.webapi.misc.WebAPICommandSource;
import java.util.Optional;
public class CachedCommand extends CachedObject {
@JsonProperty
public String name;
@JsonProperty
public String description;
public Object[] aliases;
public String usage;
public String help;
public static CachedCommand copyFrom(CommandMapping cmd) {
CachedCommand cache = new CachedCommand();
cache.name = cmd.getPrimaryAlias();
cache.aliases = cmd.getAllAliases().toArray();
cache.usage = cmd.getCallable().getUsage(WebAPICommandSource.instance).toPlain();
cache.description = cmd.getCallable().getShortDescription(WebAPICommandSource.instance).orElse(null).toPlain();
cache.help = cmd.getCallable().getHelp(WebAPICommandSource.instance).orElse(null).toPlain();
return cache;
}
@Override
@JsonProperty
public String getLink() {
return "/api/cmd/" + name;
}
}
|
Check that response is not a StreamingResponse. | """
Middleware for injecting the live-reload script.
"""
from bs4 import BeautifulSoup
from django.utils.encoding import smart_str
from django.conf import settings
from livereload import livereload_port
class LiveReloadScript(object):
"""
Injects the live-reload script into your webpages.
"""
def process_response(self, request, response):
content_type = response.get('Content-Type', '').split(';')[0].strip().lower()
if (not settings.DEBUG or
content_type not in ['text/html', 'application/xhtml+xml'] or
not hasattr(response, 'content')):
return response
soup = BeautifulSoup(
smart_str(response.content),
'html.parser',
)
if not getattr(soup, 'head', None):
return response
script = soup.new_tag(
'script', src='http://localhost:%d/livereload.js' % livereload_port(),
)
soup.head.append(script)
response.content = str(soup)
return response
| """
Middleware for injecting the live-reload script.
"""
from bs4 import BeautifulSoup
from django.utils.encoding import smart_str
from django.conf import settings
from livereload import livereload_port
class LiveReloadScript(object):
"""
Inject the live-reload script into your webpages.
"""
def process_response(self, request, response):
content_type = response.get('Content-Type', '').split(';')[0].strip().lower()
if content_type not in ['text/html', 'application/xhtml+xml'] or settings.DEBUG == False:
return response
soup = BeautifulSoup(
smart_str(response.content),
'html.parser',
)
if not getattr(soup, 'head', None):
return response
script = soup.new_tag(
'script', src='http://localhost:%d/livereload.js' % livereload_port(),
)
soup.head.append(script)
response.content = str(soup)
return response
|
Allow some listener changes after init.
You’re not allowed to modify start event listeners after the transition is
scheduled, so as to avoid changes during a start event (due to changes being
copy-on-write). However, you should still be allowed to change the OTHER event
listeners (interrupt and end) before the transition starts; in particular,
transition.remove should be allowed during a start event! | import {get, set, init} from "./schedule";
function start(name) {
return (name + "").trim().split(/^|\s+/).every(function(t) {
var i = t.indexOf(".");
if (i >= 0) t = t.slice(0, i);
return !t || t === "start";
});
}
function onFunction(key, id, name, listener) {
if (typeof listener !== "function") throw new Error;
var on0, on1, sit = start(name) ? init : set;
return function() {
var schedule = sit(this, key, id),
on = schedule.on;
// If this node shared a dispatch with the previous node,
// just assign the updated shared dispatch and we’re done!
// Otherwise, copy-on-write.
if (on !== on0) (on1 = (on0 = on).copy()).on(name, listener);
schedule.on = on1;
};
}
export default function(name, listener) {
var key = this._key,
id = this._id;
return arguments.length < 2
? get(this.node(), key, id).on.on(name)
: this.each(onFunction(key, id, name, listener));
}
| import {get, init} from "./schedule";
function onFunction(key, id, name, listener) {
if (typeof listener !== "function") throw new Error;
var on0, on1;
return function() {
var schedule = init(this, key, id),
on = schedule.on;
// If this node shared a dispatch with the previous node,
// just assign the updated shared dispatch and we’re done!
// Otherwise, copy-on-write.
if (on !== on0) (on1 = (on0 = on).copy()).on(name, listener);
schedule.on = on1;
};
}
export default function(name, listener) {
var key = this._key,
id = this._id;
return arguments.length < 2
? get(this.node(), key, id).on.on(name)
: this.each(onFunction(key, id, name, listener));
}
|
Fix unresponsive button on collaborations page
fixes VICE-2428
flag=none
Test Plan:
- see repro steps on linked ticket
- should not be able to repro
- go to /courses/<course_id>/collaborations
- click the "add collaboration" button
- if button is responsive refreshpage
- repeat 15 times
- if button is unresponsive leave a QA-1 and a comment
Change-Id: Ia834d6dd5371c38d0ee6bd6d9fb422c12f94d763
Reviewed-on: https://gerrit.instructure.com/c/canvas-lms/+/284877
Tested-by: Service Cloud Jenkins <9144042a601061f88f1e1d7a1753ea3e2972119d@instructure.com>
Reviewed-by: Omar Soto-Fortuño <2ca100155bc0669318a7e6f3850629c7667465e1@instructure.com>
Product-Review: Omar Soto-Fortuño <2ca100155bc0669318a7e6f3850629c7667465e1@instructure.com>
QA-Review: Jeffrey Johnson <7a0f98bfe168bc29d5611ba0275e88567b492abc@instructure.com> | /*
* Copyright (C) 2011 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import $ from 'jquery'
import ready from '@instructure/ready'
import CollaborationsPage from './backbone/views/CollaborationsPage.coffee'
import './jquery/index'
// eslint-disable-next-line import/extensions
import '../../boot/initializers/activateKeyClicks.js'
ready(() => {
const page = new CollaborationsPage({el: $('body')})
page.initPageState()
})
| /*
* Copyright (C) 2011 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import $ from 'jquery'
import CollaborationsPage from './backbone/views/CollaborationsPage.coffee'
import './jquery/index'
import '../../boot/initializers/activateKeyClicks.js'
const page = new CollaborationsPage({el: $('body')})
page.initPageState()
|
Update copyright years of the interpreter | import help_formatter
import argparse
def process_options():
parser = _make_options_parser()
return parser.parse_args()
def _make_options_parser():
parser = argparse.ArgumentParser(
prog='micro',
add_help=False,
formatter_class=help_formatter.HelpFormatter
)
parser.add_argument(
'-v',
'--version',
action='version',
help='- show the version message and exit',
version='Micro interpreter, v2.1\nCopyright (c) 2016, 2017 thewizardplusplus'
)
parser.add_argument(
'-h',
'--help',
action='help',
help='- show the help message and exit'
)
parser.add_argument(
'-t',
'--target',
choices=['tokens', 'preast', 'ast', 'evaluation'],
default='evaluation',
help='- set a target of a script processing'
)
parser.add_argument('script', nargs='?', default='-', help='- a script')
parser.add_argument(
'args',
nargs='*',
default=[],
help='- script arguments'
)
return parser
if __name__ == '__main__':
options = process_options()
print(options)
| import help_formatter
import argparse
def process_options():
parser = _make_options_parser()
return parser.parse_args()
def _make_options_parser():
parser = argparse.ArgumentParser(
prog='micro',
add_help=False,
formatter_class=help_formatter.HelpFormatter
)
parser.add_argument(
'-v',
'--version',
action='version',
help='- show the version message and exit',
version='Micro interpreter, v2.1\nCopyright (c) 2016 thewizardplusplus'
)
parser.add_argument(
'-h',
'--help',
action='help',
help='- show the help message and exit'
)
parser.add_argument(
'-t',
'--target',
choices=['tokens', 'preast', 'ast', 'evaluation'],
default='evaluation',
help='- set a target of a script processing'
)
parser.add_argument('script', nargs='?', default='-', help='- a script')
parser.add_argument(
'args',
nargs='*',
default=[],
help='- script arguments'
)
return parser
if __name__ == '__main__':
options = process_options()
print(options)
|
Allow custom session object for the requests backend. | # -*- coding: utf-8 -*-
import requests
class HttpClient(object):
"""A HTTP client using requests"""
default_options = dict(verify=False, allow_redirects=False)
def __init__(self, chunk_size=1024 * 24, session=None, **requests_options):
options = self.default_options.copy()
options.update(requests_options)
self.options = options
self.chunk_size = chunk_size
if session is None:
session = requests.sessions.Session()
self.session = session
def __call__(self, uri, method, body, headers):
kwargs = self.options.copy()
kwargs['headers'] = headers
if 'Transfer-Encoding' in headers:
del headers['Transfer-Encoding']
if headers.get('Content-Length'):
kwargs['data'] = body.read(int(headers['Content-Length']))
response = self.session.request(method, uri, **kwargs)
location = response.headers.get('location') or None
status = '%s %s' % (response.status_code, response.reason)
headers = [(k.title(), v) for k, v in response.headers.items()]
return (status, location, headers,
response.iter_content(chunk_size=self.chunk_size))
| # -*- coding: utf-8 -*-
import requests
class HttpClient(object):
"""A HTTP client using requests"""
default_options = dict(verify=False, allow_redirects=False)
def __init__(self, chunk_size=1024 * 24, **requests_options):
options = self.default_options.copy()
options.update(requests_options)
self.options = options
self.chunk_size = chunk_size
def __call__(self, uri, method, body, headers):
kwargs = self.options.copy()
kwargs['headers'] = headers
if 'Transfer-Encoding' in headers:
del headers['Transfer-Encoding']
if headers.get('Content-Length'):
kwargs['data'] = body.read(int(headers['Content-Length']))
response = requests.request(method, uri, **kwargs)
location = response.headers.get('location') or None
status = '%s %s' % (response.status_code, response.reason)
headers = [(k.title(), v) for k, v in response.headers.items()]
return (status, location, headers,
response.iter_content(chunk_size=self.chunk_size))
|
Fix IE < 9's idea that isn't whitespace. | /*
* jquery.textnodes
*
*
* Copyright (c) 2014 Mark Florian
* Licensed under the MIT license.
*/
(function($) {
// Match anything that isn't whitespace or the non-breaking space,
// which IE < 9 does not consider whitespace.
var rNonWhiteSpace = /[^\s\u00a0]/;
function getChildTextNodes($el, list, includeWhiteSpace) {
$el.contents().each(function () {
var isNonWhiteSpace;
if (this.nodeType === 3) {
isNonWhiteSpace = rNonWhiteSpace.test(this.nodeValue);
if (isNonWhiteSpace || includeWhiteSpace) {
list.push(this);
}
} else if (this.nodeType === 1) {
getChildTextNodes($(this), list, includeWhiteSpace);
}
return list;
});
}
$.fn.textNodes = function (includeWhiteSpace) {
var textNodes = [];
getChildTextNodes(this, textNodes, includeWhiteSpace);
return $(textNodes);
};
}(jQuery));
| /*
* jquery.textnodes
*
*
* Copyright (c) 2014 Mark Florian
* Licensed under the MIT license.
*/
(function($) {
var rNonWhiteSpace = /\S/;
function getChildTextNodes($el, list, includeWhiteSpace) {
$el.contents().each(function () {
var isNonWhiteSpace;
if (this.nodeType === 3) {
isNonWhiteSpace = rNonWhiteSpace.test(this.nodeValue);
if (isNonWhiteSpace || includeWhiteSpace) {
list.push(this);
}
} else if (this.nodeType === 1) {
getChildTextNodes($(this), list, includeWhiteSpace);
}
return list;
});
}
$.fn.textNodes = function (includeWhiteSpace) {
var textNodes = [];
getChildTextNodes(this, textNodes, includeWhiteSpace);
return $(textNodes);
};
}(jQuery));
|
Use RubyLinter instead of Linter so rbenv and rvm are supported | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Sergey Margaritov
# Copyright (c) 2013 Sergey Margaritov
#
# License: MIT
#
"""This module exports the scss-lint plugin linter class."""
import os
from SublimeLinter.lint import RubyLinter, util
class Scss(RubyLinter):
"""Provides an interface to the scss-lint executable."""
syntax = ('sass', 'scss')
executable = 'scss-lint'
regex = r'^.+?:(?P<line>\d+) (?:(?P<error>\[E\])|(?P<warning>\[W\])) (?P<message>[^`]*(?:`(?P<near>.+?)`)?.*)'
tempfile_suffix = 'scss'
defaults = {
'--include-linter:,': '',
'--exclude-linter:,': ''
}
inline_overrides = ('bundle-exec', 'include-linter', 'exclude-linter')
comment_re = r'^\s*/[/\*]'
config_file = ('--config', '.scss-lint.yml', '~')
def cmd(self):
if self.get_view_settings().get('bundle-exec', False):
return ('bundle', 'exec', self.executable)
return (self.executable_path) | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Sergey Margaritov
# Copyright (c) 2013 Sergey Margaritov
#
# License: MIT
#
"""This module exports the scss-lint plugin linter class."""
import os
from SublimeLinter.lint import Linter, util
class Scss(Linter):
"""Provides an interface to the scss-lint executable."""
syntax = ['sass', 'scss']
executable = 'scss-lint'
regex = r'^.+?:(?P<line>\d+) (?:(?P<error>\[E\])|(?P<warning>\[W\])) (?P<message>[^`]*(?:`(?P<near>.+?)`)?.*)'
tempfile_suffix = 'scss'
defaults = {
'--include-linter:,': '',
'--exclude-linter:,': ''
}
inline_overrides = ('bundle-exec', 'include-linter', 'exclude-linter')
comment_re = r'^\s*/[/\*]'
config_file = ('--config', '.scss-lint.yml', '~')
def cmd(self):
if self.get_view_settings().get('bundle-exec', False):
return ['bundle', 'exec', self.executable]
return [self.executable_path] |
Update project brian to use new ONSDigital repo location. | package com.github.davidcanboni.jenkins.values;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by david on 15/07/2015.
*/
public enum GitRepo {
babbage("https://github.com/ONSdigital/babbage.git", true),
florence("https://github.com/ONSdigital/florence.git", true),
zebedee("https://github.com/Carboni/zebedee.git"),
zebedeeReader("https://github.com/Carboni/zebedee.git", false, true),
brian("https://github.com/ONSdigital/project-brian.git"),
thetrain("https://github.com/Carboni/The-Train.git");
public URL url;
public boolean nodeJs;
public boolean submodule;
GitRepo(String url, boolean... parameters) {
try {
this.url = new URL(url);
if (parameters.length > 0) this.nodeJs = parameters[0];
if (parameters.length > 1) this.submodule = parameters[1];
} catch (MalformedURLException e) {
throw new RuntimeException("Error in url: " + url, e);
}
}
@Override
public String toString() {
// Transform zebedeeReader into zebedee-reader:
return name().replace("R", "-r");
}
}
| package com.github.davidcanboni.jenkins.values;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by david on 15/07/2015.
*/
public enum GitRepo {
babbage("https://github.com/ONSdigital/babbage.git", true),
florence("https://github.com/ONSdigital/florence.git", true),
zebedee("https://github.com/Carboni/zebedee.git"),
zebedeeReader("https://github.com/Carboni/zebedee.git", false, true),
brian("https://github.com/thomasridd/project-brian.git"),
thetrain("https://github.com/Carboni/The-Train.git");
public URL url;
public boolean nodeJs;
public boolean submodule;
GitRepo(String url, boolean... parameters) {
try {
this.url = new URL(url);
if (parameters.length > 0) this.nodeJs = parameters[0];
if (parameters.length > 1) this.submodule = parameters[1];
} catch (MalformedURLException e) {
throw new RuntimeException("Error in url: " + url, e);
}
}
@Override
public String toString() {
// Transform zebedeeReader into zebedee-reader:
return name().replace("R", "-r");
}
}
|
Make SessionKeyValueStore variable names clearer | from xblock.runtime import KeyValueStore, InvalidScopeError
class SessionKeyValueStore(KeyValueStore):
def __init__(self, request, descriptor_model_data):
self._descriptor_model_data = descriptor_model_data
self._session = request.session
def get(self, key):
try:
return self._descriptor_model_data[key.field_name]
except (KeyError, InvalidScopeError):
return self._session[tuple(key)]
def set(self, key, value):
try:
self._descriptor_model_data[key.field_name] = value
except (KeyError, InvalidScopeError):
self._session[tuple(key)] = value
def delete(self, key):
try:
del self._descriptor_model_data[key.field_name]
except (KeyError, InvalidScopeError):
del self._session[tuple(key)]
def has(self, key):
return key in self._descriptor_model_data or key in self._session
| from xblock.runtime import KeyValueStore, InvalidScopeError
class SessionKeyValueStore(KeyValueStore):
def __init__(self, request, model_data):
self._model_data = model_data
self._session = request.session
def get(self, key):
try:
return self._model_data[key.field_name]
except (KeyError, InvalidScopeError):
return self._session[tuple(key)]
def set(self, key, value):
try:
self._model_data[key.field_name] = value
except (KeyError, InvalidScopeError):
self._session[tuple(key)] = value
def delete(self, key):
try:
del self._model_data[key.field_name]
except (KeyError, InvalidScopeError):
del self._session[tuple(key)]
def has(self, key):
return key in self._model_data or key in self._session
|
Add file path to json | <?php
// reads files from specified path and returns them as an json-array
// takes one argument from GET variables, does not work without it
// the argument should come from http call to directories.php
header("Content-Type: application/json");
if(isset($_GET['dir']) && $_GET['dir'] != ""){
$directory = urldecode($_GET['dir']);
if(strlen($directory) == 8 && preg_match('/[[:digit:]]{8}/', $directory)){
$files = @scandir($dir = '../incoming/' . $directory . '/converted/');
if ($files && is_array($files)) {
$result = array();
foreach ($files as $file) {
if(!is_dir($entry = $dir . $file)){
$result['files'][]['name'] = $file;
$result['files'][]['path'] = str_replace("../", "", $dir) . $file;
}
}
echo json_encode($result);
}
}
}
| <?php
// reads files from specified path and returns them as an json-array
// takes one argument from GET variables, does not work without it
// the argument should come from http call to directories.php
header("Content-Type: application/json");
if(isset($_GET['dir']) && $_GET['dir'] != ""){
$directory = urldecode($_GET['dir']);
if(strlen($directory) == 8 && preg_match('/[[:digit:]]{8}/', $directory)){
$files = @scandir($dir = '../incoming/' . $directory . '/converted/');
if ($files && is_array($files)) {
$result = array();
foreach ($files as $file) {
if(!is_dir($entry = $dir . $file)){
$result['files'][]['name'] = $file;
}
}
echo json_encode($result);
}
}
}
|
Format (up to 120 line length).
git-svn-id: de5ce936019686f47409c93bcc5e202a9739563b@1514259 13f79535-47bb-0310-9956-ffa450edef68 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache license, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the license for the specific language governing permissions and
* limitations under the license.
*/
package org.apache.logging.log4j.spi;
import java.util.Collection;
import org.apache.logging.log4j.ThreadContext;
/**
*
*/
public interface ThreadContextStack extends ThreadContext.ContextStack, Collection<String> {
}
| /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache license, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the license for the specific language governing permissions and
* limitations under the license.
*/
package org.apache.logging.log4j.spi;
import java.util.Collection;
import org.apache.logging.log4j.ThreadContext;
/**
*
*/
public interface ThreadContextStack extends ThreadContext.ContextStack,
Collection<String> {
}
|
Enable proxy classes for parameter names
Signed-off-by: Sebastian Hoß <1d6e1cf70ec6f9ab28d3ea4b27a49a77654d370e@shoss.de> | /*
* Copyright © 2012 Sebastian Hoß <mail@shoss.de>
* This work is free. You can redistribute it and/or modify it under the
* terms of the Do What The Fuck You Want To Public License, Version 2,
* as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
*/
package com.github.sebhoss.contract.configuration;
import com.github.sebhoss.contract.verifier.ParameterNamesLookupConfiguration;
import com.github.sebhoss.contract.verifier.SpringElConfiguration;
import com.github.sebhoss.contract.verifier.impl.ErrorMessageConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Import;
/**
* Default configuration for Spring-based projects.
*/
@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
@Import({ ParameterNamesLookupConfiguration.class, SpringElConfiguration.class, ErrorMessageConfiguration.class })
public class DefaultSpringConfiguration {
// Meta-configuration
}
| /*
* Copyright © 2012 Sebastian Hoß <mail@shoss.de>
* This work is free. You can redistribute it and/or modify it under the
* terms of the Do What The Fuck You Want To Public License, Version 2,
* as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
*/
package com.github.sebhoss.contract.configuration;
import com.github.sebhoss.contract.verifier.ParameterNamesLookupConfiguration;
import com.github.sebhoss.contract.verifier.SpringElConfiguration;
import com.github.sebhoss.contract.verifier.impl.ErrorMessageConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Import;
/**
* Default configuration for Spring-based projects.
*/
@Configuration
@EnableAspectJAutoProxy
@Import({ ParameterNamesLookupConfiguration.class, SpringElConfiguration.class, ErrorMessageConfiguration.class })
public class DefaultSpringConfiguration {
// Meta-configuration
}
|
Use passed in polyglot check | <?php
namespace Rocketeer\Strategies\Check;
use Rocketeer\Abstracts\Strategies\AbstractPolyglotStrategy;
use Rocketeer\Interfaces\Strategies\CheckStrategyInterface;
class PolyglotStrategy extends AbstractPolyglotStrategy implements CheckStrategyInterface
{
/**
* Check that the PM that'll install
* the app's dependencies is present
*
* @return boolean
*/
public function manager()
{
$this->executeStrategiesMethod('manager');
return $this->passed();
}
/**
* Check that the language used by the
* application is at the required version
*
* @return boolean
*/
public function language()
{
$this->executeStrategiesMethod('language');
return $this->passed();
}
/**
* Check for the required extensions
*
* @return array
*/
public function extensions()
{
$missing = [];
$extensions = $this->executeStrategiesMethod('extensions');
foreach ($extensions as $extension) {
$missing = array_merge($missing, $extension);
}
return $missing;
}
/**
* Check for the required drivers
*
* @return array
*/
public function drivers()
{
$missing = [];
$drivers = $this->executeStrategiesMethod('drivers');
foreach ($drivers as $driver) {
$missing = array_merge($missing, $driver);
}
return $missing;
}
}
| <?php
namespace Rocketeer\Strategies\Check;
use Rocketeer\Abstracts\Strategies\AbstractPolyglotStrategy;
use Rocketeer\Interfaces\Strategies\CheckStrategyInterface;
class PolyglotStrategy extends AbstractPolyglotStrategy implements CheckStrategyInterface
{
/**
* Check that the PM that'll install
* the app's dependencies is present
*
* @return boolean
*/
public function manager()
{
$results = $this->executeStrategiesMethod('manager');
return $this->checkStrategiesResults($results);
}
/**
* Check that the language used by the
* application is at the required version
*
* @return boolean
*/
public function language()
{
$results = $this->executeStrategiesMethod('language');
return $this->checkStrategiesResults($results);
}
/**
* Check for the required extensions
*
* @return array
*/
public function extensions()
{
$missing = [];
$extensions = $this->executeStrategiesMethod('extensions');
foreach ($extensions as $extension) {
$missing = array_merge($missing, $extension);
}
return $missing;
}
/**
* Check for the required drivers
*
* @return array
*/
public function drivers()
{
$missing = [];
$drivers = $this->executeStrategiesMethod('drivers');
foreach ($drivers as $driver) {
$missing = array_merge($missing, $driver);
}
return $missing;
}
}
|
Use right command to select teams | from gather.organiser import NotEnoughPlayersError
def strip_help(bot):
messages = []
for regex, action in bot.actions.values():
if action.__doc__:
messages.append(action.__doc__.strip())
return messages
async def bot_help(bot, channel, author, message):
await bot.say_lines(channel, strip_help(bot))
async def add(bot, channel, author, message):
"""
- !add, !s - add yourself to the pool
"""
bot.organiser.add(channel, author)
await bot.say(channel, 'You are now signed in, {0}.'.format(author))
try:
team_one, team_two = bot.organiser.pop_teams(channel)
# TODO: Announce the game
except NotEnoughPlayersError:
pass
async def remove(bot, channel, author, message):
"""
- !remove, !so - remove yourself from the pool
"""
bot.organiser.remove(channel, author)
await bot.say(channel, 'You are now signed out, {0}.'.format(author))
| from gather.organiser import NotEnoughPlayersError
def strip_help(bot):
messages = []
for regex, action in bot.actions.values():
if action.__doc__:
messages.append(action.__doc__.strip())
return messages
async def bot_help(bot, channel, author, message):
await bot.say_lines(channel, strip_help(bot))
async def add(bot, channel, author, message):
"""
- !add, !s - add yourself to the pool
"""
bot.organiser.add(channel, author)
await bot.say(channel, 'You are now signed in, {0}.'.format(author))
try:
team_one, team_two = bot.organiser.select_teams()
# TODO: Announce the game
except NotEnoughPlayersError:
pass
async def remove(bot, channel, author, message):
"""
- !remove, !so - remove yourself from the pool
"""
bot.organiser.remove(channel, author)
await bot.say(channel, 'You are now signed out, {0}.'.format(author))
|
Handle case where package.json exists but not .dat | var path = require('path')
var meta = require(path.join(__dirname, 'lib', 'meta.js'))
var commands = require(path.join(__dirname, 'lib', 'commands'))
module.exports = Dat
// new Dat(cb)
// new Dat({foo: bar})
// new Dat({foo: bar}, cb)
// new Dat('./foo)
// new Dat('./foo', cb)
// new Dat('./foo', {foo: bar})
// new Dat('./foo', {foo: bar}, cb)
function Dat(dir, opts, onReady) {
var self = this
// if 'new' was not used
if (!(this instanceof Dat)) return new Dat(dir, opts)
if (typeof dir === 'function') {
onReady = dir
opts = {}
dir = process.cwd()
}
if (typeof opts === 'function') {
onReady = opts
opts = {}
}
if (typeof dir === 'object') {
onReady = opts
opts = dir
dir = process.cwd()
}
if (!onReady) onReady = function(){}
this.dir = dir
this.opts = opts
this.meta = meta(this.dir, function(err) {
if (err) return onReady()
commands._ensureExists(opts, function (err) {
if (err) {
console.error(err)
process.exit(1)
}
self._storage(opts, onReady)
})
})
}
Dat.prototype = commands
| var path = require('path')
var meta = require(path.join(__dirname, 'lib', 'meta.js'))
module.exports = Dat
// new Dat(cb)
// new Dat({foo: bar})
// new Dat({foo: bar}, cb)
// new Dat('./foo)
// new Dat('./foo', cb)
// new Dat('./foo', {foo: bar})
// new Dat('./foo', {foo: bar}, cb)
function Dat(dir, opts, onReady) {
var self = this
// if 'new' was not used
if (!(this instanceof Dat)) return new Dat(dir, opts)
if (typeof dir === 'function') {
onReady = dir
opts = {}
dir = process.cwd()
}
if (typeof opts === 'function') {
onReady = opts
opts = {}
}
if (typeof dir === 'object') {
onReady = opts
opts = dir
dir = process.cwd()
}
if (!onReady) onReady = function(){}
this.dir = dir
this.opts = opts
this.meta = meta(this.dir, function(err) {
if (err) return onReady()
self._storage(opts, onReady)
})
}
Dat.prototype = require(path.join(__dirname, 'lib', 'commands'))
|
Fix showcase to old (svn) state. | /*
* This is part of Geomajas, a GIS framework, http://www.geomajas.org/.
*
* Copyright 2008-2014 Geosparc nv, http://www.geosparc.com/, Belgium.
*
* The program is available in open source according to the GNU Affero
* General Public License. All contributions in this program are covered
* by the Geomajas Contributors License Agreement. For full licensing
* details, see LICENSE.txt in the project root.
*/
package org.geomajas.gwt.example.client.security;
import org.geomajas.gwt.client.command.TokenRequestHandler;
import org.geomajas.gwt.client.command.event.TokenChangedHandler;
import org.geomajas.plugin.staticsecurity.client.util.SsecAccess;
/**
* {@link org.geomajas.gwt.client.command.TokenRequestHandler} which allows logging in to a specific userId and
* password.
*
* @author Joachim Van der Auwera
*/
public class ShowcaseTokenRequestHandler implements TokenRequestHandler {
// CHECKSTYLE VISIBILITY MODIFIER: OFF
/** UserId to use for logging in. */
public static String userId;
/** Password to use for logging in. */
public static String password;
// CHECKSTYLE VISIBILITY MODIFIER: ON
@Override
public void login(TokenChangedHandler tokenChangedHandler) {
SsecAccess.login(userId, password, tokenChangedHandler);
}
}
| /*
* This is part of Geomajas, a GIS framework, http://www.geomajas.org/.
*
* Copyright 2008-2014 Geosparc nv, http://www.geosparc.com/, Belgium.
*
* The program is available in open source according to the GNU Affero
* General Public License. All contributions in this program are covered
* by the Geomajas Contributors License Agreement. For full licensing
* details, see LICENSE.txt in the project root.
*/
package org.geomajas.gwt.example.client.security;
import org.geomajas.gwt.client.command.TokenRequestHandler;
import org.geomajas.gwt.client.command.event.TokenChangedHandler;
import org.geomajas.plugin.staticsecurity.client.util.SsecAccess;
/**
* {@link org.geomajas.gwt.client.command.TokenRequestHandler} which allows logging in to a specific userId and password.
*
* @author Joachim Van der Auwera
*/
public class ShowcaseTokenRequestHandler implements TokenRequestHandler {
// CHECKSTYLE VISIBILITY MODIFIER: OFF
/** UserId to use for logging in. */
public static String userId;
/** Password to use for logging in. */
public static String password;
// CHECKSTYLE VISIBILITY MODIFIER: ON
@Override
public void login(TokenChangedHandler tokenChangedHandler) {
SsecAccess.login(userId, password, tokenChangedHandler);
}
}
|
Allow to pass crank opts as environment variables | package main
import (
"../../pkg/netutil"
"flag"
"log"
"os"
"syscall"
)
var (
addr string
conf string
)
func init() {
flag.StringVar(&addr, "addr", os.Getenv("CRANK_ADDR"), "external address to bind (e.g. 'tcp://:80')")
flag.StringVar(&conf, "conf", os.Getenv("CRANK_CONF"), "path to the process config file")
}
func main() {
flag.Parse()
// TODO: If required should not be a flag?
// TODO: refactor this
if addr == "" {
log.Fatal("Missing required flag: addr")
}
if conf == "" {
log.Fatal("Missing required flag: conf")
}
socket, err := netutil.BindFile(addr)
if err != nil {
log.Fatal("OOPS", err)
}
log.Print(socket)
manager := NewManager(conf, socket)
go manager.Run()
go OnSignal(manager.Restart, syscall.SIGHUP)
go OnSignal(manager.Shutdown, syscall.SIGTERM, syscall.SIGINT)
manager.OnShutdown.Wait()
log.Println("Bye!")
}
| package main
import (
"../../pkg/netutil"
"flag"
"log"
"syscall"
)
var (
addr string
conf string
)
func init() {
flag.StringVar(&addr, "addr", "", "external address to bind (e.g. 'tcp://:80')")
flag.StringVar(&conf, "conf", "", "path to the process config file")
}
func main() {
flag.Parse()
// TODO: If required should not be a flag?
// TODO: refactor this
if addr == "" {
log.Fatal("Missing required flag: addr")
}
if conf == "" {
log.Fatal("Missing required flag: conf")
}
socket, err := netutil.BindFile(addr)
if err != nil {
log.Fatal("OOPS", err)
}
log.Print(socket)
manager := NewManager(conf, socket)
go manager.Run()
go OnSignal(manager.Restart, syscall.SIGHUP)
go OnSignal(manager.Shutdown, syscall.SIGTERM, syscall.SIGINT)
manager.OnShutdown.Wait()
log.Println("Bye!")
}
|
Fix loggly formatter on php 5.6 | <?php
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Formatter;
/**
* Encodes message information into JSON in a format compatible with Loggly.
*
* @author Adam Pancutt <adam@pancutt.com>
*/
class LogglyFormatter extends JsonFormatter
{
/**
* Overrides the default batch mode to new lines for compatibility with the
* Loggly bulk API.
*
* @param integer $batchMode
*/
public function __construct($batchMode = self::BATCH_MODE_NEWLINES, $appendNewline = false)
{
parent::__construct($batchMode, $appendNewline);
}
/**
* Appends the 'timestamp' parameter for indexing by Loggly.
*
* @see https://www.loggly.com/docs/automated-parsing/#json
* @see \Monolog\Formatter\JsonFormatter::format()
*/
public function format(array $record)
{
if (isset($record["datetime"]) && ($record["datetime"] instanceof \DateTime)) {
$record["timestamp"] = $record["datetime"]->format("Y-m-d\TH:i:s.uO");
// TODO 2.0 unset the 'datetime' parameter, retained for BC
}
return parent::format($record);
}
}
| <?php
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Formatter;
/**
* Encodes message information into JSON in a format compatible with Loggly.
*
* @author Adam Pancutt <adam@pancutt.com>
*/
class LogglyFormatter extends JsonFormatter
{
/**
* Overrides the default batch mode to new lines for compatibility with the
* Loggly bulk API.
*
* @param integer $batchMode
*/
public function __construct($batchMode = self::BATCH_MODE_NEWLINES, $appendNewline = false)
{
parent::__construct($batchMode, $appendNewline);
}
/**
* Appends the 'timestamp' parameter for indexing by Loggly.
*
* @see https://www.loggly.com/docs/automated-parsing/#json
* @see \Monolog\Formatter\JsonFormatter::format()
*/
public function format(array $record)
{
if (isset($record["datetime"]) && ($record["datetime"] instanceof \DateTime)) {
$record["timestamp"] = $record["datetime"]->format("c");
// TODO 2.0 unset the 'datetime' parameter, retained for BC
}
return parent::format($record);
}
}
|
Use a reference browser instead of autocomplete | import {ReferenceInput} from 'role:@sanity/form-builder'
import client from 'client:@sanity/base/client'
import {unprefixType} from '../utils/unprefixType'
function fetchSingle(id) {
return client.fetch('*[.$id == %id]', {id}).then(response => unprefixType(response.result[0]))
}
export default ReferenceInput.createBrowser({
fetch(field) {
const toFieldTypes = field.to.map(toField => toField.type)
const params = toFieldTypes.reduce((acc, toFieldType, i) => {
acc[`toFieldType${i}`] = `beerfiesta.${toFieldType}`
return acc
}, {})
const eqls = Object.keys(params).map(key => (
`.$type == %${key}`
)).join(' || ')
return client.fetch(`*[${eqls}]`, params)
.then(response => response.result.map(unprefixType))
},
materializeReferences(referenceIds) {
return Promise.all(referenceIds.map(fetchSingle))
}
})
| import React from 'react'
import {createReferenceInput} from 'role:@sanity/form-builder'
import client from 'client:@sanity/base/client'
import {unprefixType} from '../utils/unprefixType'
import debounce from 'debounce-promise'
function fetchSingle(id) {
return client.fetch('*[.$id == %id]', {id}).then(response => unprefixType(response.result[0]))
}
function createHit(document) {
return {document}
}
const ReferenceInput = createReferenceInput({
search: debounce((query, field) => {
const toField = field.to[0]
if (!toField.searchField) {
throw new TypeError(`Unable to peform search: No "searchField" specified on reference type for "${field.name}". Check your schema.`)
}
return client.fetch(`*[.$type == %type && .${toField.searchField} == %q]`, {
type: `beerfiesta.${toField.type}`,
q: query
})
.then(response => response.result.map(unprefixType).map(createHit))
}, 200),
materializeReferences(referenceIds) {
return Promise.all(referenceIds.map(fetchSingle))
}
})
export default function Reference(props) {
return (
<div>
<ReferenceInput {...props} />
<div style={{fontSize: 10}}>[Only exact matches are supported for now!]</div>
</div>
)
}
Reference.valueContainer = ReferenceInput.valueContainer
|
Change assoc. map array to use an object | 'use strict';
var markovDictionaryBuilder = (function(logger) {
function buildDict(wordSet, chainSize) {
logger.logDebug("building dictionary from " + wordSet.length + " words with a chain size of " + chainSize);
var map = {};
var dict = [];
for (var i = 0, len = wordSet.length - chainSize; i < len; i++) {
var end = i + parseFloat(chainSize);
var workingSet = wordSet.slice(i, end+1);
var k = workingSet.slice(0, workingSet.length-1);
var n = workingSet.slice(-1);
var dictItem = {
'key' : k.join('/').toLowerCase(),
'words' : k,
'next' : n
};
var mi = map[dictItem.key];
if (typeof(mi) !== 'number') {
var dictIndex = dict.length;
dict.push(dictItem);
map[dictItem.key] = dictIndex;
} else {
dict[mi].next.push(dictItem.next[0]);
}
}
return dict;
}
return {
buildDict : buildDict
};
})(logger); | 'use strict';
var markovDictionaryBuilder = (function(logger) {
function buildDict(wordSet, chainSize) {
logger.logDebug("building dictionary from " + wordSet.length + " words with a chain size of " + chainSize);
var map = [];
var dict = [];
for (var i = 0, len = wordSet.length - chainSize; i < len; i++) {
var end = i + parseFloat(chainSize);
var workingSet = wordSet.slice(i, end+1);
var k = workingSet.slice(0, workingSet.length-1);
var n = workingSet.slice(-1);
var dictItem = {
'key' : k.join('/').toLowerCase(),
'words' : k,
'next' : n
};
var mi = map[dictItem.key];
if (typeof(mi) !== 'number') {
var dictIndex = dict.length;
dict.push(dictItem);
map[dictItem.key] = dictIndex;
} else {
dict[mi].next.push(dictItem.next[0]);
}
}
return dict;
}
return {
buildDict : buildDict
};
})(logger); |
Add localadmin to locality layer
It was missing previously. | /* Look up which admin fields should be populated for a record in a given layer.
*
* The logic is: look up eveything above in the WOF heirarchy, ignoring things like
* 'dependency'
*
* Note: this filtering really only matters for geonames currently, since OSM and OA
* consist entirely of venue and address records, which should have all fields
* looked up. WOF documents use the actual WOF heirarchy to fill in admin values,
* so they also won't be affected by this.
*/
function getAdminLayers(layer) {
switch (layer) {
case 'country':
return ['country'];
case 'macroregion':
return ['country', 'macroregion'];
case 'region':
return ['country', 'macroregion', 'region'];
case 'county':
return ['country', 'macroregion', 'region', 'macrocounty', 'county'];
case 'locality':
return ['country', 'macroregion', 'region', 'macrocounty', 'county', 'localadmin', 'locality'];
default:
return undefined;//undefined means use all layers as normal
}
}
module.exports = getAdminLayers;
| /* Look up which admin fields should be populated for a record in a given layer.
*
* The logic is: look up eveything above in the WOF heirarchy, ignoring things like
* 'dependency'
*
* Note: this filtering really only matters for geonames currently, since OSM and OA
* consist entirely of venue and address records, which should have all fields
* looked up. WOF documents use the actual WOF heirarchy to fill in admin values,
* so they also won't be affected by this.
*/
function getAdminLayers(layer) {
switch (layer) {
case 'country':
return ['country'];
case 'macroregion':
return ['country', 'macroregion'];
case 'region':
return ['country', 'macroregion', 'region'];
case 'county':
return ['country', 'macroregion', 'region', 'macrocounty', 'county'];
case 'locality':
return ['country', 'macroregion', 'region', 'macrocounty', 'county', 'locality'];
default:
return undefined;//undefined means use all layers as normal
}
}
module.exports = getAdminLayers;
|
Make annotation tests work with non-evaluated annotations (GH-4050)
Backported from 3dc2b9dfc23638fbef2558d619709b5235d5df08
Partial fix for https://github.com/cython/cython/issues/3919 | # mode: run
# tag: generators, pure3.5
from __future__ import generator_stop
# "generator_stop" was only added in Py3.5.
def with_outer_raising(*args):
"""
>>> x = with_outer_raising(1, 2, 3)
>>> try:
... list(x())
... except RuntimeError:
... print("OK!")
... else:
... print("NOT RAISED!")
OK!
"""
def generator():
for i in args:
yield i
raise StopIteration
return generator
def anno_gen(x: 'int') -> 'float':
"""
>>> gen = anno_gen(2)
>>> next(gen)
2.0
>>> ret, arg = sorted(anno_gen.__annotations__.items())
>>> print(ret[0]); print(str(ret[1]).strip("'")) # strip makes it pass with/without PEP563
return
float
>>> print(arg[0]); print(str(arg[1]).strip("'"))
x
int
"""
yield float(x)
| # mode: run
# tag: generators, pure3.5
from __future__ import generator_stop
# "generator_stop" was only added in Py3.5.
def with_outer_raising(*args):
"""
>>> x = with_outer_raising(1, 2, 3)
>>> try:
... list(x())
... except RuntimeError:
... print("OK!")
... else:
... print("NOT RAISED!")
OK!
"""
def generator():
for i in args:
yield i
raise StopIteration
return generator
def anno_gen(x: 'int') -> 'float':
"""
>>> gen = anno_gen(2)
>>> next(gen)
2.0
>>> ret, arg = sorted(anno_gen.__annotations__.items())
>>> print(ret[0]); print(ret[1])
return
float
>>> print(arg[0]); print(arg[1])
x
int
"""
yield float(x)
|
Use '-' in cache name as separator between plugin name and cache name
In other places we already use '-' as separator in names that include
the plugin name, e.g. for capabilities that are defined by a plugin.
To be consistent the cache name should use the same separator. '.'
cannot be used for capabilities since it is not allowed in parameter
names in Git config files.
Change-Id: Ic1a669930831a1d4e526f2a22771879ecf7f19c1
Signed-off-by: Edwin Kempin <b444e279ad95fdef4fbdd82c813b624595df204a@sap.com> | // Copyright (C) 2009 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.sshd.commands;
import com.google.common.cache.Cache;
import com.google.common.collect.Sets;
import com.google.gerrit.extensions.registration.DynamicMap;
import com.google.gerrit.sshd.SshCommand;
import com.google.inject.Inject;
import java.util.SortedSet;
abstract class CacheCommand extends SshCommand {
@Inject
protected DynamicMap<Cache<?, ?>> cacheMap;
protected SortedSet<String> cacheNames() {
SortedSet<String> names = Sets.newTreeSet();
for (DynamicMap.Entry<Cache<?, ?>> e : cacheMap) {
names.add(cacheNameOf(e.getPluginName(), e.getExportName()));
}
return names;
}
protected String cacheNameOf(String plugin, String name) {
if ("gerrit".equals(plugin)) {
return name;
} else {
return plugin + "-" + name;
}
}
}
| // Copyright (C) 2009 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.sshd.commands;
import com.google.common.cache.Cache;
import com.google.common.collect.Sets;
import com.google.gerrit.extensions.registration.DynamicMap;
import com.google.gerrit.sshd.SshCommand;
import com.google.inject.Inject;
import java.util.SortedSet;
abstract class CacheCommand extends SshCommand {
@Inject
protected DynamicMap<Cache<?, ?>> cacheMap;
protected SortedSet<String> cacheNames() {
SortedSet<String> names = Sets.newTreeSet();
for (DynamicMap.Entry<Cache<?, ?>> e : cacheMap) {
names.add(cacheNameOf(e.getPluginName(), e.getExportName()));
}
return names;
}
protected String cacheNameOf(String plugin, String name) {
if ("gerrit".equals(plugin)) {
return name;
} else {
return plugin + "." + name;
}
}
}
|
Save only one variable (dict) | // ==UserScript==
// @name EPFL People
// @namespace none
// @description A script to improve browsing on people.epfl.ch
// @include http://people.epfl.ch/*
// @version 1
// @grant none
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
// @author EPFL-dojo
// ==/UserScript==
//Avoid conflicts
this.$ = this.jQuery = jQuery.noConflict(true);
$(document).ready(function()
{
// get the h1 name content
$.epfl_user = {
"name": $("h1").text(),
"sciper": $('a[href*="http://people.epfl.ch/cgi-bin/people?id="]').attr('href').match(/id=([0-9]{6})/)[1]
};
// change the main title content to add the sciper in it
$("h1").text($.epfl_user["name"] + " #" + $.epfl_user["sciper"] + " ()");
$.get("/cgi-bin/people/showcv?id=" + $.epfl_user["sciper"] + "&op=admindata&type=show&lang=en&cvlang=en", function(data){
$.epfl_user["username"] = data.match(/Username: (\w+)\s/)[1];
$("h1").text($.epfl_user["name"] + " #" + $.epfl_user["sciper"] + " (" + $.epfl_user["username"]+ ")");
})
});
| // ==UserScript==
// @name EPFL People
// @namespace none
// @description A script to improve browsing on people.epfl.ch
// @include http://people.epfl.ch/*
// @version 1
// @grant none
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
// @author EPFL-dojo
// ==/UserScript==
//Avoid conflicts
this.$ = this.jQuery = jQuery.noConflict(true);
$(document).ready(function()
{
// get the h1 name content
$.h1name = $("h1").text();
// get the sciper number
$.sciper = $('a[href*="http://people.epfl.ch/cgi-bin/people?id="]').attr('href').match(/id=([0-9]{6})/)[1];
// change the main title content to add the sciper in it
$("h1").text($.h1name + " #" + $.sciper + " ()");
$.get("/cgi-bin/people/showcv?id=" + $.sciper + "&op=admindata&type=show&lang=en&cvlang=en", function(data){
$.username = data.match(/Username: (\w+)\s/)[1]
$("h1").text($.h1name + " #" + $.sciper + " (" + $.username + ")");
})
});
|
Use a more standard variable name for the class argument. | from springfield import Entity
def entity_from_mongo(cls, values):
"""
Construct an Entity of type `cls` from a Mongo document.
"""
entity = cls()
if hasattr(values, '__values__'):
for key, val in values.__values__.items():
if key == '_id':
key = 'id'
if key in entity.__fields__:
entity.set(key, val)
else:
for key, val in values.items():
if key == '_id':
key = 'id'
if key in entity.__fields__:
entity.set(key, val)
return entity
def entity_to_mongo(entity):
"""
Convert an Entity type into a structure able to be stored in Mongo.
"""
data = {}
for key, val in entity.__values__.iteritems():
field = entity.__fields__[key]
if isinstance(val, Entity):
val = entity_to_mongo(val)
else:
val = field.flatten(val)
if key == 'id':
key = '_id'
data[key] = val
return data
| from springfield import Entity
def entity_from_mongo(kls, values):
"""
Construct an Entity of type `kls` from a Mongo document.
"""
entity = kls()
if hasattr(values, '__values__'):
for key, val in values.__values__.items():
if key == '_id':
key = 'id'
if key in entity.__fields__:
entity.set(key, val)
else:
for key, val in values.items():
if key == '_id':
key = 'id'
if key in entity.__fields__:
entity.set(key, val)
return entity
def entity_to_mongo(entity):
"""
Convert an Entity type into a structure able to be stored in Mongo.
"""
data = {}
for key, val in entity.__values__.iteritems():
field = entity.__fields__[key]
if isinstance(val, Entity):
val = entity_to_mongo(val)
else:
val = field.flatten(val)
if key == 'id':
key = '_id'
data[key] = val
return data
|
Fix the param names for updateCompleteForm() | <?php
namespace SclZfCartPayment;
use SclZfCart\Entity\OrderInterface;
use SclZfCartPayment\Entity\PaymentInterface;
use Zend\Form\Form;
/**
* The interface that a payment method must implement to integrate with this
* payment module.
*
* @author Tom Oram <tom@scl.co.uk>
*/
interface PaymentMethodInterface
{
/**
* The name of the payment method.
*
* @return string
*/
public function name();
/**
* The payment method may update the confirm form.
*
* @param Form $form
* @param OrderInteface $order
* @param PaymentInterface $payment
* @return void
*/
public function updateCompleteForm(
Form $form,
OrderInterface $order,
PaymentInterface $payment
);
/**
* Takes the values returned from the payment method and completes the payment.
*
* @param array $data
* @return boolean Return true if the payment was successful
*/
public function complete(array $data);
}
| <?php
namespace SclZfCartPayment;
use SclZfCart\Entity\OrderInterface;
use SclZfCartPayment\Entity\PaymentInterface;
use Zend\Form\Form;
/**
* The interface that a payment method must implement to integrate with this
* payment module.
*
* @author Tom Oram <tom@scl.co.uk>
*/
interface PaymentMethodInterface
{
/**
* The name of the payment method.
*
* @return string
*/
public function name();
/**
* The payment method may update the confirm form.
*
* @param Form $form
* @param OrderInteface $cart
* @param PaymentInterface $cart
* @return void
*/
public function updateCompleteForm(
Form $form,
OrderInterface $cart,
PaymentInterface $payment
);
/**
* Takes the values returned from the payment method and completes the payment.
*
* @param array $data
* @return boolean Return true if the payment was successful
*/
public function complete(array $data);
}
|
Fix call to incorrect function name | /*
* Game core for Robots Order BreakOut Trepidation!
*
* @canvas = reference to an HTML5 canvas element.
*/
'use strict';
import Actors from 'Actors.js';
import Collision from 'Collision.js';
export default class {
constructor(canvas) {
// Player settings.
this._score = 0;
this._lives = 3;
// Game settings.
this._running = false;
this._canvas = canvas;
this._ctx = this._canvas.getContext("2d");
this._actors = new Actors(this._canvas.width, this._canvas.height);
this._collision = new Collision();
}
_clearScene() {
this._ctx.clearRect(0, 0, this._canvas.width, this._canvas.height);
// TODO: Draw background.
}
_drawScene() {
this._clearScene();
// TODO: Draw scene.
if (this._running) {
requestAnimationFrame(()=> this._drawScene());
}
}
_startGameLoop() {
requestAnimationFrame(()=> this._drawScene());
}
// This is kinda out of place here, but haven't found a better
// place for it yet.
movePaddle(direction) {
// TODO: Implement paddle movement.
}
start() {
this._startGameLoop();
}
pause() {
// TODO: Implement some kind of pause.
}
stop() {
this._running = false;
}
}
| /*
* Game core for Robots Order BreakOut Trepidation!
*
* @canvas = reference to an HTML5 canvas element.
*/
'use strict';
import Actors from 'Actors.js';
import Collision from 'Collision.js';
export default class {
constructor(canvas) {
// Player settings.
this._score = 0;
this._lives = 3;
// Game settings.
this._running = false;
this._canvas = canvas;
this._ctx = this._canvas.getContext("2d");
this._actors = new Actors(this._canvas.width, this._canvas.height);
this._collision = new Collision();
}
_clearScene() {
this._ctx.clearRect(0, 0, this._canvas.width, this._canvas.height);
// TODO: Draw background.
}
_drawScene() {
this.clearScene();
// TODO: Draw scene.
if (this._running) {
requestAnimationFrame(()=> this.drawScene());
}
}
_startGameLoop() {
requestAnimationFrame(()=> this.drawScene());
}
// This is kinda out of place here, but haven't found a better
// place for it yet.
movePaddle(direction) {
// TODO: Implement paddle movement.
}
start() {
this._startGameLoop();
}
pause() {
// TODO: Implement some kind of pause.
}
stop() {
this._running = false;
}
}
|
Fix React warning about calling setState on unmounted component | import React, {PropTypes} from 'react';
import classNames from 'classnames';
import t from '../utilities/translate';
export default class BreedButtonView extends React.Component {
static propTypes = {
onClick: PropTypes.func.isRequired,
disabled: PropTypes.bool
}
constructor(props) {
super(props);
this.state = {
tempDisabled: false
};
}
handleClick = () => {
if (!this.state.tempDisabled) {
this.props.onClick();
this.setState({tempDisabled: true});
// Disable the button for a bit to avoid mass breeding
this.timer = setTimeout(() => {
this.setState({tempDisabled: false});
this.timer = null;
}, 500);
}
}
componentWillUnmount() {
if (this.timer) {
clearTimeout(this.timer);
}
}
render() {
const disabled = this.props.disabled || this.state.tempDisabled;
return (
<div className={classNames('breed-button', { disabled })} onClick={this.handleClick}>
<div className="button-label breed-button-label unselectable">{ t("~FV_EGG_GAME.BREED_BUTTON") }</div>
</div>
);
}
}
| import React, {PropTypes} from 'react';
import classNames from 'classnames';
import t from '../utilities/translate';
export default class BreedButtonView extends React.Component {
static propTypes = {
onClick: PropTypes.func.isRequired,
disabled: PropTypes.bool
}
constructor(props) {
super(props);
this.state = {
tempDisabled: false
};
}
render() {
let _this = this;
const handleClick = () => {
if (!_this.state.tempDisabled) {
_this.props.onClick();
_this.setState({tempDisabled: true});
// Disable the button for a bit to avoid mass breeding
setTimeout(function() {
_this.setState({tempDisabled: false});
}, 500);
}
};
return (
<div className={classNames('breed-button', { 'disabled': this.props.disabled})} onClick={handleClick}>
<div className="button-label breed-button-label unselectable">{ t("~FV_EGG_GAME.BREED_BUTTON") }</div>
</div>
);
}
}
|
Add Characteristic to depends since we are using it directly now.
--HG--
branch : 1-lookup-index | import re
from setuptools import setup, find_packages
versionPattern = re.compile(r"""^__version__ = ['"](.*?)['"]$""", re.M)
with open("fusion_index/_version.py", "rt") as f:
version = versionPattern.search(f.read()).group(1)
setup(
name='fusion-index',
version=version,
description='Lookup/search index service for Fusion',
url='https://bitbucket.org/fusionapp/fusion-index',
install_requires=[
'Twisted[tls] >= 15.0.0',
'txspinneret >= 0.1.2',
'Axiom >= 0.7.4',
'eliot >= 0.8.0',
'testtools',
'characteristic',
],
license='MIT',
packages=find_packages() + ['axiom.plugins'],
include_package_data=True)
| import re
from setuptools import setup, find_packages
versionPattern = re.compile(r"""^__version__ = ['"](.*?)['"]$""", re.M)
with open("fusion_index/_version.py", "rt") as f:
version = versionPattern.search(f.read()).group(1)
setup(
name='fusion-index',
version=version,
description='Lookup/search index service for Fusion',
url='https://bitbucket.org/fusionapp/fusion-index',
install_requires=[
'Twisted[tls] >= 15.0.0',
'txspinneret >= 0.1.2',
'Axiom >= 0.7.4',
'eliot >= 0.8.0',
'testtools',
],
license='MIT',
packages=find_packages() + ['axiom.plugins'],
include_package_data=True)
|
Fix License Header (Thanks Christophe).
git-svn-id: 2c03e0f2e02f0f2dd4186d3c621cdb4dda8971fb@572356 13f79535-47bb-0310-9956-ffa450edef68 | /*
* Copyright 2007 The Apache Software Foundation.
*
* 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.apache.jackrabbit.ocm.exception;
/**
* The <code>InvalidQuerySyntaxException</code> is an
* <code>ObjectContentManagerException</code> thrown if the query of the
* {@link org.apache.jackrabbit.ocm.manager.ObjectContentManager#getObjectIterator(String, String)}
* is invalid. This exception actually wraps a standard JCR
* <code>javax.jcr.InvalidQueryException</code> to make it an unchecked
* exception. The cause of this exception will always be the original
* <code>InvalidQueryException</code> and the message will always be the
* original exception's message.
*/
public class InvalidQueryException extends ObjectContentManagerException {
/**
* Create an exception wrapping the given checked JCR exception
*
* @param cause The wrapped JCR <code>InvalidQueryException</code>
*/
public InvalidQueryException(javax.jcr.query.InvalidQueryException cause) {
super(cause.getMessage(), cause);
}
}
| /*
* $Url: $
* $Id: $
*
* Copyright 1997-2005 Day Management AG
* Barfuesserplatz 6, 4001 Basel, Switzerland
* All Rights Reserved.
*
* This software is the confidential and proprietary information of
* Day Management AG, ("Confidential Information"). You shall not
* disclose such Confidential Information and shall use it only in
* accordance with the terms of the license agreement you entered into
* with Day.
*/
package org.apache.jackrabbit.ocm.exception;
/**
* The <code>InvalidQuerySyntaxException</code> is an
* <code>ObjectContentManagerException</code> thrown if the query of the
* {@link org.apache.jackrabbit.ocm.manager.ObjectContentManager#getObjectIterator(String, String)}
* is invalid. This exception actually wraps a standard JCR
* <code>javax.jcr.InvalidQueryException</code> to make it an unchecked
* exception. The cause of this exception will always be the original
* <code>InvalidQueryException</code> and the message will always be the
* original exception's message.
*/
public class InvalidQueryException extends ObjectContentManagerException {
/**
* Create an exception wrapping the given checked JCR exception
*
* @param cause The wrapped JCR <code>InvalidQueryException</code>
*/
public InvalidQueryException(javax.jcr.query.InvalidQueryException cause) {
super(cause.getMessage(), cause);
}
}
|
Allow baseLayer option to be null to avoid rendering a base layer at all | import geojs from 'geojs/geo.js';
import VisComponent from '../../VisComponent';
export default class Geo extends VisComponent {
constructor (el, {map = {}, baseLayer = {}, features = []}) {
super(el);
// Construct a GeoJS map object based on the requested options.
this.plot = geojs.map(Object.assign({
node: el
}, map));
// Create a base layer.
if (baseLayer !== null) {
// Set default base layer options.
baseLayer.type = baseLayer.type || 'osm';
baseLayer.renderer = baseLayer.renderer || null;
this.plot.createLayer(baseLayer.type, baseLayer);
}
// Set up requested feature layers.
features.forEach(feature => {
this.plot.createLayer('feature', {
renderer: 'd3'
})
.createFeature(feature.type)
.data(feature.data)
.position(d => ({
x: d[feature.x],
y: d[feature.y]
}))
.style('fillColor', 'red')
.style('strokeColor', 'darkred');
});
this.render();
}
render () {
this.plot.draw();
}
}
| import geojs from 'geojs/geo.js';
import VisComponent from '../../VisComponent';
export default class Geo extends VisComponent {
constructor (el, {map = {}, baseLayer = {}, features = []}) {
super(el);
// Set default base layer options.
baseLayer.type = baseLayer.type || 'osm';
baseLayer.renderer = baseLayer.renderer || null;
// Construct a GeoJS map object based on the requested options.
this.plot = geojs.map(Object.assign({
node: el
}, map));
// Create a base layer.
this.plot.createLayer(baseLayer.type, baseLayer);
// Set up requested feature layers.
features.forEach(feature => {
this.plot.createLayer('feature', {
renderer: 'd3'
})
.createFeature(feature.type)
.data(feature.data)
.position(d => ({
x: d[feature.x],
y: d[feature.y]
}))
.style('fillColor', 'red')
.style('strokeColor', 'darkred');
});
this.render();
}
render () {
this.plot.draw();
}
}
|
Add empty line between methods | <?php
namespace FullyBaked\Pslackr\Messages;
class CustomMessage implements Message
{
protected $text;
protected $optionalFields = [];
public function __construct($messageText)
{
$this->text = $messageText;
}
public function asJson()
{
$message = ['text' => 'This is a test message'];
$message = array_merge($message, $this->optionalFields);
return json_encode($message);
}
public function channel($channelName)
{
$this->optionalFields['channel'] = $channelName;
}
public function username($username)
{
$this->optionalFields['username'] = $username;
}
public function iconEmoji($token)
{
$this->optionalFields['icon_emoji'] = $token;
}
public function iconUrl($url)
{
$this->optionalFields['icon_url'] = $url;
}
}
| <?php
namespace FullyBaked\Pslackr\Messages;
class CustomMessage implements Message
{
protected $text;
protected $optionalFields = [];
public function __construct($messageText)
{
$this->text = $messageText;
}
public function asJson()
{
$message = ['text' => 'This is a test message'];
$message = array_merge($message, $this->optionalFields);
return json_encode($message);
}
public function channel($channelName)
{
$this->optionalFields['channel'] = $channelName;
}
public function username($username)
{
$this->optionalFields['username'] = $username;
}
public function iconEmoji($token)
{
$this->optionalFields['icon_emoji'] = $token;
}
public function iconUrl($url)
{
$this->optionalFields['icon_url'] = $url;
}
}
|
Add references to other singleton objects | /*
* See LICENSE file in distribution for copyright and licensing information.
*/
package seph.lang;
import seph.lang.persistent.IPersistentList;
/**
* @author <a href="mailto:ola.bini@gmail.com">Ola Bini</a>
*/
@SephSingleton(parents="SephGround")
public class Ground implements SephObject {
public final static Ground instance = new Ground();
@SephCell
public final static SephObject Something = null;
@SephCell
public final static SephObject Ground = null;
@SephCell
public final static SephObject SephGround = null;
@SephCell
public final static SephObject Base = null;
@SephCell
public final static SephObject DefaultBehavior = null;
@SephCell
public final static SephObject IODefaultBehavior = null;
public SephObject get(String cellName) {
return seph.lang.bim.GroundBase.get(cellName);
}
public boolean isActivatable() {
return false;
}
public SephObject activateWith(LexicalScope scope, SephObject receiver, IPersistentList arguments) {
throw new RuntimeException(" *** couldn't activate: " + this);
}
}// Ground
| /*
* See LICENSE file in distribution for copyright and licensing information.
*/
package seph.lang;
import seph.lang.persistent.IPersistentList;
/**
* @author <a href="mailto:ola.bini@gmail.com">Ola Bini</a>
*/
@SephSingleton(parents="SephGround")
public class Ground implements SephObject {
public final static Ground instance = new Ground();
@SephCell
public final static SephObject Something = null;
public SephObject get(String cellName) {
return seph.lang.bim.GroundBase.get(cellName);
}
public boolean isActivatable() {
return false;
}
public SephObject activateWith(LexicalScope scope, SephObject receiver, IPersistentList arguments) {
throw new RuntimeException(" *** couldn't activate: " + this);
}
}// Ground
|
Define the lesson plan form type only on page load. | $(document).ready(function() {
function LessonPlanEntryFormType(pickers) {
var self = this;
this.pickers = pickers;
pickers.forEach(function(picker) {
picker.onSelectionCompleted = function() { self.doneCallback.apply(self, arguments); }
});
}
LessonPlanEntryFormType.prototype.pick = function() {
var $modal = $('<div class="modal hide fade" />');
this.pickers[0].pick($modal[0]);
$modal.modal();
}
LessonPlanEntryFormType.prototype.doneCallback = function(idTypePairList) {
idTypePairList.forEach(function(x) {
$element = $('<tr>\n\
<td>' + x[2] + '</td>\n\
<td> </td>\n\
<td>\n\
<span class="btn btn-danger resource-delete"><i class="icon-trash"></i></span>\n\
<input type="hidden" name="resources[]" value="' + x[0] + ',' + x[1] + '" />\n\
</td>\n\
</tr>');
$("#linked_resources tbody").append($element);
});
};
var LessonPlanEntryForm = new LessonPlanEntryFormType([]);
$('.addresource-button').click(function() {
LessonPlanEntryForm.pick();
});
$(document).on('click', '.resource-delete', null, function() {
$(this).parents('tr').remove();
});
});
| function LessonPlanEntryFormType(pickers) {
var self = this;
this.pickers = pickers;
pickers.forEach(function(picker) {
picker.onSelectionCompleted = function() { self.doneCallback.apply(self, arguments); }
});
}
LessonPlanEntryFormType.prototype.pick = function() {
var $modal = $('<div class="modal hide fade" />');
this.pickers[0].pick($modal[0]);
$modal.modal();
}
LessonPlanEntryFormType.prototype.doneCallback = function(idTypePairList) {
idTypePairList.forEach(function(x) {
$element = $('<tr>\n\
<td>' + x[2] + '</td>\n\
<td> </td>\n\
<td>\n\
<span class="btn btn-danger resource-delete"><i class="icon-trash"></i></span>\n\
<input type="hidden" name="resources[]" value="' + x[0] + ',' + x[1] + '" />\n\
</td>\n\
</tr>');
$("#linked_resources tbody").append($element);
});
};
var LessonPlanEntryForm = new LessonPlanEntryFormType([]);
$(document).ready(function() {
$('.addresource-button').click(function() {
LessonPlanEntryForm.pick();
});
$(document).on('click', '.resource-delete', null, function() {
$(this).parents('tr').remove();
});
});
|
Update PaymentType and ExecutionType to have correct options | var _ = require('underscore');
var Transaction = require('./Transaction');
var PayIn = Transaction.extend({
defaults: _.extend({}, Transaction.prototype.defaults, {
CreditedWalletId: null,
/**
* PaymentType (CARD, BANK_WIRE, DIRECT_DEBIT, PREAUTHORIZED)
*/
PaymentType: null,
/**
* One of PayInPaymentDetails implementations, depending on PaymentType
*/
PaymentDetails: null,
/**
* ExecutionType (WEB, DIRECT, EXTERNAL_INSTRUCTION)
*/
ExecutionType: null,
/**
* One of PayInExecutionDetails implementations, depending on ExecutionType
*/
ExecutionDetails: null
}),
getReadOnlyProperties: function() {
var properties = Transaction.prototype.getReadOnlyProperties();
properties.push('PaymentType', 'ExecutionType');
return properties;
}
});
module.exports = PayIn;
| var _ = require('underscore');
var Transaction = require('./Transaction');
var PayIn = Transaction.extend({
defaults: _.extend({}, Transaction.prototype.defaults, {
CreditedWalletId: null,
/**
* PaymentType (CARD, BANK_WIRE, AUTOMATIC_DEBIT, DIRECT_DEBIT)
*/
PaymentType: null,
/**
* One of PayInPaymentDetails implementations, depending on PaymentType
*/
PaymentDetails: null,
/**
* ExecutionType (WEB, TOKEN, DIRECT, PREAUTHORIZED, RECURRING_ORDER_EXECUTION, EXTERNAL_INSTRUCTION)
*/
ExecutionType: null,
/**
* One of PayInExecutionDetails implementations, depending on ExecutionType
*/
ExecutionDetails: null
}),
getReadOnlyProperties: function() {
var properties = Transaction.prototype.getReadOnlyProperties();
properties.push('PaymentType', 'ExecutionType');
return properties;
}
});
module.exports = PayIn; |
Disable Afrotropical connector. Because it doesn't have a regular harvest, just one-time and maybe upon request of content partner.
git-svn-id: d46fe582d22b46b457d3ac1c55a88da2fbe913a1@1382 baf6b65b-9124-4dc3-b1c0-01155b4af546 | <?php
/* connector for Afrotropical
estimated execution time: 41 mins.
This connector reads an EOL XML and converts PDF files stored in <mediaURL> into text description objects.
*/
exit;
$timestart = microtime(1);
include_once(dirname(__FILE__) . "/../../config/environment.php");
require_library('connectors/AfrotropicalAPI');
$GLOBALS['ENV_DEBUG'] = false;
$taxa = AfrotropicalAPI::get_all_taxa();
$xml = SchemaDocument::get_taxon_xml($taxa);
$resource_path = CONTENT_RESOURCE_LOCAL_PATH . "138.xml";
$OUT = fopen($resource_path, "w+");
fwrite($OUT, $xml);
fclose($OUT);
//echo "time: ". Functions::time_elapsed()."\n";
$elapsed_time_sec = microtime(1)-$timestart;
echo "\n";
echo "elapsed time = $elapsed_time_sec sec \n";
echo "elapsed time = " . $elapsed_time_sec/60 . " min \n";
echo "elapsed time = " . $elapsed_time_sec/60/60 . " hr \n";
exit("\n\n Done processing.");
?>
| <?php
/* connector for Afrotropical
estimated execution time: 41 mins.
This connector reads an EOL XML and converts PDF files stored in <mediaURL> into text description objects.
*/
//exit;
$timestart = microtime(1);
include_once(dirname(__FILE__) . "/../../config/environment.php");
require_library('connectors/AfrotropicalAPI');
$GLOBALS['ENV_DEBUG'] = false;
$taxa = AfrotropicalAPI::get_all_taxa();
$xml = SchemaDocument::get_taxon_xml($taxa);
$resource_path = CONTENT_RESOURCE_LOCAL_PATH . "138.xml";
$OUT = fopen($resource_path, "w+");
fwrite($OUT, $xml);
fclose($OUT);
//echo "time: ". Functions::time_elapsed()."\n";
$elapsed_time_sec = microtime(1)-$timestart;
echo "\n";
echo "elapsed time = $elapsed_time_sec sec \n";
echo "elapsed time = " . $elapsed_time_sec/60 . " min \n";
echo "elapsed time = " . $elapsed_time_sec/60/60 . " hr \n";
exit("\n\n Done processing.");
?>
|
Fix for collapsible-menu-active on menu header (wasn’t removing properly) | /*
* Collapsible widget extension: active menu item class
* https://github.com/filamentgroup/collapsible
* Copyright (c) 2016 Filament Group, Inc.
* Licensed under the MIT, GPL licenses.
*/
;(function ( $, window, document ) {
var headerClass = "collapsible-header";
var menuActiveClass = "collapsible-menu-active";
function clearActive( $link ) {
// remove on link, if header and remove on sibling list items
$link.removeClass( menuActiveClass )
.closest( "ul,ol" ).find( "." + menuActiveClass ).removeClass( menuActiveClass );
}
$( document ).on( "focusin focusout mouseover mouseout", function( e ) {
var $link = $( e.target ).closest( "a, ." + headerClass );
var $collapsible = $link.closest( ".collapsible" );
if( $link.length && $collapsible.length ) {
clearActive( $link );
if( e.type === "focusin" || e.type === "mouseover" ) {
$link.addClass( menuActiveClass );
}
}
});
})(jQuery, window, document);
| /*
* Collapsible widget extension: active menu item class
* https://github.com/filamentgroup/collapsible
* Copyright (c) 2016 Filament Group, Inc.
* Licensed under the MIT, GPL licenses.
*/
;(function ( $, window, document ) {
var headerClass = "collapsible-header";
var menuActiveClass = "collapsible-menu-active";
function clearActive( $link ) {
$link.closest( "ul,ol" ).find( "." + menuActiveClass ).removeClass( menuActiveClass );
}
$( document ).on( "focusin focusout mouseover mouseout", function( e ) {
var $link = $( e.target ).closest( "a, ." + headerClass );
var $collapsible = $link.closest( ".collapsible" );
if( $link.length && $collapsible.length ) {
clearActive( $link );
if( e.type === "focusin" || e.type === "mouseover" ) {
$link.addClass( menuActiveClass );
}
}
});
})(jQuery, window, document);
|
Fix loading media list row layout | import cx from 'clsx';
import React from 'react';
import PropTypes from 'prop-types';
import MediaLoadingIndicator from './MediaLoadingIndicator';
const LoadingRow = ({
className,
selected = false,
...attrs
}) => (
<div
className={cx('MediaListRow', 'is-loading', className, selected && 'is-selected')}
{...attrs}
>
<MediaLoadingIndicator className="MediaListRow-loader" />
<div className="MediaListRow-data">
<div className="MediaListRow-artist">
{' … '}
</div>
<div className="MediaListRow-title">
{' … '}
</div>
</div>
<div className="MediaListRow-duration">
{' … '}
</div>
<div className="MediaListRow-icon" />
</div>
);
LoadingRow.propTypes = {
className: PropTypes.string,
selected: PropTypes.bool,
};
export default LoadingRow;
| import cx from 'clsx';
import React from 'react';
import PropTypes from 'prop-types';
import MediaLoadingIndicator from './MediaLoadingIndicator';
const LoadingRow = ({
className,
selected = false,
...attrs
}) => (
<div
className={cx('MediaListRow', 'is-loading', className, selected && 'is-selected')}
{...attrs}
>
<MediaLoadingIndicator className="MediaListRow-loader" />
<div className="MediaListRow-artist">
{' … '}
</div>
<div className="MediaListRow-title">
{' … '}
</div>
<div className="MediaListRow-duration">
{' … '}
</div>
</div>
);
LoadingRow.propTypes = {
className: PropTypes.string,
selected: PropTypes.bool,
};
export default LoadingRow;
|
Add spaces around equal signs. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
setup.py
Part of sirup project
(c) 2017 Copyright Rezart Qelibari <rqelibari@users.noreply.github.com>
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.
"""
# Support setuptools only, distutils has a divergent and more annoying API
from setuptools import setup, find_packages
setup(
packages = find_packages(),
install_requires = [
'invoke'
],
setup_requires = ['pytest-runner'],
extras_require = {
'dev': [
'flake8',
'Sphinx',
'pytest'
]
}
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
setup.py
Part of sirup project
(c) 2017 Copyright Rezart Qelibari <rqelibari@users.noreply.github.com>
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.
"""
# Support setuptools only, distutils has a divergent and more annoying API
from setuptools import setup, find_packages
setup(
packages=find_packages(),
install_requires=[
'invoke'
],
setup_requires=['pytest-runner'],
extras_require={
'dev': [
'flake8',
'Sphinx',
'pytest'
]
}
)
|
Fix typo in test description | "use strict";
const { assert } = require("chai");
const { describe, it } = require("mocha-sugar-free");
const { JSDOM, VirtualConsole } = require("../..");
describe("API: virtual console jsdomErrors", () => {
// Note that web-platform-tests do not log CSS parsing errors, so this has to be an API test.
it("should not emit invalid stylesheet errors due to spaces (GH-2123)", () => {
const virtualConsole = new VirtualConsole();
const errors = [];
virtualConsole.on("jsdomError", e => {
errors.push(e);
});
// eslint-disable-next-line no-new
new JSDOM(`
<html>
<head></head>
<body>
<style>
.cool-class {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}
</style>
<p class="cool-class">
Hello!
</p>
</body>
</html>
`, { virtualConsole });
assert.isEmpty(errors);
});
});
| "use strict";
const { assert } = require("chai");
const { describe, it } = require("mocha-sugar-free");
const { JSDOM, VirtualConsole } = require("../..");
describe("API: virtual console jsdomErrors", () => {
// Note that web-platform-tests do not log CSS parsing errors, so this has to be an API test.
it("should not omit invalid stylesheet errors due to spaces (GH-2123)", () => {
const virtualConsole = new VirtualConsole();
const errors = [];
virtualConsole.on("jsdomError", e => {
errors.push(e);
});
// eslint-disable-next-line no-new
new JSDOM(`
<html>
<head></head>
<body>
<style>
.cool-class {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}
</style>
<p class="cool-class">
Hello!
</p>
</body>
</html>
`, { virtualConsole });
assert.isEmpty(errors);
});
});
|
Clear highlight when the animation finishes | // ONLY works for numbers
function countingSort(array, maxValue) {
highlightCode([0]);
if (array.constructor !== Array || array.length == 0) {
highlightCode([1]);
return [];
}
highlightCode([3, 4, 6]);
var valueCount = Array.apply(null, Array(maxValue)).map(Number.prototype.valueOf, 0);
var value;
for (var i = 0; i < array.length; i++) {
value = array[i];
highlight(i, "#unsortedArray");
valueCount[value] += 1;
countUpdate(value);
clearHighlight("#countingArray");
}
highlightCode([11,12,13]);
var result = new Array(array.list);
var index = 0;
for (var i = 0; i < valueCount.length; i++) {
highlightCode([14]);
for (var j = 0; j < valueCount[i]; j++) {
result[index] = i;
sortedUpdate(index, i);
index++;
}
highlightCode([13]);
}
highlightCode([20]);
clearHighlight("#countingArray");
clearHighlight("#sortedArray");
return result;
}
| // ONLY works for numbers
function countingSort(array, maxValue) {
highlightCode([0]);
if (array.constructor !== Array || array.length == 0) {
highlightCode([1]);
return [];
}
highlightCode([3, 4, 6]);
var valueCount = Array.apply(null, Array(maxValue)).map(Number.prototype.valueOf, 0);
var value;
for (var i = 0; i < array.length; i++) {
value = array[i];
highlight(i, "#unsortedArray");
valueCount[value] += 1;
countUpdate(value);
clearHighlight("#countingArray");
}
highlightCode([11,12,13]);
var result = new Array(array.list);
var index = 0;
for (var i = 0; i < valueCount.length; i++) {
highlightCode([14]);
for (var j = 0; j < valueCount[i]; j++) {
result[index] = i;
sortedUpdate(index, i);
index++;
}
highlightCode([13]);
}
highlightCode([20]);
return result;
}
|
Add Model::transform() for simple transformer support.
Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com> | <?php namespace Orchestra\Model;
use Closure;
use Illuminate\Database\Eloquent\Model;
abstract class Eloquent extends Model
{
/**
* Determine if the model instance uses soft deletes.
*
* @return bool
*/
public function isSoftDeleting()
{
return (property_exists($this, 'forceDeleting') && $this->forceDeleting === false);
}
/**
* Execute a Closure within a transaction.
*
* @param \Closure $callback
*
* @return mixed
*
* @throws \Throwable
*/
public function transaction(Closure $callback)
{
return $this->getConnection()->transaction($callback);
}
/**
* Transform each attribute in the model using a callback.
*
* @param callable $callback
*
* @return \Illuminate\Support\Fluent
*/
public function transform(callable $callback)
{
return new Illuminate\Support\Fluent($callback($this));
}
}
| <?php namespace Orchestra\Model;
use Closure;
use Illuminate\Database\Eloquent\Model;
abstract class Eloquent extends Model
{
/**
* Determine if the model instance uses soft deletes.
*
* @return bool
*/
public function isSoftDeleting()
{
return (property_exists($this, 'forceDeleting') && $this->forceDeleting === false);
}
/**
* Execute a Closure within a transaction.
*
* @param \Closure $callback
*
* @return mixed
*
* @throws \Throwable
*/
public function transaction(Closure $callback)
{
return $this->getConnection()->transaction($callback);
}
}
|
Switch which name is used as a metadata key | '''
Main interface to BSE functionality
'''
from . import io
def get_basis_set(name):
'''Reads a json basis set file given only the name
The path to the basis set file is taken to be the 'data' directory
in this project
'''
return io.read_table_basis_by_name(name)
def get_metadata(keys=None, key_filter=None):
if key_filter:
raise RuntimeError("key_filter not implemented")
avail_names = io.get_available_names()
metadata = {}
for n in avail_names:
bs = io.read_table_basis_by_name(n)
displayname = bs['basisSetName']
defined_elements = list(bs['basisSetElements'].keys())
function_types = set()
for e in bs['basisSetElements'].values():
for s in e['elementElectronShells']:
function_types.add(s['shellFunctionType'])
metadata[n] = {
'displayname': displayname,
'elements': defined_elements,
'functiontypes': list(function_types),
}
return metadata
| '''
Main interface to BSE functionality
'''
from . import io
def get_basis_set(name):
'''Reads a json basis set file given only the name
The path to the basis set file is taken to be the 'data' directory
in this project
'''
return io.read_table_basis_by_name(name)
def get_metadata(keys=None, key_filter=None):
if key_filter:
raise RuntimeError("key_filter not implemented")
avail_names = io.get_available_names()
metadata = {}
for n in avail_names:
bs = io.read_table_basis_by_name(n)
common_name = bs['basisSetName']
defined_elements = list(bs['basisSetElements'].keys())
function_types = set()
for e in bs['basisSetElements'].values():
for s in e['elementElectronShells']:
function_types.add(s['shellFunctionType'])
metadata[common_name] = {
'mangled_name': n,
'elements': defined_elements,
'functiontypes': list(function_types),
}
return metadata
|
Add scopes to test framework
Review URL: http://codereview.chromium.org/211045
git-svn-id: 1dc80909446f7a7ee3e21dd4d1b8517df524e9ee@238 fc8a088e-31da-11de-8fef-1f5ae417a2df | // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.sdk.internal.tools.v8;
import java.util.HashMap;
import java.util.Map;
/**
* Known V8 VM debugger commands and events.
*/
public enum DebuggerCommand {
CONTINUE("continue"),
EVALUATE("evaluate"),
BACKTRACE("backtrace"),
FRAME("frame"),
SCRIPTS("scripts"),
SOURCE("source"),
SCOPE("scope"),
SETBREAKPOINT("setbreakpoint"),
CHANGEBREAKPOINT("changebreakpoint"),
CLEARBREAKPOINT("clearbreakpoint"),
LOOKUP("lookup"),
// Events
BREAK("break"),
EXCEPTION("exception"),
AFTER_COMPILE("afterCompile"),
;
public final String value;
DebuggerCommand(String value) {
this.value = value;
}
private static final Map<String, DebuggerCommand> valueToCommandMap =
new HashMap<String, DebuggerCommand>();
static {
for (DebuggerCommand c : values()) {
valueToCommandMap.put(c.value, c);
}
}
/**
* @param value the DebuggerCommand string value
* @return the DebuggerCommand instance or null if none corresponds to value
*/
public static DebuggerCommand forString(String value) {
if (value == null) {
return null;
}
return valueToCommandMap.get(value);
}
}
| // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.sdk.internal.tools.v8;
import java.util.HashMap;
import java.util.Map;
/**
* Known V8 VM debugger commands and events.
*/
public enum DebuggerCommand {
CONTINUE("continue"),
EVALUATE("evaluate"),
BACKTRACE("backtrace"),
FRAME("frame"),
SCRIPTS("scripts"),
SOURCE("source"),
SETBREAKPOINT("setbreakpoint"),
CHANGEBREAKPOINT("changebreakpoint"),
CLEARBREAKPOINT("clearbreakpoint"),
LOOKUP("lookup"),
// Events
BREAK("break"),
EXCEPTION("exception"),
AFTER_COMPILE("afterCompile"),
;
public final String value;
DebuggerCommand(String value) {
this.value = value;
}
private static final Map<String, DebuggerCommand> valueToCommandMap =
new HashMap<String, DebuggerCommand>();
static {
for (DebuggerCommand c : values()) {
valueToCommandMap.put(c.value, c);
}
}
/**
* @param value the DebuggerCommand string value
* @return the DebuggerCommand instance or null if none corresponds to value
*/
public static DebuggerCommand forString(String value) {
if (value == null) {
return null;
}
return valueToCommandMap.get(value);
}
}
|
Update post body data type | package com.nmuzychuk.blog.model;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
/**
* Simple object representing a post.
*/
@Entity
public class Post {
@ManyToOne
private User user;
@Id
@GeneratedValue
private Long id;
private String title;
@Lob
private String body;
@OneToMany(mappedBy = "post")
private Set<Comment> comments = new HashSet<>();
protected Post() {
}
public Post(User user, String title, String body) {
this.user = user;
this.title = title;
this.body = body;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Long getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
}
| package com.nmuzychuk.blog.model;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
/**
* Simple object representing a post.
*/
@Entity
public class Post {
@ManyToOne
private User user;
@Id
@GeneratedValue
private Long id;
private String title;
private String body;
@OneToMany(mappedBy = "post")
private Set<Comment> comments = new HashSet<>();
protected Post() {
}
public Post(User user, String title, String body) {
this.user = user;
this.title = title;
this.body = body;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Long getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
}
|
Update library on finish state manual set. | var notifier = require('./notifier');
var xbmc = require('../notifiers/xbmc');
notifier.use(xbmc);
var Item = require('../models/item').Item;
var ItemTypes = require('../models/item').ItemTypes;
var ItemStates = require('../models/item').ItemStates;
var ItemTypeIcons = require('../models/item').ItemTypeIcons;
exports.changeState = function(req, res) {
Item.findById(req.query.id, function(err, item) {
if (err) {
res.redirect('/error', { error: err });
} else {
item.state = req.query.state; //TODO vulnerability (validate)
if (item.state === ItemStates.finished) {
item.planNextCheck(0); /// Cancel next check, if any.
notifier.updateLibrary(item);
} else {
item.planNextCheck(1);
}
item.save(function(err) {
if (err) {
console.log(err);
res.redirect('/error', { error: err });
}
}); //TODO log
res.redirect('/list');
}
});
};
| var Item = require('../models/item').Item;
var ItemTypes = require('../models/item').ItemTypes;
var ItemStates = require('../models/item').ItemStates;
var ItemTypeIcons = require('../models/item').ItemTypeIcons;
exports.changeState = function(req, res) {
Item.findById(req.query.id, function(err, item) {
if (err) {
res.redirect('/error', { error: err });
} else {
item.state = req.query.state; //TODO vulnerability (validate)
if (item.state === ItemStates.finished)
item.planNextCheck(0); /// Cancel next check, if any.
else
item.planNextCheck(1);
item.save(function(err) {
if (err) {
console.log(err);
res.redirect('/error', { error: err });
}
}); //TODO log
res.redirect('/list');
}
});
};
|
Add index.html alias on api | """
Main budget web app (backend)
Written by Fela Maslen, 2016
"""
from flask import Flask, request, render_template
from srv.config import PIE_TOLERANCE
from srv.misc import get_serial
from srv.rest_api import WebAPI
APP = Flask('budget')
@APP.route('/api', methods=['GET', 'POST'])
def api():
""" api entry point """
the_api = WebAPI(request)
if the_api.res['api_error']:
return "Unknown server error", 500
return the_api.get_json(), the_api.res['code']
@APP.route('/')
@APP.route('/index.html')
def index():
""" web app entry point """
dev = 'dev' in request.args
serial = get_serial()
return render_template('index.html', dev=dev, serial=serial, \
pie_tolerance=PIE_TOLERANCE)
if __name__ == '__main__':
APP.run(host='0.0.0.0', port=8000)
| """
Main budget web app (backend)
Written by Fela Maslen, 2016
"""
from flask import Flask, request, render_template
from srv.config import PIE_TOLERANCE
from srv.misc import get_serial
from srv.rest_api import WebAPI
APP = Flask('budget')
@APP.route('/api', methods=['GET', 'POST'])
def api():
""" api entry point """
the_api = WebAPI(request)
if the_api.res['api_error']:
return "Unknown server error", 500
return the_api.get_json(), the_api.res['code']
@APP.route('/')
def index():
""" web app entry point """
dev = 'dev' in request.args
serial = get_serial()
return render_template('index.html', dev=dev, serial=serial, \
pie_tolerance=PIE_TOLERANCE)
if __name__ == '__main__':
APP.run(host='0.0.0.0', port=8000)
|
Use webfonts.js in main to avoid load order error in built javascript. | /*
* Spreed WebRTC.
* Copyright (C) 2013-2015 struktur AG
*
* This file is part of Spreed WebRTC.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
define([ // Helper module to put non dependency base libraries together.
'modernizr',
'moment',
'Howler',
'desktop-notify',
'bigscreen',
'visibly',
'avltree',
'jed',
'audiocontext',
'rAF',
'humanize',
'sha',
'sjcl',
'text'], function() {});
| /*
* Spreed WebRTC.
* Copyright (C) 2013-2015 struktur AG
*
* This file is part of Spreed WebRTC.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
define([ // Helper module to put non dependency base libraries together.
'modernizr',
'moment',
'Howler',
'desktop-notify',
'bigscreen',
'visibly',
'avltree',
'jed',
'audiocontext',
'rAF',
'humanize',
'sha',
'sjcl',
'text',
'webfont'], function() {});
|
Add plugins to included configs | "use strict"
var rules = {
"no-yield-in-race": require("./lib/rules/no-yield-in-race"),
"yield-effects": require("./lib/rules/yield-effects"),
"no-unhandled-errors": require("./lib/rules/no-unhandled-errors")
}
var allRules = Object.keys(rules).reduce(function(result, name) {
result["redux-saga/" + name] = 2
return result
}, {})
module.exports = {
rules: rules,
configs: {
recommended: {
plugins: ['redux-saga'],
rules: {
"redux-saga/no-yield-in-race": 2,
"redux-saga/yield-effects": 2,
"redux-saga/no-unhandled-errors": 2
}
},
all: {
plugins: ['redux-saga'],
rules: allRules
}
}
}
| "use strict"
var rules = {
"no-yield-in-race": require("./lib/rules/no-yield-in-race"),
"yield-effects": require("./lib/rules/yield-effects"),
"no-unhandled-errors": require("./lib/rules/no-unhandled-errors")
}
var allRules = Object.keys(rules).reduce(function(result, name) {
result["redux-saga/" + name] = 2
return result
}, {})
module.exports = {
rules: rules,
configs: {
recommended: {
rules: {
"redux-saga/no-yield-in-race": 2,
"redux-saga/yield-effects": 2,
"redux-saga/no-unhandled-errors": 2
}
},
all: {
rules: allRules
}
}
}
|
Make fixed learning rates not crash.
There was a slight bug in this code before, which I fixed. | """ Classes that simplify learning rate modification. """
import theano
import theano.tensor as TT
class _LearningRate(object):
""" Suplerclass for learning rates. """
def __init__(self, initial_rate):
"""
Args:
initial_rate: Initial value of the learning rate. """
self._rate = initial_rate
def get(self, cycle):
"""
Args:
cycle: The symbolic global step.
Returns:
The learning rate to use for this cycle. """
return TT.as_tensor_variable(self._rate, name="lr")
class Fixed(_LearningRate):
""" The simplest type of learning rate. It is just a fixed value. """
pass
class ExponentialDecay(_LearningRate):
""" A learning rate that decays exponentially with time. """
def __init__(self, decay_rate, decay_steps, *args, **kwargs):
"""
Args:
decay_rate: Number of steps needed to decay by decay_rate.
decay_steps: The decay rate. """
super(ExponentialDecay, self).__init__(*args, **kwargs)
self.__decay_steps = decay_steps
self.__decay_rate = decay_rate
def get(self, cycle):
rate = self._rate * self.__decay_rate ** (cycle / float(self.__decay_steps))
return TT.cast(rate, theano.config.floatX)
| """ Classes that simplify learning rate modification. """
import theano
import theano.tensor as TT
class _LearningRate(object):
""" Suplerclass for learning rates. """
def __init__(self, initial_rate):
"""
Args:
initial_rate: Initial value of the learning rate. """
self._rate = initial_rate
def get(self, cycle):
"""
Args:
cycle: The symbolic global step.
Returns:
The learning rate to use for this cycle. """
return self.__rate
class Fixed(_LearningRate):
""" The simplest type of learning rate. It is just a fixed value. """
pass
class ExponentialDecay(_LearningRate):
""" A learning rate that decays exponentially with time. """
def __init__(self, decay_rate, decay_steps, *args, **kwargs):
"""
Args:
decay_rate: Number of steps needed to decay by decay_rate.
decay_steps: The decay rate. """
super(ExponentialDecay, self).__init__(*args, **kwargs)
self.__decay_steps = decay_steps
self.__decay_rate = decay_rate
def get(self, cycle):
rate = self._rate * self.__decay_rate ** (cycle / float(self.__decay_steps))
return TT.cast(rate, theano.config.floatX)
|
Include only what's necessary to test locally | // ==UserScript==
// @connect docs.google.com
// @connect rslifka.github.io
// @grant GM_addStyle
// @grant GM_getResourceText
// @grant GM_getValue
// @grant GM_log
// @grant GM_setValue
// @grant GM_xmlhttpRequest
// @match https://*.destinyitemmanager.com/*
// @name (DEVELOPMENT) Fate of All Fools
// @require file:///Users/rslifka/Dropbox/workspace/fate_of_all_fools/public/fateOfAllFools.js
// @resource fateOfAllFoolsCSS file:///Users/rslifka/Dropbox/workspace/fate_of_all_fools/public/fateOfAllFools.css
// @run-at document-idle
// ==/UserScript==
| // ==UserScript==
// @author Robert Slifka (GitHub @rslifka)
// @connect docs.google.com
// @connect rslifka.github.io
// @copyright 2017-2018, Robert Slifka (https://github.com/rslifka/fate_of_all_fools)
// @description (DEVELOPMENT) Enhancements to the Destiny Item Manager
// @grant GM_addStyle
// @grant GM_getResourceText
// @grant GM_getValue
// @grant GM_log
// @grant GM_setValue
// @grant GM_xmlhttpRequest
// @homepage https://github.com/rslifka/fate_of_all_fools
// @license MIT; https://raw.githubusercontent.com/rslifka/fate_of_all_fools/master/LICENSE.txt
// @match https://*.destinyitemmanager.com/*
// @name (DEVELOPMENT) Fate of All Fools
// @require file:///Users/rslifka/Dropbox/workspace/fate_of_all_fools/public/fateOfAllFools.js
// @resource fateOfAllFoolsCSS file:///Users/rslifka/Dropbox/workspace/fate_of_all_fools/public/fateOfAllFools.css
// @run-at document-idle
// @supportURL https://github.com/rslifka/fate_of_all_fools/issues
// ==/UserScript==
|
Enforce the fact that a discipleship teacher will always be associated with one person. | /*
* Copyright 2014 satrapu.
*
* 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 ro.satrapu.churchmanagement.persistence;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.MapsId;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
/**
* Represents a {@link Person} who is available to act in a church as a discipleship teacher.
*
* @author satrapu
*/
@Entity
@Table(name = "Discipleship_Teachers")
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class DiscipleshipTeacher extends ManagedEntityBase {
private static final long serialVersionUID = 1L;
@MapsId
@OneToOne(optional = false, fetch = FetchType.EAGER)
@JoinColumn(name = "Id")
private Person person;
}
| /*
* Copyright 2014 satrapu.
*
* 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 ro.satrapu.churchmanagement.persistence;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.MapsId;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
/**
* Represents a {@link Person} who is available to act in a church as a discipleship teacher.
*
* @author satrapu
*/
@Entity
@Table(name = "Discipleship_Teachers")
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class DiscipleshipTeacher extends ManagedEntityBase {
private static final long serialVersionUID = 1L;
@MapsId
@OneToOne
@JoinColumn(name = "Id")
private Person person;
}
|
Add fix for replaceFlowmapIcon test | import ReplaceFlowmapIcon from '../../../src/commands/appdynamics/ReplaceFlowmapIcon'
var assert = require('assert')
var href = {
baseVal: 'images/icon_nodetype_java_100x100.png'
}
var node = {
data: 'Inventory-Service',
parentElement: {
parentElement: {
querySelector: function (string) {
if (string === 'image.adsFlowNodeTypeIcon') {
return {
href: href
}
}
}
}
}
}
describe('ReplaceFlowmapIcon', function () {
describe('#apply', function () {
it('replaces the icon of a tier on the flowmap', function () {
new ReplaceFlowmapIcon('Inventory-Service', 'php').apply(node, 'data')
assert.equal(href.baseVal, 'images/icon_nodetype_php_100x100.png')
})
it('replaces the icon of a tier on the flowmap and is case insensetive', function () {
new ReplaceFlowmapIcon('Inventory-Service', 'PYTHON').apply(node, 'data')
assert.equal(href.baseVal, 'images/icon_nodetype_python_100x100.png')
})
it('leaves the icon unchanged for an unknown replace pattern', function () {
new ReplaceFlowmapIcon('Inventory-Service', 'images/icon_nodetype_ruby_100x100.png').apply(node, 'data')
assert.equal(href.baseVal, 'images/icon_nodetype_ruby_100x100.png')
})
})
})
| import ReplaceFlowmapIcon from '../../../src/commands/appdynamics/ReplaceFlowmapIcon'
var assert = require('assert')
var href = {
baseVal: 'images/icon_nodetype_java_100x100.png'
}
var node = {
data: 'Inventory-Service',
parentElement: {
parentElement: {
querySelector: function (string) {
if (string === 'image') {
return {
href: href
}
}
}
}
}
}
describe('ReplaceFlowmapIcon', function () {
describe('#apply', function () {
it('replaces the icon of a tier on the flowmap', function () {
new ReplaceFlowmapIcon('Inventory-Service', 'php').apply(node, 'data')
assert.equal(href.baseVal, 'images/icon_nodetype_php_100x100.png')
})
it('replaces the icon of a tier on the flowmap and is case insensetive', function () {
new ReplaceFlowmapIcon('Inventory-Service', 'PYTHON').apply(node, 'data')
assert.equal(href.baseVal, 'images/icon_nodetype_python_100x100.png')
})
it('leaves the icon unchanged for an unknown replace pattern', function () {
new ReplaceFlowmapIcon('Inventory-Service', 'images/icon_nodetype_ruby_100x100.png').apply(node, 'data')
assert.equal(href.baseVal, 'images/icon_nodetype_ruby_100x100.png')
})
})
})
|
Remove $middle from constructor and fix some typo | <?php
namespace Kuartet\BI\ExchangeRate;
use \Carbon\Carbon;
use \PHPUnit_Framework_TestCase;
class ExchangeRateTest extends PHPUnit_Framework_TestCase
{
public function testConstructor()
{
$code = 'IDR';
$name = 'Indonesian Rupiah';
$sell = 10000;
$buy = 11000;
$middle = 10500;
$updatedAt = Carbon::now();
$exchangeRate = new ExchangeRate($code, $name, $sell, $buy, $updatedAt);
$this->assertInstanceOf('Kuartet\BI\ExchangeRate\ExchangeRateInterface', $exchangeRate);
$this->assertEquals($code, $exchangeRate->getCode());
$this->assertEquals($name, $exchangeRate->getName());
$this->assertEquals($sell, $exchangeRate->getSell());
$this->assertEquals($buy, $exchangeRate->getBuy());
$this->assertEquals($middle, $exchangeRate->getMiddle());
$this->assertEquals($updatedAt, $exchangeRate->getUpdatedAt());
}
}
| <?php
namespace Kuartet\BI\ExchangeRate;
use \Carbon\Carbon;
use \PHPUnit_Framework_TestCase;
class ExchangeRateTest extends PHPUnit_Framework_TestCase
{
public function testConstructor()
{
$code = 'IDR';
$name = 'Indonesian Rupiah';
$sell = 10000;
$buy = 11000;
$middle = 10500;
$updatedAt = Carbon::now();
$exchangeRate = new ExchangeRate($code, $name, $sell, $buy, $middle, $updatedAt);
$this->assertInstanceOf('Kuartet\BI\ExchangeRate\ExchangeRateInterface', $exchangeRate);
$this->assertEquals($code, $exchangeRate->getCode());
$this->assertEquals($name, $exchangeRate->getName());
$this->assertEquals($sell, $exchangeRate->getSell());
$this->assertEquals($but, $exchangeRate->getBuy());
$this->assertEquals($middle, $exchangeRate->getMiddle());
$this->assertEquals($updatedAt, $exchangeRate->getUpdatedAt());
}
}
|
Use check, random, and reactive-var | Package.describe({
name:"lepozepo:cloudinary",
summary: "Upload files to Cloudinary",
version:"4.2.1",
git:"https://github.com/Lepozepo/cloudinary"
});
Npm.depends({
cloudinary: "1.3.1",
"cloudinary-jquery": "2.0.9"
});
Package.on_use(function (api){
api.versionsFrom('METEOR@1.0');
// Core Packages
api.use(["meteor-base@1.0.1","coffeescript","mongo","underscore"], ["client", "server"]);
api.use(["templating"], "client");
api.use(["check","random","reactive-var"], ["client","server"]);
// External Packages
api.use(["matb33:collection-hooks@0.7.3"], ["client", "server"],{weak:true});
// Cloudinary Client Side
api.add_files(".npm/package/node_modules/cloudinary-jquery/cloudinary-jquery.min.js","client");
// Core Files
api.add_files("server/configuration.coffee", "server");
api.add_files("server/signature.coffee", "server");
api.add_files("client/functions.coffee", "client");
api.export && api.export("Cloudinary",["server","client"]);
});
| Package.describe({
name:"lepozepo:cloudinary",
summary: "Upload files to Cloudinary",
version:"4.2.1",
git:"https://github.com/Lepozepo/cloudinary"
});
Npm.depends({
cloudinary: "1.3.1",
"cloudinary-jquery": "2.0.9"
});
Package.on_use(function (api){
api.versionsFrom('METEOR@1.0');
// Core Packages
api.use(["meteor-base@1.0.1","coffeescript","mongo","underscore"], ["client", "server"]);
api.use(["templating"], "client");
api.imply(["check","random","reactive-var"], ["client","server"]);
// External Packages
api.use(["matb33:collection-hooks@0.7.3"], ["client", "server"],{weak:true});
// Cloudinary Client Side
api.add_files(".npm/package/node_modules/cloudinary-jquery/cloudinary-jquery.min.js","client");
// Core Files
api.add_files("server/configuration.coffee", "server");
api.add_files("server/signature.coffee", "server");
api.add_files("client/functions.coffee", "client");
api.export && api.export("Cloudinary",["server","client"]);
});
|
Clarify what _MultiVAlueEnum does and where it comes from. | import random
from enum import Enum
from enum34_custom import (
_MultiValueMeta, OrderableMixin, CaseInsensitiveMultiValueEnum, MultiValueEnum
)
from types import DynamicClassAttribute
class _RandomMultiValueMeta(_MultiValueMeta):
def make_random(cls):
return random.choice(list(cls))
class _MultiValueEnum(OrderableMixin, MultiValueEnum, metaclass=_RandomMultiValueMeta):
def __str__(self):
return str(self.value)
def __repr__(self):
apostrophe = "'" if isinstance(self.value, str) else ''
return "{0}({1}{2}{1})".format(self.__class__.__qualname__, apostrophe, self)
@DynamicClassAttribute
def value(self):
"""The value of the Enum member."""
return self._value_[0]
class _CaseInsensitiveMultiValueEnum(CaseInsensitiveMultiValueEnum):
def __str__(self):
return str(self.value[0])
class _ReprMixin:
def __repr__(self):
return "{}('{}')".format(self.__class__.__qualname__, self)
def _make_float(string):
return float(string.strip().replace(',', ''))
def _make_int(string):
return int(string.strip().replace(',', ''))
| import random
from enum import Enum
from enum34_custom import _MultiValueMeta, OrderableMixin, CaseInsensitiveMultiValueEnum
from types import DynamicClassAttribute
class _MultiMeta(_MultiValueMeta):
def make_random(cls):
return random.choice(list(cls))
class _MultiValueEnum(OrderableMixin, Enum, metaclass=_MultiMeta):
def __str__(self):
return str(self.value)
def __repr__(self):
apostrophe = "'" if isinstance(self.value, str) else ''
return "{0}({1}{2}{1})".format(self.__class__.__qualname__, apostrophe, self)
@DynamicClassAttribute
def value(self):
"""The value of the Enum member."""
return self._value_[0]
class _CaseInsensitiveMultiValueEnum(CaseInsensitiveMultiValueEnum):
def __str__(self):
return str(self.value[0])
class _ReprMixin:
def __repr__(self):
return "{}('{}')".format(self.__class__.__qualname__, self)
def _make_float(string):
return float(string.strip().replace(',', ''))
def _make_int(string):
return int(string.strip().replace(',', ''))
|
Clean up syntax for JSDoc and ESLint | /*
* Copyright (c) 2017 Bonnie Schulkin. All Rights Reserved.
*
* This file is part of BoxCharter.
*
* BoxCharter is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version.
*
* BoxCharter is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
* for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with BoxCharter. If not, see <http://www.gnu.org/licenses/>.
*
*/
/**
* Class for status passed from server to client.
* @module status
*/
const adminEmail = 'admin@boxcharter.com'
const contactAdmin = `Please report this error to ${adminEmail}`
const statusStrings = {
success: 'alert-success',
warning: 'alert-warning',
danger: 'alert-danger',
badRequest: `The server did not understand this request. ${contactAdmin}`,
contactAdmin,
}
/**
* Status object.
* @class
*/
class Status {
/**
* User constructor
* @constructor
* @param {string} type - type of alert for front end
* @param {string} msg - message for the allert
*/
constructor(type, msg) {
this.alertType = type
this.text = msg
this.clrAlertClosed = false // used by client
}
}
module.exports = {
Status,
statusStrings,
}
| /*
* Copyright (c) 2017 Bonnie Schulkin. All Rights Reserved.
*
* This file is part of BoxCharter.
*
* BoxCharter is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version.
*
* BoxCharter is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
* for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with BoxCharter. If not, see <http://www.gnu.org/licenses/>.
*
*/
class Status {
constructor(type, msg) {
this.alertType = type
this.text = msg
this.clrAlertClosed = false // for ui
}
}
const adminEmail = 'admin@boxcharter.com'
const contactAdmin = `Please report this error to ${adminEmail}`
const statusStrings = {
success: 'alert-success',
warning: 'alert-warning',
danger: 'alert-danger',
contactAdmin: contactAdmin,
badRequest: `The server did not understand this request. ${contactAdmin}`
}
module.exports = {
Status: Status,
statusStrings: statusStrings }
|
Fix incorrect default share images. | {{-- General social metadata --}}
<link rel="canonical" href="{{ URL::current() }}"/>
<meta name="description"
content="@yield('meta_description', 'Vote for your favorite ' . setting('candidate_type') . ' who has done kickass things in the world this year.')"/>
{{-- Twitter --}}
<meta name="twitter:site" content="@dosomething"/>
<meta name="twitter:creator" content="@dosomething"/>
<meta name="twitter:url" content="{{ URL::current() }}"/>
<meta name="twitter:title" content="@yield('meta_title', setting('site_title'))"/>
<meta name="twitter:description"
content="@yield('meta_description', 'Vote for your favorite ' . setting('candidate_type') . ' who has done kickass things in the world.')"/>
<meta name="twitter:image" content="@yield('meta_image', asset(setting('twitter_share', 'assets/images/twitter_share.default.jpg')))"/>
{{-- Facebook --}}
<meta property="og:site_name" content="{{ setting('site_title') }}"/>
<meta property="og:title" content="@yield('meta_title', setting('site_title'))"/>
<meta property="og:image" content="@yield('meta_image', asset(setting('facebook_share', 'assets/images/facebook_share.default.jpg')))"/>
| {{-- General social metadata --}}
<link rel="canonical" href="{{ URL::current() }}"/>
<meta name="description"
content="@yield('meta_description', 'Vote for your favorite ' . setting('candidate_type') . ' who has done kickass things in the world this year.')"/>
{{-- Twitter --}}
<meta name="twitter:site" content="@dosomething"/>
<meta name="twitter:creator" content="@dosomething"/>
<meta name="twitter:url" content="{{ URL::current() }}"/>
<meta name="twitter:title" content="@yield('meta_title', setting('site_title'))"/>
<meta name="twitter:description"
content="@yield('meta_description', 'Vote for your favorite ' . setting('candidate_type') . ' who has done kickass things in the world.')"/>
<meta name="twitter:image" content="@yield('meta_image', asset(setting('facebook_share', 'assets/images/facebook_share.default.jpg')))"/>
{{-- Facebook --}}
<meta property="og:site_name" content="{{ setting('site_title') }}"/>
<meta property="og:title" content="@yield('meta_title', setting('site_title'))"/>
<meta property="og:image" content="@yield('meta_image', asset(setting('twitter_share', 'assets/images/twitter_share.default.jpg')))"/>
|
Rename previous to prev for consistency. | // Obtain ALL anchors on the page.
var links = document.links;
// The previous/next urls if they exist.
var prev = findHref("prev");
var next = findHref("next");
/**
* Find the href for a given name.
* @param {String} The name of the anchor to search for.
* @return {String} The href for a given tag, otherwise an empty string.
*/
function findHref(name) {
for (var index = 0; index < links.length; ++index) {
// The complete anchor HTML element (<a>).
var anchor = links[index];
// Not all anchors have text, rels or classes defined.
var rel = (anchor.rel !== undefined) ? anchor.rel : '';
var text = (anchor.text !== undefined) ? anchor.text.toLowerCase() : '';
var class_name = (anchor.className !== undefined) ? anchor.className : '';
if (rel.indexOf(name) > -1 || text.indexOf(name) > -1 || class_name.indexOf(name) > -1) {
return anchor.href;
}
}
}
// Go to the next/previous pages using the arrow keys.
document.addEventListener('keydown', function(event) {
if(event.keyCode == 37) {
if (prev) chrome.extension.sendMessage({redirect: prev});
}
else if(event.keyCode == 39) {
if (next) chrome.extension.sendMessage({redirect: next});
}
});
| // Obtain ALL anchors on the page.
var links = document.links;
// The previous/next urls if they exist.
var previous = findHref("prev");
var next = findHref("next");
/**
* Find the href for a given name.
* @param {String} The name of the anchor to search for.
* @return {String} The href for a given tag, otherwise an empty string.
*/
function findHref(name) {
for (var index = 0; index < links.length; ++index) {
// The complete anchor HTML element (<a>).
var anchor = links[index];
// Not all anchors have text, rels or classes defined.
var rel = (anchor.rel !== undefined) ? anchor.rel : '';
var text = (anchor.text !== undefined) ? anchor.text.toLowerCase() : '';
var class_name = (anchor.className !== undefined) ? anchor.className : '';
if (rel.indexOf(name) > -1 || text.indexOf(name) > -1 || class_name.indexOf(name) > -1) {
return anchor.href;
}
}
}
// Go to the next/previous pages using the arrow keys.
document.addEventListener('keydown', function(event) {
if(event.keyCode == 37) {
if (previous) chrome.extension.sendMessage({redirect: previous});
}
else if(event.keyCode == 39) {
if (next) chrome.extension.sendMessage({redirect: next});
}
});
|
Fix a scoping issue when calling next(). |
function handle( req, res, done )
{
var payload = req.flick.payload,
repository = payload.repository.owner.name + '/' + payload.repository.name,
index = 0,
self = this;
function next( err )
{
var handler = self.stack[ index++ ];
if( !handler || err )
{
return done( err );
}
if( !~[ '*', repository ].indexOf( handler.repository ) )
{
return next();
}
handler.handle( req, res, next );
}
next();
}
exports.handle = handle;
function use( repository, fn )
{
if( !fn )
{
fn = repository;
repository = '*';
}
this.stack.push( {
repository: repository,
handle: fn
} );
}
exports.use = use;
|
function handle( req, res, done )
{
var payload = req.flick.payload,
repository = payload.repository.owner.name + '/' + payload.repository.name,
index = 0;
function next( err )
{
var handler = this.stack[ index++ ];
if( !handler || err )
{
return done( err );
}
if( !~[ '*', repository ].indexOf( handler.repository ) )
{
return next();
}
handler.handle( req, res, next );
}
next();
}
exports.handle = handle;
function use( repository, fn )
{
if( !fn )
{
fn = repository;
repository = '*';
}
this.stack.push( {
repository: repository,
handle: fn
} );
}
exports.use = use;
|
Fix a KeyError that is raised when there are no reuslts | """This module provides a SearchResults class."""
from types import GeneratorType
from ..resources import Record, StatsResult
from ..swimlane_dict import SwimlaneDict
__metaclass__ = type
class SearchResult:
"""A class that wraps a Swimlane search result."""
def __init__(self, report, resp):
"""Init a SearchResult.
Args:
report (Report): The report that was used to initiate the search.
resp (SwimlaneDict): The JSON response from a search request.
"""
self.is_stats = isinstance(resp, GeneratorType)
if self.is_stats:
self.stats = (StatsResult(SwimlaneDict(r)) for r in resp)
else:
self.report = report
self.count = resp["count"]
self.offset = resp["offset"]
self.limit = resp["limit"]
results = []
if report.applicationIds[0] in resp['results']:
results = resp["results"][report.applicationIds[0]]
self.records = (Record(SwimlaneDict(r)) for r in results)
| """This module provides a SearchResults class."""
from types import GeneratorType
from ..resources import Record, StatsResult
from ..swimlane_dict import SwimlaneDict
__metaclass__ = type
class SearchResult:
"""A class that wraps a Swimlane search result."""
def __init__(self, report, resp):
"""Init a SearchResult.
Args:
report (Report): The report that was used to initiate the search.
resp (SwimlaneDict): The JSON response from a search request.
"""
self.is_stats = isinstance(resp, GeneratorType)
if self.is_stats:
self.stats = (StatsResult(SwimlaneDict(r)) for r in resp)
else:
self.report = report
self.count = resp["count"]
self.offset = resp["offset"]
self.limit = resp["limit"]
results = (resp["results"][report.applicationIds[0]]
if resp["results"] else [])
self.records = (Record(SwimlaneDict(r)) for r in results)
|
Drop any unknown request fields when converting into index document
Previously, convert_request_json_into_index_json relied on the request
being sent through the dmutils.apiclient, which dropped any fields that
aren't supposed to be indexed. This means that dmutils contains a copy
of the filter and text fields lists.
Instead, new converting functions only keeps text and filter fields from
the request, so it can accept any service document for indexing. | import six
from .query_builder import FILTER_FIELDS, TEXT_FIELDS
from .conversions import strip_and_lowercase
FILTER_FIELDS_SET = set(FILTER_FIELDS)
TEXT_FIELDS_SET = set(TEXT_FIELDS)
def process_values_for_matching(values):
if isinstance(values, list):
return [strip_and_lowercase(value) for value in values]
elif isinstance(values, six.string_types):
return strip_and_lowercase(values)
return values
def convert_request_json_into_index_json(request_json):
index_json = {}
for field in request_json:
if field in FILTER_FIELDS_SET:
index_json["filter_" + field] = process_values_for_matching(
request_json[field]
)
if field in TEXT_FIELDS_SET:
index_json[field] = request_json[field]
return index_json
| import six
from .query_builder import FILTER_FIELDS, TEXT_FIELDS
from .conversions import strip_and_lowercase
def process_values_for_matching(request_json, key):
values = request_json[key]
if isinstance(values, list):
return [strip_and_lowercase(value) for value in values]
elif isinstance(values, six.string_types):
return strip_and_lowercase(values)
return values
def convert_request_json_into_index_json(request_json):
filter_fields = [field for field in request_json if field in FILTER_FIELDS]
for field in filter_fields:
request_json["filter_" + field] = \
process_values_for_matching(request_json, field)
if field not in TEXT_FIELDS:
del request_json[field]
return request_json
|
Update tests to test for prototype mocking | var assert = require('chai').assert;
var makeMock = require('../lib/makeMock');
function API() {
}
API.someFunction = function someFunction() {}
API.prototype.anotherFunction = function() {
};
var mockAPI = makeMock(API);
var newAPI = new mockAPI();
describe('makeMock', function () {
beforeEach(function () {
mockAPI.reset();
newAPI.reset();
});
it('should mock object properties correctly', function () {
assert.equal(typeof mockAPI.someFunction, 'function');
assert.equal(typeof mockAPI.someFunction.assertCalledOnceWith, 'function');
});
it('should mock object prototype correctly', function () {
assert.equal(typeof newAPI.anotherFunction, 'function');
assert.equal(typeof newAPI.anotherFunction.assertCalledOnceWith, 'function');
});
it('should allow definition of return values', function () {
mockAPI.someFunction.returns(10);
assert.equal(mockAPI.someFunction(), 10);
});
it('should allow definition of return values on prototype functions', function () {
newAPI.anotherFunction.returns('some value');
assert.equal(newAPI.anotherFunction(), 'some value');
});
}); | var assert = require('chai').assert;
var makeMock = require('../lib/makeMock');
var api = {
someFunction: function() {
},
prototype: {
anotherFunction: function() {
}
}
}
var mockAPI = makeMock(api);
var newAPI = new mockAPI();
describe('makeMock', function () {
beforeEach(function () {
mockAPI.reset();
newAPI.reset();
});
it('should mock object properties correctly', function () {
assert.equal(typeof mockAPI.someFunction, 'function');
assert.equal(typeof mockAPI.someFunction.assertCalledOnceWith, 'function');
});
it('should mock object prototype correctly', function () {
assert.equal(typeof newAPI.anotherFunction, 'function');
assert.equal(typeof newAPI.anotherFunction.assertCalledOnceWith, 'function');
});
it('should allow definition of return values', function () {
mockAPI.someFunction.returns(10);
assert.equal(mockAPI.someFunction(), 10);
});
it('should allow definition of return values on prototype functions', function () {
newAPI.anotherFunction.returns('some value');
assert.equal(newAPI.anotherFunction(), 'some value');
});
}); |
Fix CraftBukkit handle field being serialized | package roycurtis.signshopexport.json;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
public class Exclusions implements ExclusionStrategy
{
@Override
public boolean shouldSkipField(FieldAttributes f)
{
String name = f.getName();
return
// Ignore dynamic CraftBukkit handle field
name.equalsIgnoreCase("handle")
// Ignore book page contents
|| name.equalsIgnoreCase("pages")
// Ignore unsupported tags
|| name.equalsIgnoreCase("unhandledTags")
// Ignore redundant data object
|| name.equalsIgnoreCase("data")
// Ignore hide flags
|| name.equalsIgnoreCase("hideFlag")
// Ignore shield patterns
|| name.equalsIgnoreCase("blockEntityTag");
}
@Override
public boolean shouldSkipClass(Class<?> clazz)
{
String name = clazz.getSimpleName();
if ( name.equalsIgnoreCase("ItemStack") )
if ( clazz.getTypeName().startsWith("net.minecraft.server") )
return true;
return name.equalsIgnoreCase("ChatComponentText");
}
} | package roycurtis.signshopexport.json;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
public class Exclusions implements ExclusionStrategy
{
@Override
public boolean shouldSkipField(FieldAttributes f)
{
String name = f.getName();
// Ignore book page contents
return name.equalsIgnoreCase("pages")
// Ignore unsupported tags
|| name.equalsIgnoreCase("unhandledTags")
// Ignore redundant data object
|| name.equalsIgnoreCase("data")
// Ignore hide flags
|| name.equalsIgnoreCase("hideFlag")
// Ignore shield patterns
|| name.equalsIgnoreCase("blockEntityTag");
}
@Override
public boolean shouldSkipClass(Class<?> clazz)
{
String name = clazz.getSimpleName();
if ( name.equalsIgnoreCase("ItemStack") )
if ( clazz.getTypeName().startsWith("net.minecraft.server") )
return true;
return name.equalsIgnoreCase("ChatComponentText");
}
} |
Use approrpiate transform implementation in canvas backend. | /**
* Copyright 2010 The PlayN 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 playn.html;
import com.google.gwt.canvas.dom.client.Context2d;
import playn.core.AbstractLayer;
import playn.core.StockInternalTransform;
abstract class HtmlLayerCanvas extends AbstractLayer {
abstract void paint(Context2d ctx, float parentAlpha);
protected HtmlLayerCanvas() {
super(HtmlPlatform.hasTypedArraySupport ?
new HtmlInternalTransform() : new StockInternalTransform());
}
void transform(Context2d ctx) {
ctx.translate(originX, originY);
ctx.transform(transform.m00(), transform.m01(), transform.m10(),
transform.m11(), transform.tx() - originX, transform.ty() - originY);
ctx.translate(-originX, -originY);
}
}
| /**
* Copyright 2010 The PlayN 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 playn.html;
import com.google.gwt.canvas.dom.client.Context2d;
import playn.core.AbstractLayer;
abstract class HtmlLayerCanvas extends AbstractLayer {
abstract void paint(Context2d ctx, float parentAlpha);
protected HtmlLayerCanvas() {
super(new HtmlInternalTransform());
}
void transform(Context2d ctx) {
ctx.translate(originX, originY);
ctx.transform(transform.m00(), transform.m01(), transform.m10(),
transform.m11(), transform.tx() - originX, transform.ty() - originY);
ctx.translate(-originX, -originY);
}
}
|
Remove commented import that isn't used | package async
func Waterfall(routines []Routine, callbacks ...Done) {
l := New()
l.Multiple(routines...)
l.RunWaterfall(callbacks...)
}
func (l *List) RunWaterfall(callbacks ...Done) {
fall := fall(l, callbacks...)
next := next(l, callbacks...)
l.Wait.Add(l.Len())
fall(next)
}
func fall(l *List, callbacks ...Done) func(Done, ...interface{}) {
return func(next Done, args ...interface{}) {
e := l.Front()
_, r := l.Remove(e)
// Run the first waterfall routine and give it the next function, and
// any arguments that were provided
go r(next, args...)
l.Wait.Wait()
}
}
func next(l *List, callbacks ...Done) Done {
fall := fall(l, callbacks...)
return func(err error, args ...interface{}) {
next := next(l, callbacks...)
l.Wait.Done()
if err != nil || l.Len() == 0 {
// Just in case it's an error, let's make sure we've cleared
// all of the sync.WaitGroup waits that we initiated.
for i := 0; i < l.Len(); i++ {
l.Wait.Done()
}
// Send the results to the callbacks
for i := 0; i < len(callbacks); i++ {
callbacks[i](err, args...)
}
return
}
// Run the next waterfall routine with any arguments that were provided
fall(next, args...)
return
}
}
| package async
// import "fmt"
func Waterfall(routines []Routine, callbacks ...Done) {
l := New()
l.Multiple(routines...)
l.RunWaterfall(callbacks...)
}
func (l *List) RunWaterfall(callbacks ...Done) {
fall := fall(l, callbacks...)
next := next(l, callbacks...)
l.Wait.Add(l.Len())
fall(next)
}
func fall(l *List, callbacks ...Done) func(Done, ...interface{}) {
return func(next Done, args ...interface{}) {
e := l.Front()
_, r := l.Remove(e)
// Run the first waterfall routine and give it the next function, and
// any arguments that were provided
go r(next, args...)
l.Wait.Wait()
}
}
func next(l *List, callbacks ...Done) Done {
fall := fall(l, callbacks...)
return func(err error, args ...interface{}) {
next := next(l, callbacks...)
l.Wait.Done()
if err != nil || l.Len() == 0 {
// Just in case it's an error, let's make sure we've cleared
// all of the sync.WaitGroup waits that we initiated.
for i := 0; i < l.Len(); i++ {
l.Wait.Done()
}
// Send the results to the callbacks
for i := 0; i < len(callbacks); i++ {
callbacks[i](err, args...)
}
return
}
// Run the next waterfall routine with any arguments that were provided
fall(next, args...)
return
}
}
|
Fix exception - batch is not required field of AR | from bika.lims.browser.sample import SamplesView as _SV
from bika.lims.permissions import *
from Products.CMFCore.utils import getToolByName
from zope.interface import implements
from Products.CMFPlone.utils import safe_unicode
import plone
class SamplesView(_SV):
def __init__(self, context, request):
super(SamplesView, self).__init__(context, request)
self.view_url = self.context.absolute_url() + "/samples"
if 'path' in self.contentFilter:
del(self.contentFilter['path'])
def contentsMethod(self, contentFilter):
tool = getToolByName(self.context, self.catalog)
state = [x for x in self.review_states if x['id'] == self.review_state][0]
for k, v in state['contentFilter'].items():
self.contentFilter[k] = v
tool_samples = tool(contentFilter)
samples = {}
for sample in (p.getObject() for p in tool_samples):
for ar in sample.getAnalysisRequests():
batch = ar.getBatch()
if batch and ar.getBatch().UID() == self.context.UID():
samples[sample.getId()] = sample
return samples.values()
| from bika.lims.browser.sample import SamplesView as _SV
from bika.lims.permissions import *
from Products.CMFCore.utils import getToolByName
from zope.interface import implements
from Products.CMFPlone.utils import safe_unicode
import plone
class SamplesView(_SV):
def __init__(self, context, request):
super(SamplesView, self).__init__(context, request)
self.view_url = self.context.absolute_url() + "/samples"
if 'path' in self.contentFilter:
del(self.contentFilter['path'])
def contentsMethod(self, contentFilter):
tool = getToolByName(self.context, self.catalog)
state = [x for x in self.review_states if x['id'] == self.review_state][0]
for k, v in state['contentFilter'].items():
self.contentFilter[k] = v
tool_samples = tool(contentFilter)
samples = {}
for sample in (p.getObject() for p in tool_samples):
for ar in sample.getAnalysisRequests():
if ar.getBatch().UID() == self.context.UID():
samples[sample.getId()] = sample
return samples.values()
|
Fix driver detection for elephantsql | package org.cloudfoundry.runtime.service.relational;
import org.cloudfoundry.runtime.env.*;
import org.cloudfoundry.runtime.service.AbstractDataSourceCreator;
import org.springframework.util.Assert;
import javax.sql.DataSource;
/**
* Simplified access to RDBMS service.
*
* @author Thomas Risberg
*
*/
public class RdbmsServiceCreator extends AbstractDataSourceCreator<RdbmsServiceInfo> {
private AbstractDataSourceCreator delegate;
@Override
public DataSource createService(AbstractDataSourceServiceInfo serviceInfo) {
if (serviceInfo.getLabel() != null && (serviceInfo.getLabel().startsWith("postgres") || serviceInfo.getLabel().startsWith("elephantsql"))) {
this.delegate = new PostgresqlServiceCreator();
}
else {
this.delegate = new MysqlServiceCreator();
}
return super.createService(serviceInfo);
}
@Override
public String getDriverClassName() {
Assert.notNull(delegate, "DataSourceCreator delegate was not populated");
return delegate.getDriverClassName();
}
@Override
public String getValidationQuery() {
Assert.notNull(delegate, "DataSourceCreator delegate was not populated");
return delegate.getValidationQuery();
}
}
| package org.cloudfoundry.runtime.service.relational;
import org.cloudfoundry.runtime.env.*;
import org.cloudfoundry.runtime.service.AbstractDataSourceCreator;
import org.springframework.util.Assert;
import javax.sql.DataSource;
/**
* Simplified access to RDBMS service.
*
* @author Thomas Risberg
*
*/
public class RdbmsServiceCreator extends AbstractDataSourceCreator<RdbmsServiceInfo> {
private AbstractDataSourceCreator delegate;
@Override
public DataSource createService(AbstractDataSourceServiceInfo serviceInfo) {
if (serviceInfo.getLabel() != null && serviceInfo.getLabel().startsWith("postgres")) {
this.delegate = new PostgresqlServiceCreator();
}
else {
this.delegate = new MysqlServiceCreator();
}
return super.createService(serviceInfo);
}
@Override
public String getDriverClassName() {
Assert.notNull(delegate, "DataSourceCreator delegate was not populated");
return delegate.getDriverClassName();
}
@Override
public String getValidationQuery() {
Assert.notNull(delegate, "DataSourceCreator delegate was not populated");
return delegate.getValidationQuery();
}
}
|
Add explicit default for edu_suitable_for_home | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddEduAttributesToArticles extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('articles', function (Blueprint $table) {
$table->after('publish', function ($table) {
$table->json('edu_media_types')->nullable();
$table->json('edu_target_age_groups')->nullable();
$table->boolean('edu_suitable_for_home')->default(0);
$table->json('edu_keywords')->nullable();
});
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('articles', function (Blueprint $table) {
$table->dropColumn(['edu_media_types', 'edu_target_age_groups', 'edu_suitable_for_home', 'edu_keywords']);
});
}
}
| <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddEduAttributesToArticles extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('articles', function (Blueprint $table) {
$table->after('publish', function ($table) {
$table->json('edu_media_types')->nullable();
$table->json('edu_target_age_groups')->nullable();
$table->boolean('edu_suitable_for_home');
$table->json('edu_keywords')->nullable();
});
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('articles', function (Blueprint $table) {
$table->dropColumn(['edu_media_types', 'edu_target_age_groups', 'edu_suitable_for_home', 'edu_keywords']);
});
}
}
|
Add log interrupted and stopped | package ru.nsu.ccfit.bogush.factory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Supplier<T extends CarFactoryObject> extends SimplePeriodical implements Runnable {
private Storage<T> storage;
private static final long DEFAULT_PERIOD = 0;
private Class<T> contentType;
private Thread thread;
private static final String LOGGER_NAME = "Supplier";
private static final Logger logger = LogManager.getLogger(LOGGER_NAME);
public Supplier(Storage<T> storage, Class<T> contentType) {
this(storage, contentType, DEFAULT_PERIOD);
}
public Supplier(Storage<T> storage, Class<T> contentType, long period) {
super(period);
logger.trace("initialize with period " + period);
this.storage = storage;
this.contentType = contentType;
this.thread = new Thread(this);
thread.setName(toString());
}
@Override
public void run() {
try {
while (true) {
storage.store(contentType.newInstance());
waitPeriod();
}
} catch (IllegalAccessException | InstantiationException e) {
e.printStackTrace();
} catch (InterruptedException e) {
logger.trace("interrupted");
} finally {
logger.trace("stopped");
}
}
@Override
public String toString() {
return contentType.getSimpleName() + "-" + getClass().getSimpleName() + "-" + thread.getId();
}
public Thread getThread() {
return thread;
}
}
| package ru.nsu.ccfit.bogush.factory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Supplier<T extends CarFactoryObject> extends SimplePeriodical implements Runnable {
private Storage<T> storage;
private static final long DEFAULT_PERIOD = 0;
private Class<T> contentType;
private Thread thread;
private static final String LOGGER_NAME = "Supplier";
private static final Logger logger = LogManager.getLogger(LOGGER_NAME);
public Supplier(Storage<T> storage, Class<T> contentType) {
this(storage, contentType, DEFAULT_PERIOD);
}
public Supplier(Storage<T> storage, Class<T> contentType, long period) {
super(period);
logger.trace("initialize with period " + period);
this.storage = storage;
this.contentType = contentType;
this.thread = new Thread(this);
thread.setName(toString());
}
@Override
public void run() {
while (true) {
try {
storage.store(contentType.newInstance());
waitPeriod();
} catch (InterruptedException | IllegalAccessException | InstantiationException e) {
e.printStackTrace();
}
}
}
@Override
public String toString() {
return contentType.getSimpleName() + "-" + getClass().getSimpleName() + "-" + thread.getId();
}
public Thread getThread() {
return thread;
}
}
|
Fix spl_autoload_register so it won't conflict with other register | <?php
class Elegant {
function __construct()
{
$mod_path = APPPATH . 'models/';
if(file_exists($mod_path)) $this->_read_model_dir($mod_path);
}
// Open model directories recursively and load the models inside
private function _read_model_dir($dirpath)
{
$ci =& get_instance();
$handle = opendir($dirpath);
if(!$handle) return;
while (false !== ($filename = readdir($handle)))
{
if($filename == "." or $filename == "..") continue;
$filepath = $dirpath.$filename;
if(is_dir($filepath))
$this->_read_model_dir($filepath);
elseif(strpos(strtolower($filename), '.php') !== false)
{
$name = strtolower($filepath);
require_once $name;
}
else continue;
}
closedir($handle);
}
}
spl_autoload_register(function($class){
if(strpos($class, "Elegant\\") === 0)
{
$classname = str_replace("Elegant\\", "", $class);
$path = 'src/' . strtolower( str_replace("\\", "/", $classname) ) . EXT;
require_once $path;
}
}); | <?php
class Elegant {
function __construct()
{
$mod_path = APPPATH . 'models/';
if(file_exists($mod_path)) $this->_read_model_dir($mod_path);
}
// Open model directories recursively and load the models inside
private function _read_model_dir($dirpath)
{
$ci =& get_instance();
$handle = opendir($dirpath);
if(!$handle) return;
while (false !== ($filename = readdir($handle)))
{
if($filename == "." or $filename == "..") continue;
$filepath = $dirpath.$filename;
if(is_dir($filepath))
$this->_read_model_dir($filepath);
elseif(strpos(strtolower($filename), '.php') !== false)
{
$name = strtolower($filepath);
require_once $name;
}
else continue;
}
closedir($handle);
}
}
spl_autoload_register(function($class){
if(strpos($class, "Elegant\\") !== 0) return;
$classname = str_replace("Elegant\\", "", $class);
$path = 'src/' . strtolower( str_replace("\\", "/", $classname) ) . ".php";
require_once $path;
}); |
[Release_0.0.1] Fix DataTable in User page | $.extend( true, $.fn.dataTable.defaults, {
"autoWidth": false,
"columnDefs": [
{ width: '10%', targets: 0 },
{ width: '10%', targets: 1 },
{ width: '10%', targets: 2 },
{ width: '10%', targets: 3 },
{ width: '20%', targets: 4 },
{ width: '10%', targets: 5 },
{ width: '10%', targets: 6 },
{ width: '20%', targets: 7 },
],
"order": [[ 0, "asc" ]]
} );
$(document).ready(function() {
$('#items').DataTable();
// Breadcum
$('#breadcrumb-home').append(en.cms.breadcrumb.home);
$('#breadcrumb-user').append(en.cms.breadcrumb.user);
// Table headers
$('#header-username').append(en.cms.header.username);
$('#header-email').append(en.cms.header.email);
$('#header-firstname').append(en.cms.header.firstname);
$('#header-lastname').append(en.cms.header.lastname);
$('#header-lastlogin').append(en.cms.header.lastlogin);
$('#header-isstaff').append(en.cms.header.isstaff);
$('#header-isactive').append(en.cms.header.isactive);
$('#main-title').append(en.cms.breadcrumb.user);
$('#add').append(en.cms.action.add_user);
} );
| $.extend( true, $.fn.dataTable.defaults, {
"autoWidth": false,
"columnDefs": [
{ width: '10%', targets: 0 },
{ width: '15%', targets: 1 },
{ width: '10%', targets: 2 },
{ width: '10%', targets: 3 },
{ width: '25%', targets: 4 },
{ width: '10%', targets: 5 },
{ width: '10%', targets: 6 },
],
"order": [[ 0, "asc" ]]
} );
$(document).ready(function() {
$('#items').DataTable();
// Breadcum
$('#breadcrumb-home').append(en.cms.breadcrumb.home);
$('#breadcrumb-user').append(en.cms.breadcrumb.user);
// Table headers
$('#header-username').append(en.cms.header.username);
$('#header-email').append(en.cms.header.email);
$('#header-firstname').append(en.cms.header.firstname);
$('#header-lastname').append(en.cms.header.lastname);
$('#header-lastlogin').append(en.cms.header.lastlogin);
$('#header-isstaff').append(en.cms.header.isstaff);
$('#header-isactive').append(en.cms.header.isactive);
$('#main-title').append(en.cms.breadcrumb.user);
$('#add').append(en.cms.action.add_user);
} );
|
Add configuration properties to the service. | <?php
namespace DTS\eBaySDK\Trading\Services;
class TradingBaseService extends \DTS\eBaySDK\Services\BaseService
{
const HDR_API_VERSION = 'X-EBAY-API-COMPATIBILITY-LEVEL';
const HDR_APP_ID = 'X-EBAY-API-APP-NAME';
const HDR_CERT_ID = 'X-EBAY-API-CERT-NAME';
const HDR_CONTENT_LENGTH = 'Content-Length';
const HDR_CONTENT_TYPE = 'Content-Type';
const HDR_DEV_ID = 'X-EBAY-API-DEV-NAME';
const HDR_OPERATION_NAME = 'X-EBAY-API-CALL-NAME';
const HDR_SITE_ID = 'X-EBAY-API-SITEID';
public function __construct($config = array())
{
if (!array_key_exists(get_called_class(), self::$configProperties)) {
self::$configProperties[get_called_class()] = array(
'apiVersion' => array('required' => true),
'appId' => array('required' => false),
'certId' => array('required' => false),
'devId' => array('required' => false),
'siteId' => array('required' => true)
);
}
parent::__construct($config);
}
}
| <?php
namespace DTS\eBaySDK\Trading\Services;
class TradingBaseService extends \DTS\eBaySDK\Services\BaseService
{
const HDR_API_VERSION = 'X-EBAY-API-COMPATIBILITY-LEVEL';
const HDR_APP_ID = 'X-EBAY-API-APP-NAME';
const HDR_CERT_ID = 'X-EBAY-API-CERT-NAME';
const HDR_CONTENT_LENGTH = 'Content-Length';
const HDR_CONTENT_TYPE = 'Content-Type';
const HDR_DEV_ID = 'X-EBAY-API-DEV-NAME';
const HDR_OPERATION_NAME = 'X-EBAY-API-CALL-NAME';
const HDR_SITE_ID = 'X-EBAY-API-SITEID';
public function __construct($config = [])
{
parent::__construct($config);
}
}
|
Add missing semicolon and bracket | 'use strict';
/**
* Module dependencies
*/
import rndstr from 'rndstr';
import AuthSess from '../../models/auth-session';
import Userkey from '../../models/userkey';
/**
* Accept
*
* @param {Object} params
* @param {Object} user
* @return {Promise<object>}
*/
module.exports = (params, user) =>
new Promise(async (res, rej) =>
{
// Get 'token' parameter
const token = params.token;
if (token == null) {
return rej('token is required');
}
// Fetch token
const session = await AuthSess
.findOne({ token: token });
if (session === null) {
return rej('session not found');
}
// Generate userkey
const key = rndstr('a-zA-Z0-9', 32);
// Insert userkey doc
await Userkey.insert({
created_at: new Date(),
app: session.app,
user: user._id,
key: key
});
// Response
res();
});
| 'use strict';
/**
* Module dependencies
*/
import rndstr from 'rndstr';
import AuthSess from '../../models/auth-session';
import Userkey from '../../models/userkey';
/**
* Accept
*
* @param {Object} params
* @param {Object} user
* @return {Promise<object>}
*/
module.exports = (params, user) =>
new Promise(async (res, rej) =>
{
// Get 'token' parameter
const token = params.token;
if (token == null) {
return rej('token is required');
}
// Fetch token
const session = await AuthSess
.findOne({ token: token });
if (session === null) {
return rej('session not found');
}
// Generate userkey
const key = rndstr('a-zA-Z0-9', 32);
// Insert userkey doc
await Userkey.insert({
created_at: new Date(),
app: session.app,
user: user._id,
key: key
});
// Response
res();
}
|
Change the is_producttype template tag to return a boolean rather than a string. | from django import template
from django.conf import settings
from django.core import urlresolvers
from django.template import Context, Template
from django.utils.translation import get_language, ugettext_lazy as _
from satchmo.configuration import config_value
from satchmo.product.models import Category
from satchmo.shop.templatetags import get_filter_args
register = template.Library()
def is_producttype(product, ptype):
"""Returns True if product is ptype"""
if ptype in product.get_subtypes():
return True
else:
return False
register.filter('is_producttype', is_producttype)
def product_images(product, args=""):
args, kwargs = get_filter_args(args,
keywords=('include_main', 'maximum'),
boolargs=('include_main'),
intargs=('maximum'),
stripquotes=True)
q = product.productimage_set
if kwargs.get('include_main', True):
q = q.all()
else:
main = product.main_image
q = q.exclude(id = main.id)
maximum = kwargs.get('maximum', -1)
if maximum>-1:
q = list(q)[:maximum]
return q
register.filter('product_images', product_images)
def smart_attr(product, key):
"""Run the smart_attr function on the spec'd product
"""
return product.smart_attr(key)
register.filter('smart_attr', smart_attr)
| from django import template
from django.conf import settings
from django.core import urlresolvers
from django.template import Context, Template
from django.utils.translation import get_language, ugettext_lazy as _
from satchmo.configuration import config_value
from satchmo.product.models import Category
from satchmo.shop.templatetags import get_filter_args
register = template.Library()
def is_producttype(product, ptype):
"""Returns True if product is ptype"""
if ptype in product.get_subtypes():
return "true"
else:
return ""
register.filter('is_producttype', is_producttype)
def product_images(product, args=""):
args, kwargs = get_filter_args(args,
keywords=('include_main', 'maximum'),
boolargs=('include_main'),
intargs=('maximum'),
stripquotes=True)
q = product.productimage_set
if kwargs.get('include_main', True):
q = q.all()
else:
main = product.main_image
q = q.exclude(id = main.id)
maximum = kwargs.get('maximum', -1)
if maximum>-1:
q = list(q)[:maximum]
return q
register.filter('product_images', product_images)
def smart_attr(product, key):
"""Run the smart_attr function on the spec'd product
"""
return product.smart_attr(key)
register.filter('smart_attr', smart_attr)
|
BAP-3835: Package Manager does not take in account root folder | <?php
namespace Oro\Bundle\DistributionBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$treeBuilder->root('oro_distribution')
->children()
->scalarNode('entry_point')
->beforeNormalization()
->ifNull()
->then(
function () {
return 'install.php';
}
)
->end()
->end()
->end();
return $treeBuilder;
}
}
| <?php
namespace Oro\Bundle\DistributionBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$treeBuilder->root('oro_distribution')
->children()
->scalarNode('entry_point')
->beforeNormalization()
->ifNull()
->then(
function () {
return '/install.php';
}
)
->end()
->end()
->end();
return $treeBuilder;
}
}
|
Update settings to not require creation of default settings | 'use strict';
// Load requirements
const fs = require('fs'),
path = require('path'),
os = require('os');
// Load modules
const utils = require(__base + 'libs/utils'),
logger = require(__base + 'libs/log');
// Variables
const config = require(path.join(__base, '../config/config')),
settingsFile = path.join(config.directories.settings, 'settings.json');
// Define the recursive settings object builds
const buildSettings = function(rules) {
for ( let prop in rules ) {
Object.defineProperty(this, prop, {
get: function() { // jshint ignore:line
if ( rules[prop] !== null && typeof rules[prop] === 'object' && ! Array.isArray(rules[prop]) )
return new buildSettings(rules[prop]);
else
return rules[prop];
}
});
}
};
// Create a dynamic object
let obj = require(settingsFile);
obj.directory = config.directories.settings;
let settings = new buildSettings(obj);
// Export the object
module.exports = settings;
| 'use strict';
// Load requirements
const fs = require('fs'),
path = require('path'),
os = require('os');
// Load modules
const utils = require('../utils'),
logger = require('../log');
// Variables
const configDir = path.resolve('./config'),
settingsFile = path.join(configDir, 'settings.json');
// Create directory
if ( ! fs.existsSync(configDir) ) {
fs.mkdirSync(configDir);
}
// Create example settings
if ( ! fs.existsSync(settingsFile) ) {
fs.writeFileSync(settingsFile, JSON.stringify(require('./data/sample'), null, 4));
// logger.warn('Created a new settings file in config, please customise these settings before running again');
// process.exit(0);
}
// Define the recursive settings object builds
const buildSettings = function(rules) {
for ( let prop in rules ) {
Object.defineProperty(this, prop, {
get: function() { // jshint ignore:line
if ( rules[prop] !== null && typeof rules[prop] === 'object' && ! Array.isArray(rules[prop]) )
return new buildSettings(rules[prop]);
else
return rules[prop];
}
});
}
};
// Create a dynamic object
let settings = new buildSettings(require(settingsFile));
// Export the object
module.exports = settings;
|
Set partner 99 to have no live streaming
Set partner 99 to have content distribution
git-svn-id: 8a2ccb88241e16c78017770bc38d91d6d5396a5a@59443 6b8eccd3-e8c5-4e7d-8186-e12b5326b719 | <?php
/**
* @package deployment
*
* Adds default permissions to partner 99
*
*/
//-- Bootstraping
error_reporting(E_ALL);
require_once(dirname(__FILE__).'/../../../bootstrap.php');
require_once(ROOT_DIR . '/api_v3/bootstrap.php');
$dryRun = true; //TODO: change for real run
if($argc > 1 && $argv[1] == 'realrun')
$dryRun = false;
define("TEMPLATE_PARTNER_ID", 99 );
//-- Script start
//Get partner 99
$partner99 = PartnerPeer::retrieveByPK(TEMPLATE_PARTNER_ID);
//Enable the vast
$partner99->setEnableVast(true);
//Enable plugin metadata
$partner99->setPluginEnabled('metadata', true);
//Enable plugin metadata
$partner99->setPluginEnabled('contentDistribution', true);
//Disable plugin Live Streaming
$partner99->setLiveStreamEnabled(false);
if($dryRun)
{
KalturaLog::log('DRY RUN - Adding new permissions [Vast, CustomMetadata, Thumbnails managment] to partner [99]\n');
KalturaLog::log(var_dump($partner99));
}
else
{
KalturaLog::log('Adding new permissions [Vast, CustomMetadata, Thumbnails managment] to partner [99]');
//save changes to DB
$partner99->save();
}
KalturaLog::log('Done!'); | <?php
/**
* @package deployment
*
* Adds default permissions to partner 99
*
*/
//-- Bootstraping
error_reporting(E_ALL);
require_once(dirname(__FILE__).'/../../../bootstrap.php');
require_once(ROOT_DIR . '/api_v3/bootstrap.php');
$dryRun = true; //TODO: change for real run
if($argc > 1 && $argv[1] == 'realrun')
$dryRun = false;
define("TEMPLATE_PARTNER_ID", 99 );
//-- Script start
//Get partner 99
$partner99 = PartnerPeer::retrieveByPK(TEMPLATE_PARTNER_ID);
//Enable the vast
$partner99->setEnableVast(true);
//Enable plugin metadata
$partner99->setPluginEnabled('metadata', true);
if($dryRun)
{
KalturaLog::log('DRY RUN - Adding new permissions [Vast, CustomMetadata, Thumbnails managment] to partner [99]\n');
KalturaLog::log(var_dump($partner99));
}
else
{
KalturaLog::log('Adding new permissions [Vast, CustomMetadata, Thumbnails managment] to partner [99]');
//save changes to DB
$partner99->save();
}
KalturaLog::log('Done!'); |
wdip-dot-reporter: Allow stdout to be overwritten from config | import chalk from 'chalk'
import WDIOReporter from 'wdio-reporter'
/**
* Initialize a new `Dot` matrix test reporter.
*/
export default class DotReporter extends WDIOReporter {
constructor (options) {
/**
* make dot reporter to write to output stream by default
*/
options = Object.assign({ stdout: true }, options)
super(options)
}
/**
* pending tests
*/
onTestSkip () {
this.write(chalk.cyanBright('.'))
}
/**
* passing tests
*/
onTestPass () {
this.write(chalk.greenBright('.'))
}
/**
* failing tests
*/
onTestFail () {
this.write(chalk.redBright('F'))
}
}
| import chalk from 'chalk'
import WDIOReporter from 'wdio-reporter'
/**
* Initialize a new `Dot` matrix test reporter.
*/
export default class DotReporter extends WDIOReporter {
constructor (options) {
/**
* make dot reporter to write to output stream by default
*/
options = Object.assign(options, { stdout: true })
super(options)
}
/**
* pending tests
*/
onTestSkip () {
this.write(chalk.cyanBright('.'))
}
/**
* passing tests
*/
onTestPass () {
this.write(chalk.greenBright('.'))
}
/**
* failing tests
*/
onTestFail () {
this.write(chalk.redBright('F'))
}
}
|
Improve message posted to slack | #!/usr/bin/env python
import pika
import json
import requests
import os
RABBIT_MQ_SERVER = os.environ["RABBIT_MQ_SERVER"]
RABBIT_MQ_USER = os.environ["RABBIT_MQ_USER"]
RABBIT_MQ_PWD = os.environ["RABBIT_MQ_PWD"]
credentials = pika.PlainCredentials(RABBIT_MQ_USER, RABBIT_MQ_PWD)
connection = pika.BlockingConnection(pika.ConnectionParameters(
RABBIT_MQ_SERVER, credentials = credentials))
channel = connection.channel()
def callback(ch, method, properties, body):
payload = {}
req = json.loads(body)
check_type = req["monitor"]["result"]["check"]["type"]
host = json.loads(req["monitor"]["result"]["check"]["arguments"])["host"]
time = req["monitor"]["result"]["timestamp"]
payload["text"] = check_type + " check failed for " + host + " at " + time
webhook_url = json.loads(req["monitor"]["notifier"]["arguments"])["webhook_url"]
r = requests.post(webhook_url, data = json.dumps(payload))
channel.basic_consume(callback, queue='slack', no_ack=True)
channel.start_consuming()
| #!/usr/bin/env python
import pika
import json
import requests
import os
RABBIT_MQ_SERVER = os.environ["RABBIT_MQ_SERVER"]
RABBIT_MQ_USER = os.environ["RABBIT_MQ_USER"]
RABBIT_MQ_PWD = os.environ["RABBIT_MQ_PWD"]
credentials = pika.PlainCredentials(RABBIT_MQ_USER, RABBIT_MQ_PWD)
connection = pika.BlockingConnection(pika.ConnectionParameters(
RABBIT_MQ_SERVER, credentials = credentials))
channel = connection.channel()
def callback(ch, method, properties, body):
payload = {}
payload["text"] = body
req = json.loads(body)
webhook_url = json.loads(req["monitor"]["notifier"]["arguments"])["webhook_url"]
r = requests.post(webhook_url, data = json.dumps(payload))
channel.basic_consume(callback, queue='slack', no_ack=True)
channel.start_consuming()
|
Simplify nib compiler and support recent Xcode versions by using xcrun | """
Automatic compilation of XIB files
"""
from __future__ import print_function
import subprocess, os
from py2app.decorators import converts
gTool = None
def _get_ibtool():
global gTool
if gTool is None:
if os.path.exists('/usr/bin/xcrun'):
gTool = subprocess.check_output(['/usr/bin/xcrun', '-find', 'ibtool'])[:-1]
else:
gTool = 'ibtool'
print (gTool)
return gTool
@converts(suffix=".xib")
def convert_xib(source, destination, dry_run=0):
destination = destination[:-4] + ".nib"
print("compile %s -> %s"%(source, destination))
if dry_run:
return
subprocess.check_call([_get_ibtool(), '--compile', destination, source])
@converts(suffix=".nib")
def convert_nib(source, destination, dry_run=0):
destination = destination[:-4] + ".nib"
print("compile %s -> %s"%(source, destination))
if dry_run:
return
subprocess.check_call([_get_ibtool, '--compile', destination, source])
| """
Automatic compilation of XIB files
"""
import subprocess, os
from py2app.decorators import converts
@converts(suffix=".xib")
def convert_xib(source, destination, dry_run=0):
destination = destination[:-4] + ".nib"
if dry_run:
return
p = subprocess.Popen(['ibtool', '--compile', destination, source])
xit = p.wait()
if xit != 0:
raise RuntimeError("ibtool failed, code %d"%(xit,))
@converts(suffix=".nib")
def convert_nib(source, destination, dry_run=0):
destination = destination[:-4] + ".nib"
if dry_run:
return
p = subprocess.Popen(['ibtool', '--compile', destination, source])
xit = p.wait()
if xit != 0:
raise RuntimeError("ibtool failed, code %d"%(xit,))
|
Move dask.array.creation.* into dask.array.* namespace | from __future__ import absolute_import, division, print_function
from ..utils import ignoring
from .core import (Array, stack, concatenate, tensordot, transpose, from_array,
choose, where, coarsen, broadcast_to, constant, fromfunction, compute,
unique, store)
from .core import (arccos, arcsin, arctan, arctanh, arccosh, arcsinh, arctan2,
ceil, copysign, cos, cosh, degrees, exp, expm1, fabs, floor, fmod,
frexp, hypot, isinf, isnan, ldexp, log, log10, log1p, modf, radians,
sin, sinh, sqrt, tan, tanh, trunc, around, isnull, notnull, isclose)
from .reductions import (sum, prod, mean, std, var, any, all, min, max, vnorm,
argmin, argmax,
nansum, nanmean, nanstd, nanvar, nanmin,
nanmax, nanargmin, nanargmax)
from .percentile import percentile
with ignoring(ImportError):
from .reductions import nanprod
from . import random, linalg, ghost
from .wrap import ones, zeros, empty
from .reblock import reblock
from ..context import set_options
from .optimization import optimize
from .creation import arange, linspace
| from __future__ import absolute_import, division, print_function
from ..utils import ignoring
from .core import (Array, stack, concatenate, tensordot, transpose, from_array,
choose, where, coarsen, broadcast_to, constant, fromfunction, compute,
unique, store)
from .core import (arccos, arcsin, arctan, arctanh, arccosh, arcsinh, arctan2,
ceil, copysign, cos, cosh, degrees, exp, expm1, fabs, floor, fmod,
frexp, hypot, isinf, isnan, ldexp, log, log10, log1p, modf, radians,
sin, sinh, sqrt, tan, tanh, trunc, around, isnull, notnull, isclose)
from .reductions import (sum, prod, mean, std, var, any, all, min, max, vnorm,
argmin, argmax,
nansum, nanmean, nanstd, nanvar, nanmin,
nanmax, nanargmin, nanargmax)
from .percentile import percentile
with ignoring(ImportError):
from .reductions import nanprod
from . import random, linalg, ghost, creation
from .wrap import ones, zeros, empty
from .reblock import reblock
from ..context import set_options
from .optimization import optimize
|
Move dispatching WebComponentsReady until after HTMLImports.whenReady is patched. | /**
* @license
* Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
(function(scope) {
'use strict';
if (customElements && customElements.polyfillWrapFlushCallback) {
// Here we ensure that the public `HTMLImports.whenReady`
// always comes *after* custom elements have upgraded.
let flushCallback;
function runAndClearCallback() {
if (flushCallback) {
let cb = flushCallback;
flushCallback = null;
cb();
}
}
let origWhenReady = HTMLImports.whenReady;
customElements.polyfillWrapFlushCallback(function(cb) {
flushCallback = cb;
origWhenReady(runAndClearCallback);
});
HTMLImports.whenReady = function(cb) {
origWhenReady(function() {
runAndClearCallback();
cb();
});
}
}
HTMLImports.whenReady(function() {
requestAnimationFrame(function() {
window.dispatchEvent(new CustomEvent('WebComponentsReady'));
});
});
})(window.WebComponents);
| /**
* @license
* Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
(function(scope) {
'use strict';
HTMLImports.whenReady(function() {
requestAnimationFrame(function() {
window.dispatchEvent(new CustomEvent('WebComponentsReady'));
});
});
if (customElements && customElements.polyfillWrapFlushCallback) {
// Here we ensure that the public `HTMLImports.whenReady`
// always comes *after* custom elements have upgraded.
let flushCallback;
function runAndClearCallback() {
if (flushCallback) {
let cb = flushCallback;
flushCallback = null;
cb();
}
}
let origWhenReady = HTMLImports.whenReady;
customElements.polyfillWrapFlushCallback(function(cb) {
flushCallback = cb;
origWhenReady(runAndClearCallback);
});
HTMLImports.whenReady = function(cb) {
origWhenReady(function() {
runAndClearCallback();
cb();
});
}
}
})(window.WebComponents);
|
Add comments & space lines | """Leetcode 7. Reverse Integer
Easy
URL: https://leetcode.com/problems/reverse-integer/description/
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
Note:
The input is assumed to be a 32-bit signed integer.
Your function should return 0 when the reversed integer overflows.
"""
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
Time complexity: O(1).
Space complexity: O(1).
"""
# Since input x is a 32-bit integer, -2^31 <= x <= 2^31 - 1.
if x < 0:
x_rev = int(str(x)[::-1][-1] + str(x)[::-1][:-1])
else:
x_rev = int(str(x)[::-1])
# If reversed integer is overflow.
if abs(x_rev) > 0x7FFFFFFF:
x_rev = 0
return x_rev
def main():
print Solution().reverse(123)
print Solution().reverse(-123)
print Solution().reverse(-pow(2, 31))
if __name__ == '__main__':
main()
| """Leetcode 7. Reverse Integer
Easy
URL: https://leetcode.com/problems/reverse-integer/description/
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
Note:
The input is assumed to be a 32-bit signed integer.
Your function should return 0 when the reversed integer overflows.
"""
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
Time complexity: O(1).
Space complexity: O(1).
"""
# Since input x is a 32-bit integer, -2^31 <= x <= 2^31 - 1.
if x < 0:
x_rev = int(str(x)[::-1][-1] + str(x)[::-1][:-1])
else:
x_rev = int(str(x)[::-1])
if abs(x_rev) > 0x7FFFFFFF:
x_rev = 0
return x_rev
def main():
print Solution().reverse(123)
print Solution().reverse(-123)
print Solution().reverse(-pow(2, 31))
if __name__ == '__main__':
main()
|
Update test because the css class has changes by updating to Bootstrap5 | <?php
namespace Backend\Modules\ContentBlocks\Tests\Action;
use Backend\Core\Tests\BackendWebTestCase;
use Symfony\Bundle\FrameworkBundle\Client;
class UploadModuleTest extends BackendWebTestCase
{
public function testAuthenticationIsNeeded(Client $client): void
{
self::assertAuthenticationIsNeeded($client, '/private/en/extensions/upload_module');
}
public function testUploadPage(Client $client): void
{
$this->login($client);
self::assertPageLoadedCorrectly(
$client,
'/private/en/extensions/upload_module',
[
'Install',
'<label for="file" class="form-label">',
]
);
}
}
| <?php
namespace Backend\Modules\ContentBlocks\Tests\Action;
use Backend\Core\Tests\BackendWebTestCase;
use Symfony\Bundle\FrameworkBundle\Client;
class UploadModuleTest extends BackendWebTestCase
{
public function testAuthenticationIsNeeded(Client $client): void
{
self::assertAuthenticationIsNeeded($client, '/private/en/extensions/upload_module');
}
public function testUploadPage(Client $client): void
{
$this->login($client);
self::assertPageLoadedCorrectly(
$client,
'/private/en/extensions/upload_module',
[
'Install',
'<label for="file" class="custom-file-label">',
]
);
}
}
|
Update the test game repository to make it clear that it only returns ephemeral games (i.e. without metadata or any non-rulesheet resources).
git-svn-id: 4739e81c2fe647bfb539b919360e2c658e6121ea@464 716a755e-b13f-cedc-210d-596dafc6fb9b | package util.game;
import java.io.File;
import java.util.HashSet;
import java.util.Set;
import util.kif.KifReader;
/**
* Test game repository that provides rulesheet-only access to games with no
* associated metadata or other resources, to be used only for unit tests.
*
* @author Sam
*/
public final class TestGameRepository extends GameRepository {
protected Set<String> getUncachedGameKeys() {
Set<String> theKeys = new HashSet<String>();
for(File game : new File("games/test").listFiles()) {
if(!game.getName().endsWith(".kif")) continue;
theKeys.add(game.getName().replace(".kif", ""));
}
return theKeys;
}
protected Game getUncachedGame(String theKey) {
try {
return Game.createEphemeralGame(KifReader.read(new File("games/test/" + theKey + ".kif").getAbsolutePath()));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
} | package util.game;
import java.io.File;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import util.gdl.grammar.Gdl;
import util.kif.KifReader;
/**
* Test game repository that provides rulesheet-only access to games with no
* associated metadata or other resources, to be used only for unit tests.
*
* @author Sam
*/
public final class TestGameRepository extends GameRepository {
protected Set<String> getUncachedGameKeys() {
Set<String> theKeys = new HashSet<String>();
for(File game : new File("games/test").listFiles()) {
if(!game.getName().endsWith(".kif")) continue;
theKeys.add(game.getName().replace(".kif", ""));
}
return theKeys;
}
protected Game getUncachedGame(String theKey) {
try {
List<Gdl> theRules = KifReader.read(new File("games/test/" + theKey + ".kif").getAbsolutePath());
return new Game(theKey, null, null, null, null, theRules);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
} |
Remove unused LanguageSelector from settings | <?php
return [
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
'urlManager' => [
'baseUrl' => '/',
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
],
],
]
];
| <?php
return [
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
'urlManager' => [
'baseUrl' => '/',
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
],
],
],
'bootstrap' => [
[
'class' => 'common\components\LanguageSelector',
'supportedLanguages' => ['en_US', 'ru_RU'],
],
],
];
|
Fix private method registration to work
This makes <custom-a> display the correct URL for its properties | import * as privateMethods from './private-methods.js';
const callbacks = ['createdCallback', 'attachedCallback', 'detachedCallback', 'attributeChangedCallback'];
export default function registerElement(tagName, Constructor) {
// Register the appropriate private methods under the generated constructor name, since when they are looked up at
// runtime it will be with that name. This is a band-aid until https://w3c.github.io/webcomponents/spec/custom/#es6
// lands. Note that the generated constructor name being === the tagName is not specified anywhere that I can see,
// but is true in Chrome :-/. Note also that we can't wait for the generated constructor to be generated, since
// before control returns to the caller of `document.registerElement`, createdCallbacks are called, and they
// sometimes use private methods.
const privateMethodsForConstructor = privateMethods.getAll(Constructor.name);
if (privateMethodsForConstructor) {
privateMethods.setAll(tagName, privateMethodsForConstructor);
}
// The WebIDL bindings generated this, thinking that they were in an ES6 world where the constructor they created
// would be the same as the one registered with the system. So delete it and replace it with the one generated by
// `document.registerElement`.
delete window[Constructor.name];
const GeneratedConstructor = window[Constructor.name] = document.registerElement(tagName, Constructor);
// Delete any custom element callbacks since native elements don't have them and we don't want that kind of
// observable difference. Their presence only matters at registration time anyway.
for (const callback of callbacks) {
delete GeneratedConstructor.prototype[callback];
}
}
| import * as privateMethods from './private-methods.js';
const callbacks = ['createdCallback', 'attachedCallback', 'detachedCallback', 'attributeChangedCallback'];
export default function registerElement(tagName, Constructor) {
// The WebIDL bindings generated this, thinking that they were in an ES6 world where the constructor they created
// would be the same as the one registered with the system. So delete it and replace it with the one generated by
// `document.registerElement`.
delete window[Constructor.name];
const GeneratedConstructor = window[Constructor.name] = document.registerElement(tagName, Constructor);
// Delete any custom element callbacks since native elements don't have them and we don't want that kind of
// observable difference. Their presence only matters at registration time anyway.
for (const callback of callbacks) {
delete GeneratedConstructor.prototype[callback];
}
// Register the appropriate private methods under the generated constructor name, since when they are looked up at
// runtime it will be with that name. This is a band-aid until https://w3c.github.io/webcomponents/spec/custom/#es6
// lands.
const privateMethodsForConstructor = privateMethods.getAll(Constructor.name);
if (privateMethodsForConstructor) {
const registerElementGeneratedName = GeneratedConstructor.name;
privateMethods.setAll(registerElementGeneratedName, privateMethodsForConstructor);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.