text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Fix voting notification returning undefined
getIssueText returns issue text not object. | import { call, takeLatest, select } from 'redux-saga/effects';
import { TOGGLE_NOTIFICATION } from 'common/actionTypes/userSettings';
import { ENABLE_VOTING } from 'common/actionTypes/voting';
import { notify, notifyPermission } from '../../utils/notification';
import { getIssueText } from '../issue/selectors';
import { notificationIsEnabled } from '../userSettings/selectors';
function* openIssue() {
const notificationEnabled = yield select(notificationIsEnabled);
const description = yield select(getIssueText);
if (notificationEnabled) {
yield call(notify, description);
}
}
function* toggleNotification() {
const notificationEnabled = yield select(notificationIsEnabled);
if (notificationEnabled) {
yield call(notifyPermission);
}
}
export default function* issueSaga() {
yield takeLatest(ENABLE_VOTING, openIssue);
yield takeLatest(TOGGLE_NOTIFICATION, toggleNotification);
}
| import { call, takeLatest, select } from 'redux-saga/effects';
import { TOGGLE_NOTIFICATION } from 'common/actionTypes/userSettings';
import { ENABLE_VOTING } from 'common/actionTypes/voting';
import { notify, notifyPermission } from '../../utils/notification';
import { getIssueText } from '../issue/selectors';
import { notificationIsEnabled } from '../userSettings/selectors';
function* openIssue() {
const notificationEnabled = yield select(notificationIsEnabled);
const { description } = yield select(getIssueText);
if (notificationEnabled) {
yield call(notify, description);
}
}
function* toggleNotification() {
const notificationEnabled = yield select(notificationIsEnabled);
if (notificationEnabled) {
yield call(notifyPermission);
}
}
export default function* issueSaga() {
yield takeLatest(ENABLE_VOTING, openIssue);
yield takeLatest(TOGGLE_NOTIFICATION, toggleNotification);
}
|
Add newlines after calendar name and date modified echos | <?php
/**
* This file controls a day view output for iCalendar information.
*/
UNL_UCBCN::outputTemplate('UNL_UCBCN_EventListing','EventListing_icalendar');
?>
BEGIN:VCALENDAR
VERSION:2.0
PRODID:UNL_UCBCN//UNL Event Publisher
X-WR-CALNAME:<?php echo $this->calendar->name."\n"; ?>
CALSCALE:GREGORIAN
X-WR-TIMEZONE:US/Central
METHOD:PUBLISH
VERSION:2.0
TZID:US/Central
LAST-MODIFIED:<?php echo date('Ymd\THis\Z')."\n"; ?>
BEGIN:STANDARD
DTSTART:20051030T070000
TZOFFSETTO:-0600
TZOFFSETFROM:+0000
TZNAME:CST
END:STANDARD
BEGIN:DAYLIGHT
DTSTART:20060402T010000
TZOFFSETTO:-0500
TZOFFSETFROM:-0600
TZNAME:CDT
END:DAYLIGHT
BEGIN:STANDARD
DTSTART:20061029T020000
TZOFFSETTO:-0600
TZOFFSETFROM:-0500
TZNAME:CST
END:STANDARD
END:VTIMEZONE
<?php
UNL_UCBCN::displayRegion($this->output);
?>
END:VCALENDAR
| <?php
/**
* This file controls a day view output for iCalendar information.
*/
UNL_UCBCN::outputTemplate('UNL_UCBCN_EventListing','EventListing_icalendar');
?>
BEGIN:VCALENDAR
VERSION:2.0
PRODID:UNL_UCBCN//UNL Event Publisher
X-WR-CALNAME:<?php echo $this->calendar->name; ?>
CALSCALE:GREGORIAN
X-WR-TIMEZONE:US/Central
METHOD:PUBLISH
VERSION:2.0
TZID:US/Central
LAST-MODIFIED:<?php echo date('Ymd\THis\Z'); ?>
BEGIN:STANDARD
DTSTART:20051030T070000
TZOFFSETTO:-0600
TZOFFSETFROM:+0000
TZNAME:CST
END:STANDARD
BEGIN:DAYLIGHT
DTSTART:20060402T010000
TZOFFSETTO:-0500
TZOFFSETFROM:-0600
TZNAME:CDT
END:DAYLIGHT
BEGIN:STANDARD
DTSTART:20061029T020000
TZOFFSETTO:-0600
TZOFFSETFROM:-0500
TZNAME:CST
END:STANDARD
END:VTIMEZONE
<?php
UNL_UCBCN::displayRegion($this->output);
?>
END:VCALENDAR
|
Change to use className instead of classList for brevity. | import ko from 'knockout'
import ptable from './ptable'
console.log('Main js file loaded!')
console.log('Knockout loaded: ', ko.version)
function AppViewModel() {
const self = this;
let cont = document.getElementById('container')
this.greeting = ko.observable('Click an element')
this.atoms = ko.observableArray(ptable)
this.atomList = ko.observableArray()
this.atomClicked = function (atom) {
self.atomList.push(atom)
}
this.nextQuestion = () => {
let resetTransition = function() {
cont.className = 'tLeft'; // remove tRight & transitioned
cont.offsetHeight // flush changes
cont.className = 'transitioned';
cont.removeEventListener('transitionend', resetTransition)
}
container.classList.add('tRight')
container.addEventListener('transitionend', resetTransition)
}
document.getElementById('container').classList.remove('tLeft');
}
ko.applyBindings(new AppViewModel())
| import ko from 'knockout'
import ptable from './ptable'
console.log('Main js file loaded!')
console.log('Knockout loaded: ', ko.version)
function AppViewModel() {
const self = this;
let cont = document.getElementById('container')
this.greeting = ko.observable('Click an element')
this.atoms = ko.observableArray(ptable)
this.atomList = ko.observableArray()
this.atomClicked = function (atom) {
self.atomList.push(atom)
}
this.nextQuestion = () => {
let resetTransition = function() {
let cl = cont.classList;
cl.remove('transitioned')
cl.add('tLeft')
cl.remove('tRight')
cont.offsetHeight // flush changes
cl.add('transitioned')
cl.remove('tLeft')
cont.removeEventListener('transitionend', resetTransition)
}
container.classList.add('tRight')
container.addEventListener('transitionend', resetTransition)
}
document.getElementById('container').classList.remove('tLeft');
}
ko.applyBindings(new AppViewModel())
|
Add temporary scrip enabled for lookup services | package eu.bcvsolutions.idm.core.api.rest.lookup;
import org.springframework.core.GenericTypeResolver;
import eu.bcvsolutions.idm.core.api.entity.BaseEntity;
import eu.bcvsolutions.idm.core.api.script.ScriptEnabled;
/**
* Lookup support
*
* @author Radek Tomiška
*
* @param <E>
*/
public abstract class AbstractEntityLookup<E extends BaseEntity> implements EntityLookup<E>, ScriptEnabled {
private final Class<?> domainType;
/**
* Creates a new {@link AbstractEntityLookup} instance discovering the supported type from the generics signature.
*/
public AbstractEntityLookup() {
this.domainType = GenericTypeResolver.resolveTypeArgument(getClass(), EntityLookup.class);
}
/*
* (non-Javadoc)
* @see org.springframework.plugin.core.Plugin#supports(java.lang.Object)
*/
@Override
public boolean supports(Class<?> delimiter) {
return domainType.isAssignableFrom(delimiter);
}
} | package eu.bcvsolutions.idm.core.api.rest.lookup;
import org.springframework.core.GenericTypeResolver;
import eu.bcvsolutions.idm.core.api.entity.BaseEntity;
/**
* Lookup support
*
* @author Radek Tomiška
*
* @param <E>
*/
public abstract class AbstractEntityLookup<E extends BaseEntity> implements EntityLookup<E> {
private final Class<?> domainType;
/**
* Creates a new {@link AbstractEntityLookup} instance discovering the supported type from the generics signature.
*/
public AbstractEntityLookup() {
this.domainType = GenericTypeResolver.resolveTypeArgument(getClass(), EntityLookup.class);
}
/*
* (non-Javadoc)
* @see org.springframework.plugin.core.Plugin#supports(java.lang.Object)
*/
@Override
public boolean supports(Class<?> delimiter) {
return domainType.isAssignableFrom(delimiter);
}
} |
Fix for links not working if there was only one type of link for a blog entry | import moment from 'moment';
import formatDescription from './format-description';
import { extractATOMPostImage } from './extract-post-image';
function getBestLink(postLinks) {
let preferredLink = '';
if (postLinks.length === 1) {
preferredLink = postLinks[0].$.href;
} else {
// Prefer alternative URIs to self URIs
const alternateLinks = postLinks.filter(link => link.$.rel === 'alternate').map(link => link.$.href);
const selfLinks = postLinks.filter(link => link.$.rel === 'self').map(link => link.$.href);
preferredLink = alternateLinks.length > 0 ? alternateLinks[0] : selfLinks[0];
}
return preferredLink;
}
export function getDescription(post) {
if (post.content) {
return post.content[0]._;
} else if (post.summary) {
return post.summary[0]._;
}
}
export default function parseATOMPosts(parsedXML) {
return parsedXML.feed.entry.map(entry => {
const blogPost = {
title: entry.title[0]._,
link: getBestLink(entry.link),
description: formatDescription(getDescription(entry))
};
const image = extractATOMPostImage(entry);
if (image) { blogPost.imageURI = image; }
if (entry.updated) { blogPost.dateUpdated = moment(new Date(entry.updated[0])); }
if (entry.published) { blogPost.datePublished = moment(new Date(entry.published[0])); }
return blogPost;
});
}
| import moment from 'moment';
import formatDescription from './format-description';
import { extractATOMPostImage } from './extract-post-image';
function getBestLink(postLinks) {
let preferredLink = '';
if (postLinks.length === 1) {
preferredLink = postLinks[0].href;
} else {
// Prefer alternative URIs to self URIs
const alternateLinks = postLinks.filter(link => link.$.rel === 'alternate').map(link => link.$.href);
const selfLinks = postLinks.filter(link => link.$.rel === 'self').map(link => link.$.href);
preferredLink = alternateLinks.length > 0 ? alternateLinks[0] : selfLinks[0];
}
return preferredLink;
}
export function getDescription(post) {
if (post.content) {
return post.content[0]._;
} else if (post.summary) {
return post.summary[0]._;
}
}
export default function parseATOMPosts(parsedXML) {
return parsedXML.feed.entry.map(entry => {
const blogPost = {
title: entry.title[0]._,
link: getBestLink(entry.link),
description: formatDescription(getDescription(entry))
};
const image = extractATOMPostImage(entry);
if (image) { blogPost.imageURI = image; }
if (entry.updated) { blogPost.dateUpdated = moment(new Date(entry.updated[0])); }
if (entry.published) { blogPost.datePublished = moment(new Date(entry.published[0])); }
return blogPost;
});
}
|
Add note about modified regex | <?php
namespace GuzzleHttp\Psr7;
final class Rfc7230
{
/**
* Header related regular expressions (copied from amphp/http package)
* (Note: once we require PHP 7.x we could just depend on the upstream package)
*
* Note: header delimiter (\r\n) is modified to \r?\n to accept line feed only delimiters for BC reasons.
*
* @link https://github.com/amphp/http/blob/v1.0.1/src/Rfc7230.php#L12-L15
* @license https://github.com/amphp/http/blob/v1.0.1/LICENSE
*/
const HEADER_REGEX = "(^([^()<>@,;:\\\"/[\]?={}\x01-\x20\x7F]++):[ \t]*+((?:[ \t]*+[\x21-\x7E\x80-\xFF]++)*+)[ \t]*+\r?\n)m";
const HEADER_FOLD_REGEX = "(\r?\n[ \t]++)";
}
| <?php
namespace GuzzleHttp\Psr7;
final class Rfc7230
{
/**
* Header related regular expressions (copied from amphp/http package)
* (Note: once we require PHP 7.x we could just depend on the upstream package)
*
* @link https://github.com/amphp/http/blob/v1.0.1/src/Rfc7230.php#L12-L15
* @license https://github.com/amphp/http/blob/v1.0.1/LICENSE
*/
const HEADER_REGEX = "(^([^()<>@,;:\\\"/[\]?={}\x01-\x20\x7F]++):[ \t]*+((?:[ \t]*+[\x21-\x7E\x80-\xFF]++)*+)[ \t]*+\r?\n)m";
const HEADER_FOLD_REGEX = "(\r?\n[ \t]++)";
}
|
Update constructor for card require DateTime | <?php
namespace Locastic\TcomPayWay\Model;
use Locastic\TcomPayWay\Helpers\CardHelper;
class Card
{
/**
* @var string
*/
private $_id;
/**
* @var string
*/
private $_number;
/**
* @var \DateTime
*/
private $_expDate;
/**
* @var string
*/
private $_cvd;
function __construct($number, \DateTime $expDate, $cvd)
{
$this->_id = null;
$this->_number = $number;
$this->_expDate = $expDate;
$this->_cvd = $cvd;
}
public function getId()
{
return CardHelper::getCardId($this->_number);
}
public function getNumber()
{
return $this->_number;
}
public function getExpDate()
{
return $this->_expDate->format('ym');
}
public function getCvd()
{
return $this->_cvd;
}
}
| <?php
namespace Locastic\TcomPayWay\Model;
use Locastic\TcomPayWay\Helpers\CardHelper;
class Card
{
/**
* @var string
*/
private $_id;
/**
* @var string
*/
private $_number;
/**
* @var \DateTime
*/
private $_expDate;
/**
* @var string
*/
private $_cvd;
function __construct($number, $expDate, $cvd)
{
$this->_id = null;
$this->_number = $number;
$this->_expDate = new \DateTime($expDate);
$this->_cvd = $cvd;
}
public function getId()
{
return CardHelper::getCardId($this->_number);
}
public function getNumber()
{
return $this->_number;
}
public function getExpDate()
{
return $this->_expDate->format('ym');
}
public function getCvd()
{
return $this->_cvd;
}
} |
Add project description for PyPI | import versioneer
from setuptools import setup, find_packages
# Add README as description
from os import path
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='domain-event-broker',
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
description='Send and receive domain events via RabbitMQ',
long_description=long_description,
long_description_content_type='text/markdown',
author='Ableton AG',
author_email='webteam@ableton.com',
url='https://github.com/AbletonAG/domain-event-broker',
license='MIT',
packages=find_packages(),
install_requires=["pika >= 1.0.0"],
tests_require=["pytest >= 3.6.0"],
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
],
)
| import versioneer
from setuptools import setup, find_packages
setup(
name='domain-event-broker',
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
description='Send and receive domain events via RabbitMQ',
author='Ableton AG',
author_email='webteam@ableton.com',
url='https://github.com/AbletonAG/domain-event-broker',
license='MIT',
packages=find_packages(),
install_requires=["pika >= 1.0.0"],
tests_require=["pytest >= 3.6.0"],
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
],
)
|
Remove uneeded comment and sort modules. | /*global define*/
define([
'dijit/_CssStateMixin',
'dijit/_TemplatedMixin',
'dijit/_WidgetBase',
'dojo/_base/declare',
'dojo/dom-class',
'dojo/text!./templates/LinkButton.html'
], function(
_CssStateMixin,
_TemplatedMixin,
_WidgetBase,
declare,
domClass,
template) {
"use strict";
return declare('Sandcastle.LinkButton', [_WidgetBase, _TemplatedMixin, _CssStateMixin], {
baseClass : "dijitButton",
templateString : template,
showLabel : true,
_setShowLabelAttr : function(val) {
if (this.containerNode) {
domClass.toggle(this.containerNode, "dijitDisplayNone", !val);
}
this._set("showLabel", val);
},
_setLabelAttr : function(/*String*/content) {
this._set("label", content);
(this.containerNode || this.focusNode).innerHTML = content;
}
});
}); | /*global define*/
define([
'dojo/_base/declare',
'dojo/dom-class', // domClass.toggle
'dijit/_WidgetBase',
'dijit/_CssStateMixin',
'dijit/_TemplatedMixin',
'dojo/text!./templates/LinkButton.html'
], function (
declare,
domClass,
_WidgetBase,
_CssStateMixin,
_TemplatedMixin,
template) {
"use strict";
return declare('Sandcastle.LinkButton', [_WidgetBase, _TemplatedMixin, _CssStateMixin], {
baseClass : "dijitButton",
templateString : template,
showLabel : true,
_setShowLabelAttr : function(val) {
if (this.containerNode) {
domClass.toggle(this.containerNode, "dijitDisplayNone", !val);
}
this._set("showLabel", val);
},
_setLabelAttr : function(/*String*/content) {
this._set("label", content);
(this.containerNode || this.focusNode).innerHTML = content;
}
});
}); |
Fix broken import in native scheduler | from __future__ import absolute_import
from __future__ import unicode_literals
from paasta_tools.frameworks.native_scheduler import MESOS_TASK_SPACER
from paasta_tools.mesos_tools import status_mesos_tasks_verbose
from paasta_tools.utils import calculate_tail_lines
from paasta_tools.utils import compose_job_id
from paasta_tools.utils import paasta_print
def perform_command(command, service, instance, cluster, verbose, soa_dir):
if verbose > 0:
tail_lines = calculate_tail_lines(verbose_level=verbose)
else:
tail_lines = 0
# We have to add a spacer at the end to make sure we only return
# things for service.main and not service.main_foo
task_id_prefix = "%s%s" % (compose_job_id(service, instance), MESOS_TASK_SPACER)
if command == 'status':
paasta_print(status_mesos_tasks_verbose(
job_id=task_id_prefix,
get_short_task_id=lambda x: x,
tail_lines=tail_lines,
))
| from __future__ import absolute_import
from __future__ import unicode_literals
from paasta_tools import native_mesos_scheduler
from paasta_tools.mesos_tools import status_mesos_tasks_verbose
from paasta_tools.utils import calculate_tail_lines
from paasta_tools.utils import compose_job_id
from paasta_tools.utils import paasta_print
def perform_command(command, service, instance, cluster, verbose, soa_dir):
if verbose > 0:
tail_lines = calculate_tail_lines(verbose_level=verbose)
else:
tail_lines = 0
# We have to add a spacer at the end to make sure we only return
# things for service.main and not service.main_foo
task_id_prefix = "%s%s" % (compose_job_id(service, instance), native_mesos_scheduler.MESOS_TASK_SPACER)
if command == 'status':
paasta_print(status_mesos_tasks_verbose(
job_id=task_id_prefix,
get_short_task_id=lambda x: x,
tail_lines=tail_lines,
))
|
Add 'Official' class to remote posts from berniesanders.com | <?php
get_header();
use SandersForPresident\Wordpress\Services\News\NewsFeedService;
$newsFeedService = new NewsFeedService();
$news = $newsFeedService->getNewsFeed();
?>
<div class="container blog list">
<div class="page-container">
<div class="page-title">
<h2>Find out what's going on near you</h2>
<h1>News</h1>
</div>
<?php foreach ($news as $item) : ?>
<article<?php if ($item->isRemote()) : ?> class="official"<?php endif; ?>>
<h2>
<a href="<?php echo $item->getLink(); ?>">
<?php echo $item->getTitle(); ?>
</a>
</h2>
<h4><?php echo $item->getFormattedDate(); ?></h4>
<div class="rte">
<?php echo $item->getContent(); ?>
</div>
</article>
<?php endforeach; ?>
</div>
</div>
<?php get_footer(); ?>
| <?php
get_header();
use SandersForPresident\Wordpress\Services\News\NewsFeedService;
$newsFeedService = new NewsFeedService();
$news = $newsFeedService->getNewsFeed();
?>
<div class="container blog list">
<div class="page-container">
<div class="page-title">
<h2>Find out what's going on near you</h2>
<h1>News</h1>
</div>
<?php foreach ($news as $item) : ?>
<article>
<h2>
<a href="<?php echo $item->getLink(); ?>">
<?php if ($item->isRemote()) : ?><span style="color: #277cc0;">BERNIE POST:</span><?php endif; ?>
<?php echo $item->getTitle(); ?>
</a>
</h2>
<h4><?php echo $item->getFormattedDate(); ?></h4>
<div class="rte">
<?php echo $item->getContent(); ?>
</div>
</article>
<?php endforeach; ?>
</div>
</div>
<?php get_footer(); ?>
|
Remove test on serialisation (order is not fixed) | from rdflib import Graph, Namespace, URIRef, Literal
from rdflib.compare import to_isomorphic
import unittest
class TestIssue655(unittest.TestCase):
def test_issue655(self):
PROV = Namespace('http://www.w3.org/ns/prov#')
bob = URIRef("http://example.org/object/Bob")
value = Literal(float("inf"))
# g1 is a simple graph with one attribute having an infinite value
g1 = Graph()
g1.add((bob, PROV.value, value))
# Build g2 out of the deserialisation of g1 serialisation
g2 = Graph()
g2.parse(data=g1.serialize(format='turtle'), format='turtle')
self.assertTrue(to_isomorphic(g1) == to_isomorphic(g2))
self.assertTrue(Literal(float("inf")).n3().split("^")[0] == '"INF"')
self.assertTrue(Literal(float("-inf")).n3().split("^")[0] == '"-INF"')
if __name__ == "__main__":
unittest.main()
| from rdflib import Graph, Namespace, URIRef, Literal
from rdflib.compare import to_isomorphic
import unittest
class TestIssue655(unittest.TestCase):
def test_issue655(self):
PROV = Namespace('http://www.w3.org/ns/prov#')
bob = URIRef("http://example.org/object/Bob")
value = Literal(float("inf"))
# g1 is a simple graph with one attribute having an infinite value
g1 = Graph()
g1.add((bob, PROV.value, value))
# Build g2 out of the deserialisation of g1 serialisation
g2 = Graph()
g2.parse(data=g1.serialize(format='turtle'), format='turtle')
self.assertTrue(g1.serialize(
format='turtle') == g2.serialize(format='turtle'))
self.assertTrue(to_isomorphic(g1) == to_isomorphic(g2))
self.assertTrue(Literal(float("inf")).n3().split("^")[0] == '"INF"')
self.assertTrue(Literal(float("-inf")).n3().split("^")[0] == '"-INF"')
if __name__ == "__main__":
unittest.main()
|
Change .filter -> .find. So it can be used on parent element | // $('#content-with-images').imagesLoaded( myFunction )
// execute a callback when all images inside a parent have loaded.
// needed because .load() doesn't work on cached images
// Useful for Masonry or Isotope, triggering dynamic layout
// after images have loaded:
// $('#content').imagesLoaded( function(){
// $('#content').masonry();
// });
// mit license. paul irish. 2010.
// webkit fix from Oren Solomianik. thx!
// callback function is passed the last image to load
// as an argument, and the collection as `this`
$.fn.imagesLoaded = function(callback){
var elems = this.find('img'),
len = elems.length,
_this = this;
elems.bind('load',function(){
if (--len <= 0){
callback.call( _this );
}
}).each(function(){
// cached images don't fire load sometimes, so we reset src.
if (this.complete || this.complete === undefined){
var src = this.src;
// webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
// data uri bypasses webkit log warning (thx doug jones)
this.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
this.src = src;
}
});
return this;
};
| // $('img.photo',this).imagesLoaded(myFunction)
// execute a callback when all images have loaded.
// needed because .load() doesn't work on cached images
// mit license. paul irish. 2010.
// webkit fix from Oren Solomianik. thx!
// callback function is passed the last image to load
// as an argument, and the collection as `this`
$.fn.imagesLoaded = function(callback){
var elems = this.filter('img'),
len = elems.length;
elems.bind('load',function(){
if (--len <= 0){ callback.call(elems,this); }
}).each(function(){
// cached images don't fire load sometimes, so we reset src.
if (this.complete || this.complete === undefined){
var src = this.src;
// webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
// data uri bypasses webkit log warning (thx doug jones)
this.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
this.src = src;
}
});
return this;
};
|
Remove unused var and console statements | import ReactDOM from 'react-dom';
const ItemTarget = {
hover(props, monitor, component) {
const dragIndex = monitor.getItem().index;
const hoverIndex = props.index;
// Don't replace items with themselves
if (dragIndex === hoverIndex) {
return;
}
// Determine rectangle on screen
const hoverBoundingRect = ReactDOM.findDOMNode(component).getBoundingClientRect();
// Get vertical middle
const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2;
// Determine mouse position
const clientOffset = monitor.getClientOffset();
// Get pixels to the top
const hoverClientY = clientOffset.y - hoverBoundingRect.top;
// Only perform the move when the mouse has crossed half of the items height
// When dragging downwards, only move when the cursor is below 50%
// When dragging upwards, only move when the cursor is above 50%
// Dragging downwards
if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) {
return;
}
// Dragging upwards
if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) {
return;
}
// Time to actually perform the action
props.moveItem(dragIndex, hoverIndex);
// Note: we're mutating the monitor item here!
// Generally it's better to avoid mutations,
// but it's good here for the sake of performance
// to avoid expensive index searches.
monitor.getItem().index = hoverIndex;
}
};
export default ItemTarget;
| import React from 'react';
import ReactDOM from 'react-dom';
const ItemTarget = {
hover(props, monitor, component) {
const dragIndex = monitor.getItem().index;
const hoverIndex = props.index;
// Don't replace items with themselves
if (dragIndex === hoverIndex) {
console.log(1);
return;
}
// Determine rectangle on screen
const hoverBoundingRect = ReactDOM.findDOMNode(component).getBoundingClientRect();
// Get vertical middle
const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2;
// Determine mouse position
const clientOffset = monitor.getClientOffset();
// Get pixels to the top
const hoverClientY = clientOffset.y - hoverBoundingRect.top;
// Only perform the move when the mouse has crossed half of the items height
// When dragging downwards, only move when the cursor is below 50%
// When dragging upwards, only move when the cursor is above 50%
// Dragging downwards
if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) {
console.log(2);
return;
}
// Dragging upwards
if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) {
console.log(3);
return;
}
// Time to actually perform the action
props.moveItem(dragIndex, hoverIndex);
// Note: we're mutating the monitor item here!
// Generally it's better to avoid mutations,
// but it's good here for the sake of performance
// to avoid expensive index searches.
monitor.getItem().index = hoverIndex;
}
};
export default ItemTarget;
|
Add link to dashboard in app title | import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import AppBar from 'material-ui/AppBar';
import CircularProgress from 'material-ui/CircularProgress';
import Notification from './Notification';
import injectTapEventPlugin from 'react-tap-event-plugin';
import Menu from './Menu';
injectTapEventPlugin();
const Layout = ({ isLoading, children, route }) => (
<MuiThemeProvider>
<div style={{ display: 'flex', flexDirection: 'column', minHeight: '100vh' }}>
<AppBar title={<Link to="/" style={{ color: '#fff' }}>Admin on REST</Link>} iconElementRight={isLoading ? <CircularProgress color="#fff" size={0.5} /> : <span/>} />
<div className="body" style={{ display: 'flex', flex: '1', backgroundColor: '#edecec' }}>
<div style={{ flex: 1 }}>{children}</div>
<Menu resources={route.resources} />
</div>
<Notification />
</div>
</MuiThemeProvider>
);
Layout.propTypes = {
isLoading: PropTypes.bool.isRequired,
children: PropTypes.node,
route: PropTypes.object.isRequired,
};
function mapStateToProps(state) {
return { isLoading: state.admin.loading > 0 };
}
export default connect(
mapStateToProps,
)(Layout);
| import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import AppBar from 'material-ui/AppBar';
import CircularProgress from 'material-ui/CircularProgress';
import Notification from './Notification';
import injectTapEventPlugin from 'react-tap-event-plugin';
import Menu from './Menu';
injectTapEventPlugin();
const Layout = ({ isLoading, children, route }) => (
<MuiThemeProvider>
<div style={{ display: 'flex', flexDirection: 'column', minHeight: '100vh' }}>
<AppBar title="Admin on REST" iconElementRight={isLoading ? <CircularProgress color="#fff" size={0.5} /> : <span/>} />
<div className="body" style={{ display: 'flex', flex: '1', backgroundColor: '#edecec' }}>
<div style={{ flex: 1 }}>{children}</div>
<Menu resources={route.resources} />
</div>
<Notification />
</div>
</MuiThemeProvider>
);
Layout.propTypes = {
isLoading: PropTypes.bool.isRequired,
children: PropTypes.node,
route: PropTypes.object.isRequired,
};
function mapStateToProps(state) {
return { isLoading: state.admin.loading > 0 };
}
export default connect(
mapStateToProps,
)(Layout);
|
Add NO_PY_EXT environment variable to disable compilation of
the C module, which is not working very well in cross-compile
mode. | #!/usr/bin/env python
from distutils.core import setup, Extension
import os
elp_srcs = ['src/periodic.c', 'src/prdic_math.c', \
'src/prdic_fd.c', \
'src/prdic_pfd.c', \
'src/prdic_main_fd.c', 'src/prdic_main_pfd.c', \
'src/prdic_main.c', \
'src/prdic_recfilter.c', 'src/prdic_shmtrig.c', \
'src/prdic_sign.c']
module1 = Extension('_elperiodic', sources = elp_srcs, \
extra_link_args = ['-Wl,--version-script=src/Symbol.map',])
def get_ex_mod():
if 'NO_PY_EXT' in os.environ:
return None
return [module1]
kwargs = {'name':'ElPeriodic',
'version':'1.0',
'description':'Phase-locked userland scheduling library',
'author':'Maksym Sobolyev',
'author_email':'sobomax@gmail.com',
'url':'https://github.com/sobomax/libelperiodic',
'packages':['elperiodic',],
'package_dir':{'elperiodic':'python'},
'ext_modules': get_ex_mod()
}
if __name__ == '__main__':
setup(**kwargs)
| #!/usr/bin/env python
from distutils.core import setup, Extension
elp_srcs = ['src/periodic.c', 'src/prdic_math.c', \
'src/prdic_fd.c', \
'src/prdic_pfd.c', \
'src/prdic_main_fd.c', 'src/prdic_main_pfd.c', \
'src/prdic_main.c', \
'src/prdic_recfilter.c', 'src/prdic_shmtrig.c', \
'src/prdic_sign.c']
module1 = Extension('_elperiodic', sources = elp_srcs, \
extra_link_args = ['-Wl,--version-script=src/Symbol.map',])
kwargs = {'name':'ElPeriodic',
'version':'1.0',
'description':'Phase-locked userland scheduling library',
'author':'Maksym Sobolyev',
'author_email':'sobomax@gmail.com',
'url':'https://github.com/sobomax/libelperiodic',
'packages':['elperiodic',],
'package_dir':{'elperiodic':'python'},
'ext_modules': [module1]
}
if __name__ == '__main__':
setup(**kwargs)
|
Add method save, manager create or update on opps db redis | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from opps.db.conf import settings
from redis import ConnectionPool
from redis import Redis as RedisClient
class Redis:
def __init__(self, key_prefix, key_sufix):
self.key_prefix = key_prefix
self.key_sufix = key_sufix
self.host = settings.OPPS_DB_HOST
self.port = settings.OPPS_DB_PORT
self.db = 0
pool = ConnectionPool(host=self.host,
port=self.port,
db=self.db)
self.conn = RedisClient(connection_pool=pool)
def close(self):
self.conn = None
return True
def key(self):
return '{}_{}_{}'.format(settings.OPPS_DB_NAME,
self.key_prefix,
self.key_sufix)
def save(self, document):
return self.conn.set(self.key(), document)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from opps.db.conf import settings
from redis import ConnectionPool
from redis import Redis as RedisClient
class Redis:
def __init__(self, key_prefix, key_sufix):
self.key_prefix = key_prefix
self.key_sufix = key_sufix
self.host = settings.OPPS_DB_HOST
self.port = settings.OPPS_DB_PORT
self.db = 0
pool = ConnectionPool(host=self.host,
port=self.port,
db=self.db)
self.conn = RedisClient(connection_pool=pool)
def close(self):
self.conn = None
return True
def key(self):
return '{}_{}_{}'.format(settings.OPPS_DB_NAME,
self.key_prefix,
self.key_sufix)
|
Add support for key/title value back in. | <?php namespace Anomaly\RelationshipFieldType\Handler;
use Anomaly\RelationshipFieldType\RelationshipFieldType;
/**
* Class Related
*
* @link http://pyrocms.com/
* @author PyroCMS, Inc. <support@pyrocms.com>
* @author Ryan Thompson <ryan@pyrocms.com>
*/
class Related
{
/**
* Handle the options.
*
* @param RelationshipFieldType $fieldType
* @return array
*/
public function handle(RelationshipFieldType $fieldType)
{
$model = $fieldType->getRelatedModel();
$query = $model->newQuery();
$fieldType->setOptions(
$query->get()->pluck(
$fieldType->config('title_name', $model->getTitleName()),
$fieldType->config('key_name', $model->getKeyName())
)->all()
);
}
}
| <?php namespace Anomaly\RelationshipFieldType\Handler;
use Anomaly\RelationshipFieldType\RelationshipFieldType;
/**
* Class Related
*
* @link http://pyrocms.com/
* @author PyroCMS, Inc. <support@pyrocms.com>
* @author Ryan Thompson <ryan@pyrocms.com>
*/
class Related
{
/**
* Handle the options.
*
* @param RelationshipFieldType $fieldType
* @return array
*/
public function handle(RelationshipFieldType $fieldType)
{
$model = $fieldType->getRelatedModel();
$query = $model->newQuery();
$fieldType->setOptions(
$query->get()->pluck(
$model->getTitleName(),
$model->getKeyName()
)->all()
);
}
}
|
sagas: Update redux-saga and add regenerator | import 'regenerator-runtime/runtime';
import { call, put, takeEvery } from 'redux-saga/effects';
const defaultOptions = {
throwErrors: false,
};
export function sagasBuilder(request, REQUEST, actions, options = {}) {
const {
throwErrors,
} = {
...defaultOptions,
...options,
};
function* makeRequest({ payload, meta }) {
let data;
let error;
try {
yield put(actions.pending(payload, meta));
data = yield call(request, payload, meta);
yield put(actions.success(data, meta));
} catch (err) {
error = err;
yield put(actions.failure(error, meta));
if (throwErrors) {
throw error;
}
}
return {
data,
error,
};
}
function* watchForRequest() {
yield takeEvery(REQUEST, makeRequest);
}
return {
makeRequest,
watchForRequest,
};
}
| import { takeEvery } from 'redux-saga';
import { call, put } from 'redux-saga/effects';
const defaultOptions = {
throwErrors: false,
};
export function sagasBuilder(request, REQUEST, actions, options = {}) {
const {
throwErrors,
} = {
...defaultOptions,
...options,
};
function* makeRequest({ payload, meta }) {
let data;
let error;
try {
yield put(actions.pending(payload, meta));
data = yield call(request, payload, meta);
yield put(actions.success(data, meta));
} catch (err) {
error = err;
yield put(actions.failure(error, meta));
if (throwErrors) {
throw error;
}
}
return {
data,
error,
};
}
function* watchForRequest() {
yield takeEvery(REQUEST, makeRequest);
}
return {
makeRequest,
watchForRequest,
};
}
|
Fix link on index view. | @extends('fluxbb::layout.main')
@section('main')
{{-- TODO: Escape all the variables!!! --}}
<ul>
@foreach ($categories as $cat_info)
<?php $category = $cat_info['category']; ?>
<li>
{{ $category->cat_name }}
<ul>
@foreach ($cat_info['forums'] as $forum)
<li>
<a href="{{ URL::route('viewforum', array('fid' => $forum->id)) }}">{{ $forum->forum_name }}</a>
<em class="forumdesc">{{ $forum->forum_desc }}</em>
<ul>
<li>{{ $forum->numTopics() }} topics</li>
<li>{{ $forum->numPosts() }} posts</li>
</ul>
</li>
@endforeach
</ul>
</li>
@endforeach
</ul>
@stop
| @extends('fluxbb::layout.main')
@section('main')
{{-- TODO: Escape all the variables!!! --}}
<ul>
@foreach ($categories as $cat_info)
<?php $category = $cat_info['category']; ?>
<li>
{{ $category->cat_name }}
<ul>
@foreach ($cat_info['forums'] as $forum)
<li>
<a href="{{ URL::action('fluxbb::home@forum', array($forum->id)) }}">{{ $forum->forum_name }}</a>
<em class="forumdesc">{{ $forum->forum_desc }}</em>
<ul>
<li>{{ $forum->numTopics() }} topics</li>
<li>{{ $forum->numPosts() }} posts</li>
</ul>
</li>
@endforeach
</ul>
</li>
@endforeach
</ul>
@stop
|
Add `--all` to graph command to show other branches (esp. origin) | from sublime_plugin import WindowCommand, TextCommand
from ..git_command import GitCommand
LOG_GRAPH_TITLE = "GRAPH"
class GsLogGraphCommand(WindowCommand, GitCommand):
"""
Open a new window displaying an ASCII-graphic representation
of the repo's branch relationships.
"""
def run(self):
repo_path = self.repo_path
view = self.window.new_file()
view.settings().set("git_savvy.log_graph_view", True)
view.settings().set("git_savvy.repo_path", repo_path)
view.set_name(LOG_GRAPH_TITLE)
view.set_scratch(True)
view.set_read_only(True)
view.run_command("gs_log_graph_initialize")
class GsLogGraphInitializeCommand(TextCommand, GitCommand):
def run(self, edit):
branch_graph = self.git("log", "--oneline", "--graph", "--all", "--decorate")
self.view.run_command("gs_replace_view_text", {"text": branch_graph})
| from sublime_plugin import WindowCommand, TextCommand
from ..git_command import GitCommand
LOG_GRAPH_TITLE = "GRAPH"
class GsLogGraphCommand(WindowCommand, GitCommand):
"""
Open a new window displaying an ASCII-graphic representation
of the repo's branch relationships.
"""
def run(self):
repo_path = self.repo_path
view = self.window.new_file()
view.settings().set("git_savvy.log_graph_view", True)
view.settings().set("git_savvy.repo_path", repo_path)
view.set_name(LOG_GRAPH_TITLE)
view.set_scratch(True)
view.set_read_only(True)
view.run_command("gs_log_graph_initialize")
class GsLogGraphInitializeCommand(TextCommand, GitCommand):
def run(self, edit):
branch_graph = self.git("log", "--oneline", "--graph", "--decorate")
self.view.run_command("gs_replace_view_text", {"text": branch_graph})
|
Fix issue with js caching | /*
* Copyright (C) Sam Parkinson 2014
*
* This file is part of ASLO.
*
* ASLO 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.
*
* ASLO 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 ASLO. If not, see <http://www.gnu.org/licenses/>.
*/
exports.get = function (url, callback) {
var key = 'HTTP_CACHE' + url;
if (localStorage[key] !== undefined) {
try {
callback(JSON.parse(localStorage[key]));
} catch (e) {};
};
$.get(url).done(function (response) {
localStorage[key] = JSON.stringify(response);
callback(response);
});
};
| /*
* Copyright (C) Sam Parkinson 2014
*
* This file is part of ASLO.
*
* ASLO 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.
*
* ASLO 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 ASLO. If not, see <http://www.gnu.org/licenses/>.
*/
exports.get = function (url, callback) {
var key = 'HTTP_CACHE' + url;
if (localStorage[key] !== undefined) {
callback(JSON.parse(localStorage[key]));
};
$.get(url).done(function (response) {
localStorage[key] = JSON.stringify(response);
callback(response);
});
};
|
Change the wording and link directly to packagist.org. | <?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* 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 Composer\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class HelpCommand extends Command
{
protected function configure()
{
$this
->setName('help')
->setDescription('')
->setHelp(<<<EOT
<info>php composer.phar help</info>
EOT
)
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln(<<<EOT
<info>Composer - Package Management for PHP</info>
<comment>Composer is a package manager tracking local dependencies of your projects and libraries.
See http://packagist.org/about for more information.</comment>
EOT
);
}
}
| <?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* 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 Composer\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class HelpCommand extends Command
{
protected function configure()
{
$this
->setName('help')
->setDescription('')
->setHelp(<<<EOT
<info>php composer.phar help</info>
EOT
)
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln(<<<EOT
<info>Composer - Package Management for PHP</info>
<comment>Composer is a package manager tracking local dependencies of your projects and libraries.
See the "about page" on packagist.org for more information.</comment>
EOT
);
}
}
|
Add fixed command name to usage format in -h | #!/usr/bin/env node
const chalk = require('chalk');
const yargs = require('yargs');
// ./modules
const rocketLaunch = require('./lib/modules/rocketLaunch');
var argv = yargs
.usage('Usage: space <command> [options]')
.demandCommand(1)
.command('about', 'Info about the CLI', about)
.command('next', 'Get next rocket launch',
function (yargs) {
return yargs.option('d', {
alias: 'details',
describe: 'Details about the next launch'
}).option('tz', {
alias: 'timezone',
describe: 'Define time zone for time info e.g. America/New_York, Europe/Paris, Asia/Shanghai'
});
},
rocketLaunch.nextLaunch
)
.help('h')
.alias('h', 'help')
.argv;
function about() {
console.log(chalk.green('Welcome to Space CLI'), '- a CLI for space information' + '\n\n' + 'Credits:' + '\n' + 'https://launchlibrary.net/ - API documentation for upcoming launches');
}
| #!/usr/bin/env node
const chalk = require('chalk');
const yargs = require('yargs');
// ./modules
const rocketLaunch = require('./lib/modules/rocketLaunch');
var argv = yargs
.usage('Usage: $0 <command> [options]')
.demandCommand(1)
.command('about', 'Info about the CLI', about)
.command('next', 'Get next rocket launch',
function (yargs) {
return yargs.option('d', {
alias: 'details',
describe: 'Details about the next launch'
}).option('tz', {
alias: 'timezone',
describe: 'Define time zone for time info e.g. America/New_York, Europe/Paris, Asia/Shanghai'
});
},
rocketLaunch.nextLaunch
)
.help('h')
.alias('h', 'help')
.argv;
function about() {
console.log(chalk.green('Welcome to Space CLI'), '- a CLI for space information' + '\n\n' + 'Credits:' + '\n' + 'https://launchlibrary.net/ - API documentation for upcoming launches');
}
|
Update the client name used in prober, so we could separate prober statsd data for multiple clients. | var globalRequest = require('request');
var Prober = require('airlock');
var xtend = require('xtend');
var errors = require('../errors.js');
module.exports = ProbingRequestHandler;
function ProbingRequestHandler(requestHandler, options) {
if (!(this instanceof ProbingRequestHandler)) {
return new ProbingRequestHandler(requestHandler, options);
}
if (typeof options.clientName !== 'string') {
throw errors.MissingClientName({
optionsStr: JSON.stringify(options)
});
}
this.prober = options.prober = Prober({
enabled: true,
title: 'typed-request-client.' + options.clientName,
statsd: options.statsd
});
// TODO consider moving this one line into a separate layer.
options.request = options.request || globalRequest;
this.requestHandler = requestHandler;
this.options = options;
}
ProbingRequestHandler.prototype.request =
function handleProbingRequest(request, opts, cb) {
opts = xtend(opts, {request: this.options.request});
var thunk = this.requestHandler.request.bind(
this.requestHandler,
request,
opts
);
this.prober.probe(thunk, cb);
};
| var globalRequest = require('request');
var Prober = require('airlock');
var xtend = require('xtend');
module.exports = ProbingRequestHandler;
function ProbingRequestHandler(requestHandler, options) {
if (!(this instanceof ProbingRequestHandler)) {
return new ProbingRequestHandler(requestHandler, options);
}
this.prober = options.prober = Prober({
enabled: true,
title: 'typed-request-client',
statsd: options.statsd
});
// TODO consider moving this one line into a separate layer.
options.request = options.request || globalRequest;
this.requestHandler = requestHandler;
this.options = options;
}
ProbingRequestHandler.prototype.request =
function handleProbingRequest(request, opts, cb) {
opts = xtend(opts, {request: this.options.request});
var thunk = this.requestHandler.request.bind(
this.requestHandler,
request,
opts
);
this.prober.probe(thunk, cb);
};
|
Modify splitter logic to include additional psr-4 namespace. | <?php
namespace WP_CLI;
/**
* Class AutoloadSplitter.
*
* This class is used to provide the splitting logic to the
* `wp-cli/autoload-splitter` Composer plugin.
*
* @package WP_CLI
*/
class AutoloadSplitter {
/**
* Check whether the current class should be split out into a separate
* autoloader.
*
* Note: `class` in this context refers to all PHP autoloadable elements:
* - classes
* - interfaces
* - traits
*
* @param string $class Fully qualified name of the current class.
* @param string $code Path to the code file that declares the class.
*
* @return bool Whether to split out the class into a separate autoloader.
*/
public function __invoke( $class, $code ) {
return
1 === preg_match( '/.*\/wp-cli\/\w*-command\/.*/', $code )
|| 1 === preg_match( '/.*\/php\/commands\/src\/.*/', $code );
}
}
| <?php
namespace WP_CLI;
/**
* Class AutoloadSplitter.
*
* This class is used to provide the splitting logic to the
* `wp-cli/autoload-splitter` Composer plugin.
*
* @package WP_CLI
*/
class AutoloadSplitter {
/**
* Check whether the current class should be split out into a separate
* autoloader.
*
* Note: `class` in this context refers to all PHP autoloadable elements:
* - classes
* - interfaces
* - traits
*
* @param string $class Fully qualified name of the current class.
* @param string $code Path to the code file that declares the class.
*
* @return bool Whether to split out the class into a separate autoloader.
*/
public function __invoke( $class, $code ) {
return 1 === preg_match( '/.*\/wp-cli\/\w*-command\/.*/', $code );
}
}
|
Declare required version of zeit.cms | from setuptools import setup, find_packages
setup(
name='zeit.content.infobox',
version='1.23.6dev',
author='gocept',
author_email='mail@gocept.com',
url='https://svn.gocept.com/repos/gocept-int/zeit.cms',
description="ZEIT infobox",
packages=find_packages('src'),
package_dir = {'': 'src'},
include_package_data = True,
zip_safe=False,
license='gocept proprietary',
namespace_packages = ['zeit', 'zeit.content'],
install_requires=[
'gocept.form',
'mock',
'setuptools',
'zeit.cms>=1.53.0.dev',
'zeit.wysiwyg',
'zope.app.appsetup',
'zope.app.testing',
'zope.component',
'zope.formlib',
'zope.interface',
'zope.publisher',
'zope.security',
'zope.testing',
],
)
| from setuptools import setup, find_packages
setup(
name='zeit.content.infobox',
version='1.23.6dev',
author='gocept',
author_email='mail@gocept.com',
url='https://svn.gocept.com/repos/gocept-int/zeit.cms',
description="ZEIT infobox",
packages=find_packages('src'),
package_dir = {'': 'src'},
include_package_data = True,
zip_safe=False,
license='gocept proprietary',
namespace_packages = ['zeit', 'zeit.content'],
install_requires=[
'gocept.form',
'mock',
'setuptools',
'zeit.cms>1.40.3',
'zeit.wysiwyg',
'zope.app.appsetup',
'zope.app.testing',
'zope.component',
'zope.formlib',
'zope.interface',
'zope.publisher',
'zope.security',
'zope.testing',
],
)
|
Fix bug and update the return value ( port ).
Changes to be committed:
modified: src/lib/edge/telegram/commandHandler.js |
module.exports = (function(){
function parseCommandOption( args ){
var options = {}, token;
while( token = args.shift() ){
if( !token.startsWith("--") ){
options.extra = [token].concat(args);
break;
}
let optionType = token.replace(/^--/, "");
let i, len;
for( i = 0, len = args.length; i < len; ++i ){
if( args[i].startsWith("--"))
break;
}
options[optionType] = args.splice(0, i);
}
return options;
}
var handlers = {};
handlers.echo = ( args )=>{
var options = {
msg: args.join(" ")
}
return [ "echo", options ];
};
}
return handlers;
})();
|
module.exports = (function(){
function parseCommandOption( args ){
var options = {}, token;
while( token = args.shift() ){
if( !token.startsWith("--") ){
options.extra = [token].concat(args);
break;
}
let optionType = token.replace(/^--/, "");
let i, len;
for( i = 0, len = args.length; i < len; ++i ){
if( args[i].startsWith("--"))
break;
}
options[optionType] = args.splice(0, i);
}
return options;
}
var handlers = {};
handlers.echo = ( ...args )=>{
return {
msg: args.join(" ")
};
}
return handlers;
})();
|
Add window size and devicePixelRatio to platform sample output
Enyo-DCO-1.1-Signed-Off-By: Ben Combee (ben.combee@palm.com) | enyo.kind({
name: "enyo.sample.PlatformSample",
kind: "FittableRows",
classes: "enyo-fit platform-sample",
components: [
{classes: "platform-sample-divider", content: "Enyo Platform Detection"},
{kind: "onyx.Groupbox", components: [
{kind: "onyx.GroupboxHeader", content: "User-Agent String"},
{name: "uaString", content: "", style: "padding: 8px;"}
]},
{tag: "br"},
{kind: "onyx.Groupbox", components: [
{kind: "onyx.GroupboxHeader", content: "Window"},
{name: "windowAttr", content: "", style: "padding: 8px;"}
]},
{tag: "br"},
{kind: "onyx.Groupbox", components: [
{kind: "onyx.GroupboxHeader", content: "enyo.platform"},
{name: "enyoPlatformJSON", content: "", style: "padding: 8px;"}
]}
],
create: function() {
this.inherited(arguments);
this.$.uaString.setContent(navigator.userAgent);
this.$.windowAttr.setContent("size: " + window.innerWidth + "x" + window.innerHeight +
", devicePixelRatio: " + window.devicePixelRatio);
this.$.enyoPlatformJSON.setContent(JSON.stringify(enyo.platform));
}
}); | enyo.kind({
name: "enyo.sample.PlatformSample",
kind: "FittableRows",
classes: "enyo-fit platform-sample",
components: [
{classes: "platform-sample-divider", content: "Enyo Platform Detection"},
{kind: "onyx.Groupbox", components: [
{kind: "onyx.GroupboxHeader", content: "User-Agent String"},
{name: "uaString", content: "", style: "padding: 8px;"}
]},
{tag: "br"},
{kind: "onyx.Groupbox", components: [
{kind: "onyx.GroupboxHeader", content: "enyo.platform"},
{name: "enyoPlatformJSON", content: "", style: "padding: 8px;"}
]}
],
create: function() {
this.inherited(arguments);
this.$.uaString.setContent(navigator.userAgent);
this.$.enyoPlatformJSON.setContent(JSON.stringify(enyo.platform));
}
}); |
Speed up non-existent class detection by not using exceptions | <?php
class PostgresDbWrapper extends PostgresDb {
/**
* Execute where method with the specified episode and season numbers
*
* @param string|int|\DB\Episode $s Season, or array with keys season & episode
* @param string|int|null $e Episode, optional if $s is an array
*
* @return self
*/
public function whereEp($s, $e = null){
if (!isset($e)){
parent::where('season', $s->season);
parent::where('episode', $s->episode);
}
else {
parent::where('season', $s);
parent::where('episode', $e);
}
return $this;
}
public $query_count = 0;
private $_nonexistantClassCache = array();
/**
* @param PDOStatement $stmt Statement to execute
*
* @return bool|array|object[]
*/
protected function _execStatement($stmt){
$className = $this->tableNameToClassName();
if (isset($className) && empty($this->_nonexistantClassCache[$className])){
if (!class_exists("\\DB\\$className"))
$this->_nonexistantClassCache[$className] = true;
else $this->setClass("\\DB\\$className");
}
$this->query_count++;
return parent::_execStatement($stmt);
}
}
| <?php
class PostgresDbWrapper extends PostgresDb {
/**
* Execute where method with the specified episode and season numbers
*
* @param string|int|\DB\Episode $s Season, or array with keys season & episode
* @param string|int|null $e Episode, optional if $s is an array
*
* @return self
*/
public function whereEp($s, $e = null){
if (!isset($e)){
parent::where('season', $s->season);
parent::where('episode', $s->episode);
}
else {
parent::where('season', $s);
parent::where('episode', $e);
}
return $this;
}
public $query_count = 0;
private $_nonexistantClassCache = array();
/**
* @param PDOStatement $stmt Statement to execute
*
* @return bool|array|object[]
*/
protected function _execStatement($stmt){
$className = $this->tableNameToClassName();
if (isset($className) && empty($this->_nonexistantClassCache[$className])){
try {
if (!class_exists("\\DB\\$className"))
throw new Exception();
$this->setClass("\\DB\\$className");
}
catch (Exception $e){ $this->_nonexistantClassCache[$className] = true; }
}
$this->query_count++;
return parent::_execStatement($stmt);
}
}
|
Fix not imported os and format code | import os
from flask import Flask, send_file
app = Flask(__name__)
@app.route("/hello")
def hello():
return "Hello World from Flask in a uWSGI Nginx Docker container with \
Python 3.6 (from the example template)"
@app.route("/")
def main():
return send_file('./static/index.html')
# Everything not declared before (not a Flask route / API endpoint)...
@app.route('/<path:path>')
def route_frontend(path):
# ...could be a static file needed by the front end that
# doesn't use the `static` path (like in `<script src="bundle.js">`)
file_path = './static/' + path
if os.path.isfile(file_path):
return send_file(file_path)
# ...or should be handled by the SPA's "router" in front end
else:
return send_file('./static/index.html')
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True, port=80)
| from flask import Flask, send_file
app = Flask(__name__)
@app.route("/hello")
def hello():
return "Hello World from Flask in a uWSGI Nginx Docker container with \
Python 3.6 (from the example template)"
@app.route("/")
def main():
return send_file('./static/index.html')
# Everything not declared before (not a Flask route / API endpoint)...
@app.route('/<path:path>')
def route_frontend(path):
# ...could be a static file needed by the front end that
# doesn't use the `static` path (like in `<script src="bundle.js">`)
file_path = './static/' + path
if os.path.isfile(file_path):
return send_file(file_path)
# ...or should be handled by the SPA's "router" in front end
else:
return send_file('./static/index.html')
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True, port=80)
|
Add enum for python2 install | from setuptools import setup, find_packages
from dimod import __version__, __author__, __description__, __authoremail__, _PY2
install_requires = ['decorator>=4.1.0']
if _PY2:
# enum is built-in for python 3
install_requires.append('enum')
extras_require = {'all': ['numpy']}
packages = ['dimod',
'dimod.responses',
'dimod.composites',
'dimod.samplers']
setup(
name='dimod',
version=__version__,
author=__author__,
author_email=__authoremail__,
description=__description__,
url='https://github.com/dwavesystems/dimod',
download_url='https://github.com/dwavesys/dimod/archive/0.1.1.tar.gz',
license='Apache 2.0',
packages=packages,
install_requires=install_requires,
extras_require=extras_require,
)
| from setuptools import setup, find_packages
from dimod import __version__, __author__, __description__, __authoremail__
install_requires = ['decorator>=4.1.0']
extras_require = {'all': ['numpy']}
packages = ['dimod',
'dimod.responses',
'dimod.composites',
'dimod.samplers']
setup(
name='dimod',
version=__version__,
author=__author__,
author_email=__authoremail__,
description=__description__,
url='https://github.com/dwavesystems/dimod',
download_url='https://github.com/dwavesys/dimod/archive/0.1.1.tar.gz',
license='Apache 2.0',
packages=packages,
install_requires=install_requires,
extras_require=extras_require,
)
|
Use 3.2.x reference images for developer version of Matplotlib | import matplotlib
from matplotlib import pyplot as plt
from astropy.utils.decorators import wraps
MPL_VERSION = matplotlib.__version__
# The developer versions of the form 3.1.x+... contain changes that will only
# be included in the 3.2.x release, so we update this here.
if MPL_VERSION[:3] == '3.1' and '+' in MPL_VERSION:
MPL_VERSION = '3.2'
ROOT = "http://{server}/testing/astropy/2018-10-24T12:38:34.134556/{mpl_version}/"
IMAGE_REFERENCE_DIR = (ROOT.format(server='data.astropy.org', mpl_version=MPL_VERSION[:3] + '.x') + ',' +
ROOT.format(server='www.astropy.org/astropy-data', mpl_version=MPL_VERSION[:3] + '.x'))
def ignore_matplotlibrc(func):
# This is a decorator for tests that use matplotlib but not pytest-mpl
# (which already handles rcParams)
@wraps(func)
def wrapper(*args, **kwargs):
with plt.style.context({}, after_reset=True):
return func(*args, **kwargs)
return wrapper
| import matplotlib
from matplotlib import pyplot as plt
from astropy.utils.decorators import wraps
MPL_VERSION = matplotlib.__version__
ROOT = "http://{server}/testing/astropy/2018-10-24T12:38:34.134556/{mpl_version}/"
IMAGE_REFERENCE_DIR = (ROOT.format(server='data.astropy.org', mpl_version=MPL_VERSION[:3] + '.x') + ',' +
ROOT.format(server='www.astropy.org/astropy-data', mpl_version=MPL_VERSION[:3] + '.x'))
def ignore_matplotlibrc(func):
# This is a decorator for tests that use matplotlib but not pytest-mpl
# (which already handles rcParams)
@wraps(func)
def wrapper(*args, **kwargs):
with plt.style.context({}, after_reset=True):
return func(*args, **kwargs)
return wrapper
|
Raise SystemExit if not in virtualenv. | #!/usr/bin/python
#-*- coding:utf-8 -*-
"""
Executes the methos in utils.py
This file should be running under the original python,
not an env one
"""
import sys
from venv_dependencies.venv_dep_utils import *
def main(modules):
venv = get_active_venv()
if not venv:
raise SystemExit("No virtual envs")
site_path = get_sitepackages_path(venv)
easy_install_file = get_easy_install_pth(site_path)
for m in modules:
m_path = module_path(m)
if m_path is None:
#should raise an exception?
continue
if create_symlink(m_path,site_path):
m_folder = get_module_folder(m_path)
change_easy_install_pth(easy_install_file, m_folder)
print "Module: %s has been linked." % m
if __name__ == "__main__":
modules = sys.argv[1:]
if modules:
main(modules)
| #!/usr/bin/python
#-*- coding:utf-8 -*-
"""
Executes the methos in utils.py
This file should be running under the original python,
not an env one
"""
import sys
from venv_dependencies.venv_dep_utils import *
def main(modules):
venv = get_active_venv()
if not venv:
print "No virtual envs"
#raise an exception here
return
site_path = get_sitepackages_path(venv)
easy_install_file = get_easy_install_pth(site_path)
for m in modules:
m_path = module_path(m)
if m_path is None:
#should raise an exception?
continue
if create_symlink(m_path,site_path):
m_folder = get_module_folder(m_path)
change_easy_install_pth(easy_install_file, m_folder)
print "Module: %s has been linked." % m
if __name__ == "__main__":
modules = sys.argv[1:]
if modules:
main(modules)
|
Fix nodes side panel contents integration tests | describe('Nodes Side Panel', function () {
beforeEach(function () {
cy.configureCluster({
mesos: '1-task-healthy',
nodeHealth: true
})
});
context('Navigate to node detail page', function () {
it('navigates to node side panel', function () {
cy.visitUrl({url: '/nodes', identify: true, fakeAnalytics: true});
cy.get('tr a').contains('dcos-01').click();
cy.hash().should('match', /nodes\/[a-zA-Z0-9-]+/);
cy.get('.page-content h1').should(function ($title) {
expect($title).to.contain('dcos-01');
});
});
it('shows error in side panel when node is invalid [10a]', function () {
cy.visitUrl({url: '/nodes/INVALID_NODE', identify: true, fakeAnalytics: true});
cy.hash().should('match', /nodes\/INVALID_NODE/);
cy.get('.page-content h3').should(function ($title) {
expect($title).to.contain('Error finding node');
});
});
});
});
| describe('Nodes Side Panel', function () {
beforeEach(function () {
cy.configureCluster({
mesos: '1-task-healthy',
nodeHealth: true
})
});
context('Navigate to side panel', function () {
it('navigates to node side panel', function () {
cy.visitUrl({url: '/nodes', identify: true, fakeAnalytics: true});
cy.get('tr a').contains('dcos-01').click();
cy.hash().should('match', /node-detail/);
cy.get('.side-panel-content-header h1').should(function ($title) {
expect($title).to.contain('dcos-01');
});
});
it('shows error in side panel when node is invalid [10a]', function () {
cy.visitUrl({url: '/nodes/list/node-detail/INVALID_NODE', identify: true, fakeAnalytics: true});
cy.hash().should('match', /node-detail/);
cy.get('.side-panel-content h3').should(function ($title) {
expect($title).to.contain('Error finding node');
});
});
});
});
|
Use PSR-7 responses in BackgroundQueuePerformAction | <?php
namespace wcf\action;
use Laminas\Diactoros\Response\JsonResponse;
use wcf\system\background\BackgroundQueueHandler;
use wcf\system\WCF;
/**
* Performs background queue jobs.
*
* @author Tim Duesterhus
* @copyright 2001-2019 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\Action
* @since 3.0
*/
class BackgroundQueuePerformAction extends AbstractAction
{
/**
* number of jobs that will be processed per invocation
* @var int
*/
public static $jobsPerRun = 5;
/**
* @inheritDoc
*/
public function execute()
{
parent::execute();
for ($i = 0; $i < self::$jobsPerRun; $i++) {
if (BackgroundQueueHandler::getInstance()->performNextJob() === false) {
// there were no more jobs
break;
}
}
WCF::getSession()->deleteIfNew();
return new JsonResponse(
BackgroundQueueHandler::getInstance()->getRunnableCount()
);
}
}
| <?php
namespace wcf\action;
use wcf\system\background\BackgroundQueueHandler;
use wcf\system\WCF;
/**
* Performs background queue jobs.
*
* @author Tim Duesterhus
* @copyright 2001-2019 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\Action
* @since 3.0
*/
class BackgroundQueuePerformAction extends AbstractAction
{
/**
* number of jobs that will be processed per invocation
* @var int
*/
public static $jobsPerRun = 5;
/**
* @inheritDoc
*/
public function execute()
{
parent::execute();
\header('Content-type: application/json; charset=UTF-8');
for ($i = 0; $i < self::$jobsPerRun; $i++) {
if (BackgroundQueueHandler::getInstance()->performNextJob() === false) {
// there were no more jobs
break;
}
}
echo BackgroundQueueHandler::getInstance()->getRunnableCount();
WCF::getSession()->deleteIfNew();
exit;
}
}
|
Clear "urls" field when submitting similar event | /**
* @class Denkmal_Component_EventAdd
* @extends Denkmal_Component_Abstract
*/
var Denkmal_Component_EventAdd = Denkmal_Component_Abstract.extend({
/** @type String */
_class: 'Denkmal_Component_EventAdd',
events: {
'click .addSimilar': 'addSimilar'
},
childrenEvents: {
'Denkmal_Form_EventAdd success.Create': function() {
this.$('.Denkmal_Form_EventAdd .preview').hide();
this.$('.Denkmal_Form_EventAdd .formWrapper').slideUp();
this.$('.formSuccess').slideDown();
}
},
addSimilar: function() {
this.findChild('Denkmal_Form_EventAdd').getField('urls').setValue('');
this.$('.Denkmal_Form_EventAdd .preview').show();
this.$('.Denkmal_Form_EventAdd .formWrapper').slideDown();
this.$('.formSuccess').slideUp();
}
});
| /**
* @class Denkmal_Component_EventAdd
* @extends Denkmal_Component_Abstract
*/
var Denkmal_Component_EventAdd = Denkmal_Component_Abstract.extend({
/** @type String */
_class: 'Denkmal_Component_EventAdd',
events: {
'click .addSimilar': 'addSimilar'
},
childrenEvents: {
'Denkmal_Form_EventAdd success.Create': function() {
this.$('.Denkmal_Form_EventAdd .preview').hide();
this.$('.Denkmal_Form_EventAdd .formWrapper').slideUp();
this.$('.formSuccess').slideDown();
}
},
addSimilar: function() {
this.$('.Denkmal_Form_EventAdd .preview').show();
this.$('.Denkmal_Form_EventAdd .formWrapper').slideDown();
this.$('.formSuccess').slideUp();
}
});
|
Add catch-all route to allow page refreshing | const userController = require('./users/userController.js');
const listingController = require('./listings/listingController.js');
module.exports = (app, db, path, rootPath) => {
// Routes for all users
app.get('/api/users', userController.getAll);
app.post('/api/users', userController.createOne);
// Routes for specific user
app.get('/api/users/:id', userController.getOne);
app.patch('/api/users/:id', userController.patchOne);
app.delete('/api/users/:id', userController.deleteOne);
// Routes for all listings belonging to a specific user
app.get('/api/users/:id/listings', listingController.getAll);
app.post('/api/users/:id/listings', listingController.createOne);
// Routes for a specific listing
app.get('/api/listings/:listId', listingController.getOne);
app.patch('/api/listings/:listId', listingController.patchOne);
app.delete('/api/listings/:listId', listingController.deleteOne);
// Routes for a specific listing's photos
app.get('/api/listings/:listId/photos', listingController.getAllPhotos);
app.post('/api/listings/:listId/photos', listingController.createOnePhoto);
// Routes for a specific listing's specific photo
app.patch('/api/listings/:listId/photos/:id', listingController.patchOnePhoto);
app.delete('/api/listings/:listId/photos/:id', listingController.deleteOnePhoto);
// Catch-all route to allow reloading
app.get('*', (req, res) => {
res.sendFile(path.resolve(rootPath + '/index.html'));
});
} | const userController = require('./users/userController.js');
const listingController = require('./listings/listingController.js');
module.exports = (app, db) => {
// Routes for all users
app.get('/api/users', userController.getAll);
app.post('/api/users', userController.createOne);
// Routes for specific user
app.get('api/users/:id', userController.getOne);
app.patch('api/users/:id', userController.patchOne);
app.delete('api/users/:id', userController.deleteOne);
// Routes for all listings belonging to a specific user
app.get('api/users/:id/listings', listingController.getAll);
app.post('api/users/:id/listings', listingController.createOne);
// Routes for a specific listing
app.get('api/listings/:listId', listingController.getOne);
app.patch('api/listings/:listId', listingController.patchOne);
app.delete('api/listings/:listId', listingController.deleteOne);
// Routes for a specific listing's photos
app.get('api/listings/:listId/photos', listingController.getAllPhotos);
app.post('api/listings/:listId/photos', listingController.createOnePhoto);
// Routes for a specific listing's specific photo
app.patch('api/listings/:listId/photos/:id', listingController.patchOnePhoto);
app.delete('api/listings/:listId/photos/:id', listingController.deleteOnePhoto);
} |
Replace the width property animation and let css deal with setting the numbers | import Ember from 'ember';
export default Ember.Component.extend({
classNameBindings: [':sidebar', 'isCollapsed:collapsed'],
applicationName: null,
currentUser: null,
navigationItems: [],
isCollapsed: false,
actions: {
toggleCollapse: function() {
this.toggleProperty('isCollapsed');
this.sendAction('toggleCollapse');
},
logout: function() {
this.sendAction('logout');
}
},
didInsertElement: function() {
this.addObserver('isCollapsed', this, this.resetScrollableElements);
},
resetScrollableElements: function() {
this.$().velocity({
opacity: 1
}, {
duration: 325,
progress: function() {
Ember.$('.scrollable').TrackpadScrollEmulator('recalculate');
}
});
}
});
| import Ember from 'ember';
export default Ember.Component.extend({
classNameBindings: [':sidebar', 'isCollapsed:collapsed'],
applicationName: null,
currentUser: null,
navigationItems: [],
isCollapsed: false,
actions: {
toggleCollapse: function() {
this.toggleProperty('isCollapsed');
this.sendAction('toggleCollapse');
},
logout: function() {
this.sendAction('logout');
}
},
didInsertElement: function() {
this.addObserver('isCollapsed', this, this.animateWidth);
},
animateWidth: function() {
var growth;
if (this.get('isCollapsed')) {
growth = '-= 170px';
} else {
growth = '+= 170px';
}
this.$().velocity({
width: growth
}, {
duration: 150,
progress: function() {
Ember.$('.scrollable').TrackpadScrollEmulator('recalculate');
}
});
}
});
|
Remove debug toolbar due to 'TypeError: process() takes exactly 3 arguments (2 given)' | from __future__ import absolute_import
from os.path import join, normpath
from .base import *
DEBUG = True
TEMPLATE_DEBUG = DEBUG
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': normpath(join(DJANGO_ROOT, 'bandnames.db')),
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
}
}
INSTALLED_APPS += (
# 'debug_toolbar',
)
MIDDLEWARE_CLASSES += (
# 'debug_toolbar.middleware.DebugToolbarMiddleware',
)
DEBUG_TOOLBAR_PATCH_SETTINGS = False
INTERNAL_IPS = ('127.0.0.1',)
| from __future__ import absolute_import
from os.path import join, normpath
from .base import *
DEBUG = True
TEMPLATE_DEBUG = DEBUG
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': normpath(join(DJANGO_ROOT, 'bandnames.db')),
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
}
}
INSTALLED_APPS += (
'debug_toolbar',
)
MIDDLEWARE_CLASSES += (
'debug_toolbar.middleware.DebugToolbarMiddleware',
)
DEBUG_TOOLBAR_PATCH_SETTINGS = False
INTERNAL_IPS = ('127.0.0.1',)
|
Fix violations checking:
* Redundant 'final' modifier | /*
* Copyright (C) VSPLF Software Foundation (VSF), the origin author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.vsplf.i18n.helpers;
import java.text.FieldPosition;
import java.text.Format;
import java.text.ParsePosition;
/**
* Lightweight porting of ICU MessageFormat.
*
* @author <a href="http://hoatle.net">hoatle (hoatlevan at gmail dot com)</a>
* @since Mar 23, 2012
*/
public final class MessageFormat extends Format {
@Override
public StringBuffer format(final Object obj, final StringBuffer toAppendTo,
final FieldPosition pos) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public Object parseObject(final String source, final ParsePosition pos) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
}
| /*
* Copyright (C) VSPLF Software Foundation (VSF), the origin author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.vsplf.i18n.helpers;
import java.text.FieldPosition;
import java.text.Format;
import java.text.ParsePosition;
/**
* Lightweight porting of ICU MessageFormat.
*
* @author <a href="http://hoatle.net">hoatle (hoatlevan at gmail dot com)</a>
* @since Mar 23, 2012
*/
public final class MessageFormat extends Format {
@Override
public final StringBuffer format(final Object obj, final StringBuffer toAppendTo,
final FieldPosition pos) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public final Object parseObject(final String source, final ParsePosition pos) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
}
|
Fix bug in distribution detection on unsupported platforms. | import re
from spack.architecture import OperatingSystem
class LinuxDistro(OperatingSystem):
""" This class will represent the autodetected operating system
for a Linux System. Since there are many different flavors of
Linux, this class will attempt to encompass them all through
autodetection using the python module platform and the method
platform.dist()
"""
def __init__(self):
try:
# This will throw an error if imported on a non-Linux platform.
from external.distro import linux_distribution
distname, version, _ = linux_distribution(
full_distribution_name=False)
distname, version = str(distname), str(version)
except ImportError as e:
distname, version = 'unknown', ''
# Grabs major version from tuple on redhat; on other platforms
# grab the first legal identifier in the version field. On
# debian you get things like 'wheezy/sid'; sid means unstable.
# We just record 'wheezy' and don't get quite so detailed.
version = re.split(r'[^\w-]', version)[0]
super(LinuxDistro, self).__init__(distname, version)
| import re
from external.distro import linux_distribution
from spack.architecture import OperatingSystem
class LinuxDistro(OperatingSystem):
""" This class will represent the autodetected operating system
for a Linux System. Since there are many different flavors of
Linux, this class will attempt to encompass them all through
autodetection using the python module platform and the method
platform.dist()
"""
def __init__(self):
distname, version, _ = linux_distribution(
full_distribution_name=False)
distname, version = str(distname), str(version)
# Grabs major version from tuple on redhat; on other platforms
# grab the first legal identifier in the version field. On
# debian you get things like 'wheezy/sid'; sid means unstable.
# We just record 'wheezy' and don't get quite so detailed.
version = re.split(r'[^\w-]', version)[0]
super(LinuxDistro, self).__init__(distname, version)
|
Fix bug in how loading indicator was created. You can now run xavier
inside a frame. | /*
Copyright 2014 - 2016 Roland Bouman (roland.bouman@gmail.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.
*/
var showLoadingIndicator, hideLoadingIndicator;
if (iFun(window.top.showLoadingIndicator)) {
showLoadingIndicator = function(){
win.top.showLoadingIndicator();
}
hideLoadingIndicator = function(){
win.top.hideLoadingIndicator();
}
}
else {
var spinner = new Spinner({
delayHide: 125,
useTransitions: typeof(useTransitions)==="undefined" ? true : Boolean(useTransitions)
});
showLoadingIndicator = function(){
spinner.show();
};
hideLoadingIndicator = function(){
spinner.hide();
};
}
function busy(yes){
if (yes) {
showLoadingIndicator();
}
else {
hideLoadingIndicator();
}
}
| /*
Copyright 2014 - 2016 Roland Bouman (roland.bouman@gmail.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.
*/
var showLoadingIndicator, hideLoadingIndicator;
if (iFun(window.top.showLoadingIndicator)) {
showLoadingIndicator = function(){
win.top.showLoadingIndicator();
}
hideLoadingIndicator = function(){
win.top.hideLoadingIndicator();
}
}
else {
var spinner = new Spinner({
delayHide: 125,
useTransitions: typeof(useTransitions)==="undefined" ? true : Boolean(useTransitions)
});
win.top.showLoadingIndicator = function(){
spinner.show();
};
win.top.hideLoadingIndicator = function(){
spinner.hide();
};
}
function busy(yes){
if (yes) {
showLoadingIndicator();
}
else {
hideLoadingIndicator();
}
}
|
Update version string to 2.6.0-pre.14.1 | 'use strict';
var
platform = require('enyo/platform'),
dispatcher = require('enyo/dispatcher'),
gesture = require('enyo/gesture');
exports = module.exports = require('./lib/options');
exports.version = '2.6.0-pre';
// Override the default holdpulse config to account for greater delays between keydown and keyup
// events in Moonstone with certain input devices.
gesture.drag.configureHoldPulse({
events: [{name: 'hold', time: 400}],
endHold: 'onLeave'
});
/**
* Registers key mappings for webOS-specific device keys related to media control.
*
* @private
*/
if (platform.webos >= 4) {
// Table of default keyCode mappings for webOS device
dispatcher.registerKeyMap({
415 : 'play',
413 : 'stop',
19 : 'pause',
412 : 'rewind',
417 : 'fastforward',
461 : 'back'
});
}
// ensure that these are registered
require('./lib/resolution');
require('./lib/fonts');
| 'use strict';
var
platform = require('enyo/platform'),
dispatcher = require('enyo/dispatcher'),
gesture = require('enyo/gesture');
exports = module.exports = require('./lib/options');
exports.version = '2.6.0-pre';
// Override the default holdpulse config to account for greater delays between keydown and keyup
// events in Moonstone with certain input devices.
gesture.drag.configureHoldPulse({
events: [{name: 'hold', time: 400}],
endHold: 'onLeave'
});
/**
* Registers key mappings for webOS-specific device keys related to media control.
*
* @private
*/
if (platform.webos >= 4) {
// Table of default keyCode mappings for webOS device
dispatcher.registerKeyMap({
415 : 'play',
413 : 'stop',
19 : 'pause',
412 : 'rewind',
417 : 'fastforward',
461 : 'back'
});
}
// ensure that these are registered
require('./lib/resolution');
require('./lib/fonts'); |
Add a selector star - no behaviour yet | define(['react'], function (React) {
'use strict';
var ul = React.DOM.ul
, li = React.DOM.li
, span = React.DOM.span
, a = React.DOM.a;
var Pager = React.createClass({
displayName: 'Pager',
render: function () {
var props = this.props;
return ul({className: 'pager'},
li({className: 'previous' + (props.offset ? '' : ' disabled')}, a({onClick: props.back}, "Back")),
li(null,
span(
null,
React.DOM.i(
{title: "0 selected", className: 'pointer pull-right fa fa-star-o'}),
"Items " + (props.offset + 1) + " to " + (props.offset + props.size) + " of " + props.length)),
li({className: 'next' + (props.offset + props.size >= props.length ? ' disabled' : '')}, a({onClick: props.next}, "Next")));
}
});
return Pager;
});
| define(['react'], function (React) {
'use strict';
var ul = React.DOM.ul
, li = React.DOM.li
, span = React.DOM.span
, a = React.DOM.a;
var Pager = React.createClass({
displayName: 'Pager',
render: function () {
var props = this.props;
return ul({className: 'pager'},
li({className: 'previous' + (props.offset ? '' : ' disabled')}, a({onClick: props.back}, "Back")),
li(null, span(null,
"Items " + (props.offset + 1) + " to " + (props.offset + props.size) + " of " + props.length)),
li({className: 'next' + (props.offset + props.size >= props.length ? ' disabled' : '')}, a({onClick: props.next}, "Next")));
}
});
return Pager;
});
|
Support optional success callback in ajax-forms plugin
[#75226372] | (function($) {
/**
* Downloads data and uses it to dynamically create set of select options.
* url - URL used to dynamically obtain select options (using $.ajax).
* formatResult - function that accepts data and returns an array of objects,
* where each object has two attributes: 'val' and 'text', e.g.:
* [{val: 'val1', text: 'First option'}, {val: 'val2', 'text': 'Second option'}]
* callback - optional function that will be called when AJAX request is completed.
*/
$.fn.getSelectOptions = function (url, formatResult, callback) {
$.ajax({
type: 'get',
url: url,
xhrFields: {
withCredentials: true
},
contentType: 'application/json'
}).done(success.bind(this));
function success (data) {
var options = formatResult(data);
this.filter('select').each(function() {
var $select = $(this);
$select.empty();
options.forEach(function (opt) {
$select.append($('<option>').attr('value', opt.val).text(opt.text));
});
});
if (typeof callback === 'function') {
callback();
}
}
return this;
};
}(jQuery));
| (function($) {
/**
* Downloads data and uses it to dynamically create set of select options.
* url - URL used to dynamically obtain select options (using $.ajax).
* formatResult - function that accepts data and returns an array of objects,
* where each object has two attributes: 'val' and 'text', e.g.:
* [{val: 'val1', text: 'First option'}, {val: 'val2', 'text': 'Second option'}]
*/
$.fn.getSelectOptions = function (url, formatResult) {
$.ajax({
type: 'get',
url: url,
xhrFields: {
withCredentials: true
},
contentType: 'application/json'
}).done(success.bind(this));
function success (data) {
var options = formatResult(data);
this.filter('select').each(function() {
var $select = $(this);
$select.empty();
options.forEach(function (opt) {
$select.append($('<option>').attr('value', opt.val).text(opt.text));
});
});
}
return this;
};
}(jQuery));
|
Add logging whenever someone triggers the IP blacklist | <?php
namespace App\Http\Middleware;
use Closure;
use App\IpBlacklist;
use Log;
class IPBasedBlacklist
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$ip = $request->ip();
$blacklist = IpBlacklist
::where('ip_address', $ip)
->first();
if (empty($blacklist)) {
return $next($request);
}
Log::Error(sprintf('Blocked %s from accessing %s due to reason: %s', $ip, $request->fullUrl(), $blacklist->reason));
abort(503);
}
}
| <?php
namespace App\Http\Middleware;
use Closure;
use App\IpBlacklist;
class IPBasedBlacklist
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$ip = $request->ip();
$blacklist = IpBlacklist
::where('ip_address', $ip)
->first();
if (empty($blacklist)) {
return $next($request);
}
abort(503);
}
}
|
client: Fix mui internal sheetsManager being shared between requests. | import React from 'react'
import Document, { Head, Main, NextScript } from 'next/document'
import { MuiThemeProvider } from 'material-ui/styles'
import { JssProvider, SheetsRegistry } from 'react-jss'
export default class SSRDocument extends Document {
static getInitialProps ({ renderPage }) {
const sheets = new SheetsRegistry()
const page = renderPage((Page) => (props) => (
<JssProvider registry={sheets}>
<MuiThemeProvider sheetsManager={new Map()}>
<Page {...props} />
</MuiThemeProvider>
</JssProvider>
))
return {
...page,
jss: sheets.toString()
}
}
render () {
return (
<html>
<Head>
<title>üWave</title>
<style id='ssr' dangerouslySetInnerHTML={{ __html: this.props.jss || '' }} />
</Head>
<body>
<Main />
<NextScript />
</body>
</html>
)
}
}
| import React from 'react'
import Document, { Head, Main, NextScript } from 'next/document'
import { JssProvider, SheetsRegistry } from 'react-jss'
export default class SSRDocument extends Document {
static getInitialProps ({ renderPage }) {
const sheets = new SheetsRegistry()
const page = renderPage((Page) => (props) => (
<JssProvider registry={sheets}>
<Page {...props} />
</JssProvider>
))
return {
...page,
jss: sheets.toString()
}
}
render () {
return (
<html>
<Head>
<title>üWave</title>
<style id='ssr' dangerouslySetInnerHTML={{ __html: this.props.jss || '' }} />
</Head>
<body>
<Main />
<NextScript />
</body>
</html>
)
}
}
|
Add bestja_project_hierarchy to the list of FPBZ's modules | # -*- coding: utf-8 -*-
{
'name': "Bestja: FBŻ",
'summary': "Installation configuration for FPBŻ",
'description': "Installation configuration for Federacja Polskich Banków Żywności",
'author': "Laboratorium EE",
'website': "http://www.laboratorium.ee",
'version': '0.1',
'category': 'Specific Industry Applications',
'depends': [
'base',
'bestja_base',
'bestja_volunteer',
'bestja_volunteer_notes',
'bestja_organization',
'bestja_organization_hierarchy',
'bestja_project',
'bestja_project_hierarchy',
'bestja_offers',
'bestja_files',
'email_confirmation',
'quizzes',
'bestja_organization_warehouse'
],
'application': True,
}
| # -*- coding: utf-8 -*-
{
'name': "Bestja: FBŻ",
'summary': "Installation configuration for FPBŻ",
'description': "Installation configuration for Federacja Polskich Banków Żywności",
'author': "Laboratorium EE",
'website': "http://www.laboratorium.ee",
'version': '0.1',
'category': 'Specific Industry Applications',
'depends': [
'base',
'bestja_base',
'bestja_volunteer',
'bestja_volunteer_notes',
'bestja_organization',
'bestja_organization_hierarchy',
'bestja_project',
'bestja_offers',
'bestja_files',
'email_confirmation',
'quizzes',
'bestja_organization_warehouse'
],
'application': True,
}
|
Test now checks that transformer returned includes source if called before source added then after | package me.nallar.mixin.internal;
import lombok.val;
import me.nallar.mixin.internal.mixinsource.MixinSource;
import org.junit.Assert;
import org.junit.Test;
public class MixinApplicatorTest {
@Test
public void testGetMixinTransformer() throws Exception {
val applicator = new MixinApplicator();
applicator.addSource(MixinSource.class);
val transformer = applicator.getMixinTransformer();
Assert.assertTrue("Must have at least one mixin transformer registered", transformer.getClassTransformers().size() != 0);
}
@Test
public void testGetMixinTransformerWithPackageSource() throws Exception {
val applicator = new MixinApplicator();
applicator.addSource("me.nallar.mixin.internal.mixinsource");
val transformer = applicator.getMixinTransformer();
Assert.assertTrue("Must have at least one mixin transformer registered", transformer.getClassTransformers().size() != 0);
}
@Test
public void testGetMixinTransformerWithPackageSourceWrongOrder() throws Exception {
val applicator = new MixinApplicator();
applicator.getMixinTransformer();
applicator.addSource("me.nallar.mixin.internal.mixinsource");
val transformer = applicator.getMixinTransformer();
Assert.assertTrue("Must have at least one mixin transformer registered", transformer.getClassTransformers().size() != 0);
}
}
| package me.nallar.mixin.internal;
import lombok.val;
import me.nallar.mixin.internal.mixinsource.MixinSource;
import org.junit.Assert;
import org.junit.Test;
public class MixinApplicatorTest {
@Test
public void testGetMixinTransformer() throws Exception {
val applicator = new MixinApplicator();
applicator.addSource(MixinSource.class);
val transformer = applicator.getMixinTransformer();
Assert.assertTrue("Must have at least one mixin transformer registered", transformer.getClassTransformers().size() != 0);
}
@Test
public void testGetMixinTransformerWithPackageSource() throws Exception {
val applicator = new MixinApplicator();
applicator.addSource("me.nallar.mixin.internal.mixinsource");
val transformer = applicator.getMixinTransformer();
Assert.assertTrue("Must have at least one mixin transformer registered", transformer.getClassTransformers().size() != 0);
}
@Test(expected = IllegalStateException.class)
public void testGetMixinTransformerWithPackageSourceWrongOrder() throws Exception {
val applicator = new MixinApplicator();
applicator.getMixinTransformer();
applicator.addSource("me.nallar.mixin.internal.mixinsource");
}
}
|
Migrate only archive manager keys | import { TASK_TYPE_HIGH_PRIORITY } from "@buttercup/channel-queue";
import log from "../../shared/library/log.js";
import { getDefaultStorageAdapter } from "./BrowserStorageInterface.js";
export function migrateLocalStorageToChromeStorage(queue) {
log.info("(Migration)", "Beginning data migration for new storage");
return queue
.channel("archiveManager")
.enqueue(() => {
const browserStorage = getDefaultStorageAdapter();
const keys = Object.keys(window.localStorage).filter(key => /^bcup_archivemgr/.test(key));
const payload = keys.reduce(
(current, key) => ({
...current,
[key]: window.localStorage[key]
}),
{}
);
log.info("(Migration)", `Migrating ${keys.length} keys`);
return new Promise(resolve => {
browserStorage.set(payload, resolve);
});
}, TASK_TYPE_HIGH_PRIORITY)
.then(() => {
log.info("(Migration)", "Migration complete");
});
}
| import { TASK_TYPE_HIGH_PRIORITY } from "@buttercup/channel-queue";
import log from "../../shared/library/log.js";
import { getDefaultStorageAdapter } from "./BrowserStorageInterface.js";
export function migrateLocalStorageToChromeStorage(queue) {
log.info("(Migration)", "Beginning data migration for new storage");
return queue
.channel("archiveManager")
.enqueue(() => {
const browserStorage = getDefaultStorageAdapter();
const payload = Object.keys(window.localStorage).reduce(
(current, key) => ({
...current,
[key]: window.localStorage[key]
}),
{}
);
log.info("(Migration)", `Migrating ${Object.keys(payload).length} keys`);
return new Promise(resolve => {
browserStorage.set(payload, resolve);
});
}, TASK_TYPE_HIGH_PRIORITY)
.then(() => {
log.info("(Migration)", "Migration complete");
});
}
|
Add more requirements that are needed for this module | from setuptools import setup
import transip
setup(
name = transip.__name__,
version = transip.__version__,
author = transip.__author__,
author_email = transip.__email__,
license = transip.__license__,
description = transip.__doc__.splitlines()[0],
long_description = open('README.rst').read(),
url = 'http://github.com/goabout/transip-backup',
download_url = 'http://github.com/goabout/transip-backup/archives/master',
packages = ['transip', 'transip.service'],
include_package_data = True,
zip_safe = False,
platforms = ['all'],
test_suite = 'tests',
entry_points = {
'console_scripts': [
'transip-api = transip.transip_cli:main',
],
},
install_requires = [
'requests',
'rsa',
'suds',
],
)
| from setuptools import setup
import transip
setup(
name = transip.__name__,
version = transip.__version__,
author = transip.__author__,
author_email = transip.__email__,
license = transip.__license__,
description = transip.__doc__.splitlines()[0],
long_description = open('README.rst').read(),
url = 'http://github.com/goabout/transip-backup',
download_url = 'http://github.com/goabout/transip-backup/archives/master',
packages = ['transip', 'transip.service'],
include_package_data = True,
zip_safe = False,
platforms = ['all'],
test_suite = 'tests',
entry_points = {
'console_scripts': [
'transip-api = transip.transip_cli:main',
],
},
install_requires = [
'requests',
],
)
|
Correct to pass JSHINT check | var zheader,version,url;
var u = "https://developers.zomato.com/api/";
var Zomato = {
init:function (opts) {
if (opts.key!=null) {
zheader = {
Accept : "text/plain; charset=utf-8",
"Content-Type": "text/plain; charset=utf-8",
"X-Zomato-API-Key":opts.key
};
} else {
console.error("Enter the key");
}
version = opts.version||"v2.1";
url = u + version;
},
restaurant:function (resid,scb,ecb) {
if (resid==null) {
console.error("Enter the restaurant id correctly");
} else {
$.ajax({
url:url+"/restaurant?res_id=" + resid,
headers:zheader,
success:function (response) {
scb(response);
},
error:function (res) {
ecb(res);
}
});
}
}
};
| var zheader,version,url;
var u = "https://developers.zomato.com/api/"
var Zomato = {
init:function (opts) {
if (opts.key!=null) {
zheader = {
Accept : "text/plain; charset=utf-8",
"Content-Type": "text/plain; charset=utf-8",
"X-Zomato-API-Key":opts.key
}
} else {
console.error("Enter the key");
};
version = opts.version||"v2.1";
url = u + version
},
restaurant:function (resid,scb,ecb) {
if (resid==null) {
console.error("Enter the restaurant id correctly");
} else {
$.ajax({
url:url+"/restaurant?res_id=" + resid,
headers:zheader,
success:function (response) {
scb(response);
},
error:function (res) {
ecb(res)
}
});
}
}
} |
organisation: Fix references to old model fields | from haystack import indexes
from .models import Person, Project, WorkingGroup, NetworkGroup
class PersonIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
twitter = indexes.CharField(model_attr='twitter')
url = indexes.CharField(model_attr='url')
def get_model(self):
return Person
class ProjectIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
twitter = indexes.CharField(model_attr='twitter')
homepage_url = indexes.CharField(model_attr='homepage_url')
mailinglist_url = indexes.CharField(model_attr='mailinglist_url')
sourcecode_url = indexes.CharField(model_attr='sourcecode_url')
def get_model(self):
return Project
class WorkingGroupIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
incubation = indexes.BooleanField(model_attr='incubation')
def get_model(self):
return WorkingGroup
class NetworkGroupIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
twitter = indexes.CharField(model_attr='twitter')
homepage_url = indexes.CharField(model_attr='homepage_url')
mailinglist_url = indexes.CharField(model_attr='mailinglist_url')
def get_model(self):
return NetworkGroup
| from haystack import indexes
from .models import Person, Project, WorkingGroup, NetworkGroup
class PersonIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
twitter = indexes.CharField(model_attr='twitter')
url = indexes.CharField(model_attr='url')
def get_model(self):
return Person
class ProjectIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
twitter = indexes.CharField(model_attr='twitter')
homepage_url = indexes.CharField(model_attr='homepage_url')
mailinglist_url = indexes.CharField(model_attr='mailinglist_url')
sourcecode_url = indexes.CharField(model_attr='sourcecode_url')
def get_model(self):
return Project
class WorkingGroupIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
incubation = indexes.BooleanField(model_attr='incubation')
def get_model(self):
return WorkingGroup
class NetworkGroupIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
mailinglist = indexes.CharField(model_attr='mailinglist')
homepage = indexes.CharField(model_attr='homepage')
twitter = indexes.CharField(model_attr='twitter')
def get_model(self):
return NetworkGroup
|
Add PBE support to current-game and featured-games endpoints | package constant;
/*
* Copyright 2015 Taylor Caldwell
*
* 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.
*/
public enum PlatformId {
NA("NA1", "na"),
BR("BR1", "br"),
LAN("LA1", "lan"),
LAS("LA2", "las"),
OCE("OC1", "oce"),
EUNE("EUN1", "eune"),
EUW("EUW1", "euw"),
KR("KR", "kr"),
RU("RU", "ru"),
TR("TR1", "tr"),
PBE("PBE1", "pbe");
private String id;
private String name;
PlatformId(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
}
| package constant;
/*
* Copyright 2015 Taylor Caldwell
*
* 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.
*/
public enum PlatformId {
NA("NA1", "na"),
BR("BR1", "br"),
LAN("LA1", "lan"),
LAS("LA2", "las"),
OCE("OC1", "oce"),
EUNE("EUN1", "eune"),
EUW("EUW1", "euw"),
KR("KR", "kr"),
RU("RU", "ru"),
TR("TR1", "tr");
private String id;
private String name;
PlatformId(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
}
|
Update the PyPI home page URL. | from setuptools import setup
setup(
name='django-waffle',
version='0.1.1',
description='A feature flipper for Django.',
long_description=open('README.rst').read(),
author='James Socol',
author_email='james.socol@gmail.com',
url='http://github.com/jsocol/django-waffle',
license='BSD',
packages=['waffle'],
include_package_data=True,
package_data = { '': ['README.rst'] },
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
| from setuptools import setup
setup(
name='django-waffle',
version='0.1.1',
description='A feature flipper for Django.',
long_description=open('README.rst').read(),
author='James Socol',
author_email='james.socol@gmail.com',
url='http://github.com/jsocol/bleach',
license='BSD',
packages=['waffle'],
include_package_data=True,
package_data = { '': ['README.rst'] },
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
|
Change tags to kwarg in full text record
This change will allow us to set the tags value with kwargs that are set
in custom attribute values. | # Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
from ggrc.extensions import get_extension_instance
class Indexer(object):
def __init__(self, settings):
pass
def create_record(self, record):
raise NotImplementedError()
def update_record(self, record):
raise NotImplementedError()
def delete_record(self, key):
raise NotImplementedError()
def search(self, terms):
raise NotImplementedError()
class Record(object):
def __init__(self, key, type, context_id, tags="", **kwargs):
self.key = key
self.type = type
self.context_id = context_id
self.tags = tags
self.properties = kwargs
def resolve_default_text_indexer():
from ggrc import settings
db_scheme = settings.SQLALCHEMY_DATABASE_URI.split(':')[0].split('+')[0]
return 'ggrc.fulltext.{db_scheme}.Indexer'.format(db_scheme=db_scheme)
def get_indexer(indexer=[]):
return get_extension_instance(
'FULLTEXT_INDEXER', resolve_default_text_indexer)
| # Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
from ggrc.extensions import get_extension_instance
class Indexer(object):
def __init__(self, settings):
pass
def create_record(self, record):
raise NotImplementedError()
def update_record(self, record):
raise NotImplementedError()
def delete_record(self, key):
raise NotImplementedError()
def search(self, terms):
raise NotImplementedError()
class Record(object):
def __init__(self, key, type, context_id, tags, **kwargs):
self.key = key
self.type = type
self.context_id = context_id
self.tags = tags
self.properties = kwargs
def resolve_default_text_indexer():
from ggrc import settings
db_scheme = settings.SQLALCHEMY_DATABASE_URI.split(':')[0].split('+')[0]
return 'ggrc.fulltext.{db_scheme}.Indexer'.format(db_scheme=db_scheme)
def get_indexer(indexer=[]):
return get_extension_instance(
'FULLTEXT_INDEXER', resolve_default_text_indexer)
|
Use commas for the CSV Reader
Since CSV means comma separated values it seems only logical that its the default. A similar change was made against the CsvReader awhile back and I just noticed the CsvReaderFactory has the same issue. | <?php
namespace Ddeboer\DataImport\Reader\Factory;
use Ddeboer\DataImport\Reader\CsvReader;
/**
* Factory that creates CsvReaders
*
*/
class CsvReaderFactory
{
protected $delimiter;
protected $enclosure;
protected $escape;
protected $headerRowNumber;
protected $strict;
public function __construct(
$headerRowNumber = null,
$strict = true,
$delimiter = ',',
$enclosure = '"',
$escape = '\\'
) {
$this->headerRowNumber = $headerRowNumber;
$this->strict = $strict;
$this->delimiter = $delimiter;
$this->enclosure = $enclosure;
$this->escape = $escape;
}
public function getReader(\SplFileObject $file)
{
$reader = new CsvReader($file, $this->delimiter, $this->enclosure, $this->escape);
if (null !== $this->headerRowNumber) {
$reader->setHeaderRowNumber($this->headerRowNumber);
}
$reader->setStrict($this->strict);
return $reader;
}
}
| <?php
namespace Ddeboer\DataImport\Reader\Factory;
use Ddeboer\DataImport\Reader\CsvReader;
/**
* Factory that creates CsvReaders
*
*/
class CsvReaderFactory
{
protected $delimiter;
protected $enclosure;
protected $escape;
protected $headerRowNumber;
protected $strict;
public function __construct(
$headerRowNumber = null,
$strict = true,
$delimiter = ';',
$enclosure = '"',
$escape = '\\'
) {
$this->headerRowNumber = $headerRowNumber;
$this->strict = $strict;
$this->delimiter = $delimiter;
$this->enclosure = $enclosure;
$this->escape = $escape;
}
public function getReader(\SplFileObject $file)
{
$reader = new CsvReader($file, $this->delimiter, $this->enclosure, $this->escape);
if (null !== $this->headerRowNumber) {
$reader->setHeaderRowNumber($this->headerRowNumber);
}
$reader->setStrict($this->strict);
return $reader;
}
}
|
Disable (really annoying) spelling auto correct. | 'use strict';
const getDictionaries = require('./hunspell-dictionaries').getDictionaries;
const getSpellChecker = require('./hunspell-checker');
const webframe = require('web-frame');
function createAndRegisterSpellchecker(language) {
getDictionaries()
.then(dictionaries => {
return dictionaries[language];
})
.then(getSpellChecker)
.then(checker => {
registerSpellChecker(language, checker);
})
.catch(exception => {
console.log(exception);
})
;
}
function registerSpellChecker(language, checker) {
webframe.setSpellCheckProvider(language, false, {
spellCheck: word => {
return checker.check(word);
}
});
}
exports.initialise = createAndRegisterSpellchecker;
| 'use strict';
const getDictionaries = require('./hunspell-dictionaries').getDictionaries;
const getSpellChecker = require('./hunspell-checker');
const webframe = require('web-frame');
function createAndRegisterSpellchecker(language) {
getDictionaries()
.then(dictionaries => {
return dictionaries[language];
})
.then(getSpellChecker)
.then(checker => {
registerSpellChecker(language, checker);
})
.catch(exception => {
console.log(exception);
})
;
}
function registerSpellChecker(language, checker) {
webframe.setSpellCheckProvider(language, true, {
spellCheck: word => {
return checker.check(word);
}
});
}
exports.initialise = createAndRegisterSpellchecker;
|
Fix for empty strings (previously '' was just removed) | #!/usr/bin/env python
"""
Copyright (c) 2006-2013 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
import re
from lib.core.exception import SqlmapUndefinedMethod
class Syntax:
"""
This class defines generic syntax functionalities for plugins.
"""
def __init__(self):
pass
@staticmethod
def _escape(expression, quote=True, escaper=None):
retVal = expression
if quote:
for item in re.findall(r"'[^']*'+", expression, re.S):
_ = item[1:-1]
if _:
retVal = retVal.replace(item, escaper(_))
else:
retVal = escaper(expression)
return retVal
@staticmethod
def escape(expression, quote=True):
errMsg = "'escape' method must be defined "
errMsg += "inside the specific DBMS plugin"
raise SqlmapUndefinedMethod(errMsg)
| #!/usr/bin/env python
"""
Copyright (c) 2006-2013 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
import re
from lib.core.exception import SqlmapUndefinedMethod
class Syntax:
"""
This class defines generic syntax functionalities for plugins.
"""
def __init__(self):
pass
@staticmethod
def _escape(expression, quote=True, escaper=None):
retVal = expression
if quote:
for item in re.findall(r"'[^']*'+", expression, re.S):
retVal = retVal.replace(item, escaper(item[1:-1]))
else:
retVal = escaper(expression)
return retVal
@staticmethod
def escape(expression, quote=True):
errMsg = "'escape' method must be defined "
errMsg += "inside the specific DBMS plugin"
raise SqlmapUndefinedMethod(errMsg)
|
Add decorator to connect to database | from flask import Flask, render_template, redirect, request
import psycopg2
from functools import wraps
import os
import urlparse
app = Flask(__name__)
def connectDB(wrapped):
@wraps(wrapped)
def inner(*args, **kwargs):
urlparse.uses_netloc.append("postgres")
url = urlparse.urlparse(os.environ["DATABASE_URL"])
conn = psycopg2.connect(
database=url.path[1:],
user=url.username,
password=url.password,
host=url.hostname,
port=url.port
)
cur = conn.cursor()
return wrapped(cur, *args, **kwargs)
return inner
@app.route('/')
def home():
return render_template('home.html')
@app.route('/participants')
@connectDB
def participants(*args):
return args[0]
@app.route('/setup')
def setup():
return render_template('setup.html')
@app.route('/register')
def register():
return render_template('register.html')
@app.route('/complete', methods=['POST'])
@connectDB
def complete(*args):
return render_template('/success.html')
| from flask import Flask, render_template, redirect
import psycopg2
import os
import urlparse
app = Flask(__name__)
# def connectDB(wrapped):
# def inner(*args, **kwargs):
# api_token = os.environ["API_TOKEN"]
# urlparse.uses_netloc.append("postgres")
# url = urlparse.urlparse(os.environ["DATABASE_URL"])
# conn = psycopg2.connect(
# database=url.path[1:],
# user=url.username,
# password=url.password,
# host=url.hostname,
# port=url.port
# )
# cur = conn.cursor()
# ret = wrapped(*args, **kwargs)
# return ret
# return inner
@app.route('/')
def home():
return render_template('home.html')
@app.route('/participants')
# @connectDB
def participants():
return render_template('participants.html')
@app.route('/setup')
def setup():
return render_template('setup.html')
@app.route('/register')
def register():
return render_template('register.html')
@app.route('/complete', methods=['POST'])
# @connectDB
def complete():
return redirect('/')
|
Rename pypi package and change author | from setuptools import setup, find_packages
from plotbitrate import __version__
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name='plotbitrate',
version=__version__,
packages=find_packages(),
description='A simple bitrate plotter for media files',
long_description=long_description,
long_description_content_type="text/markdown",
author='Eric Work',
author_email='work.eric@gmail.com',
license='BSD',
url='https://github.com/zeroepoch/plotbitrate',
py_modules=['plotbitrate'],
classifiers=[
'Topic :: Multimedia :: Sound/Audio',
'Natural Language :: English',
'Programming Language :: Python :: 3.5',
],
keywords='ffprobe bitrate plot',
python_requires='>=3.5',
entry_points={
'console_scripts': [
'plotbitrate = plotbitrate:main'
]
},
install_requires=[
'matplotlib',
'pyqt5'
]
)
| from setuptools import setup, find_packages
from plotbitrate import __version__
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name='rezun-plotbitrate',
version=__version__,
packages=find_packages(),
description='A simple bitrate plotter for media files',
long_description=long_description,
long_description_content_type="text/markdown",
author='Steve Schmidt',
author_email='azcane@gmail.com',
license='BSD',
url='https://github.com/rezun/plotbitrate',
py_modules=['plotbitrate'],
classifiers=[
'Topic :: Multimedia :: Sound/Audio',
'Natural Language :: English',
'Programming Language :: Python :: 3.5',
],
keywords='ffprobe bitrate plot',
python_requires='>=3.5',
entry_points={
'console_scripts': [
'plotbitrate = plotbitrate:main'
]
},
install_requires=[
'matplotlib',
'pyqt5'
]
)
|
Fix the yarn start command caused by WebpackDevServer config change | const WebpackDevServer = require('webpack-dev-server')
const webpack = require('webpack')
const config = require('../webpack.config')()
const env = require('./env')
const path = require('path')
const options = config.chromeExtensionBoilerplate || {}
const excludeEntriesToHotReload = options.notHotReload || []
for (const entryName in config.entry) {
if (excludeEntriesToHotReload.indexOf(entryName) === -1) {
config.entry[entryName] = [
'webpack-dev-server/client?http://localhost:' + env.PORT,
'webpack/hot/dev-server'
].concat(config.entry[entryName])
}
}
config.plugins = [new webpack.HotModuleReplacementPlugin()].concat(
config.plugins || []
)
delete config.chromeExtensionBoilerplate
const compiler = webpack({ ...config, mode: 'development' })
const server = new WebpackDevServer(compiler, {
devMiddleware: {
writeToDisk: true,
},
hot: true,
headers: { 'Access-Control-Allow-Origin': '*' }
})
server.listen(env.PORT)
| const WebpackDevServer = require('webpack-dev-server')
const webpack = require('webpack')
const config = require('../webpack.config')()
const env = require('./env')
const path = require('path')
const options = config.chromeExtensionBoilerplate || {}
const excludeEntriesToHotReload = options.notHotReload || []
for (const entryName in config.entry) {
if (excludeEntriesToHotReload.indexOf(entryName) === -1) {
config.entry[entryName] = [
'webpack-dev-server/client?http://localhost:' + env.PORT,
'webpack/hot/dev-server'
].concat(config.entry[entryName])
}
}
config.plugins = [new webpack.HotModuleReplacementPlugin()].concat(
config.plugins || []
)
delete config.chromeExtensionBoilerplate
const compiler = webpack({ ...config, mode: 'development' })
const server = new WebpackDevServer(compiler, {
stats: 'minimal',
hot: true,
writeToDisk: true,
disableHostCheck: true,
contentBase: path.join(__dirname, '../build'),
headers: { 'Access-Control-Allow-Origin': '*' }
})
server.listen(env.PORT)
|
Fix idepotency issues in healthcheck update | package io.cattle.iaas.healthcheck.process;
import static io.cattle.platform.core.model.tables.InstanceTable.*;
import io.cattle.platform.core.constants.HealthcheckConstants;
import io.cattle.platform.engine.handler.HandlerResult;
import io.cattle.platform.engine.handler.ProcessPostListener;
import io.cattle.platform.engine.process.ProcessInstance;
import io.cattle.platform.engine.process.ProcessState;
import io.cattle.platform.process.common.handler.AbstractObjectProcessLogic;
import java.util.Date;
import javax.inject.Named;
@Named
public class InstanceHealthCheckUpdate extends AbstractObjectProcessLogic implements ProcessPostListener {
@Override
public String[] getProcessNames() {
return new String[] { HealthcheckConstants.PROCESS_UPDATE_HEALTHY,
HealthcheckConstants.PROCESS_UPDATE_UNHEALTHY, HealthcheckConstants.PROCESS_UPDATE_REINITIALIZING };
}
@Override
public HandlerResult handle(ProcessState state, ProcessInstance process) {
Object now = state.getData().get("now");
Long nowLong = System.currentTimeMillis();
if (now instanceof Number) {
nowLong = ((Number) now).longValue();
} else {
state.getData().put("now", nowLong);
}
return new HandlerResult(INSTANCE.HEALTH_UPDATED, new Date(nowLong));
}
}
| package io.cattle.iaas.healthcheck.process;
import static io.cattle.platform.core.model.tables.InstanceTable.*;
import io.cattle.platform.core.constants.HealthcheckConstants;
import io.cattle.platform.engine.handler.HandlerResult;
import io.cattle.platform.engine.handler.ProcessPostListener;
import io.cattle.platform.engine.process.ProcessInstance;
import io.cattle.platform.engine.process.ProcessState;
import io.cattle.platform.process.common.handler.AbstractObjectProcessLogic;
import java.util.Date;
import javax.inject.Named;
@Named
public class InstanceHealthCheckUpdate extends AbstractObjectProcessLogic implements ProcessPostListener {
@Override
public String[] getProcessNames() {
return new String[] { HealthcheckConstants.PROCESS_UPDATE_HEALTHY,
HealthcheckConstants.PROCESS_UPDATE_UNHEALTHY, HealthcheckConstants.PROCESS_UPDATE_REINITIALIZING };
}
@Override
public HandlerResult handle(ProcessState state, ProcessInstance process) {
return new HandlerResult(INSTANCE.HEALTH_UPDATED, new Date());
}
}
|
Remove unnecessary $mdDialog from the EmailConfirmationCtrl. | angular.module("ccj16reg.view.emailConfirmation", ["ngRoute", "ngMaterial", "ccj16reg.registration"])
.config(function($routeProvider) {
"use strict";
$routeProvider.when("/confirmpreregistration", {
templateUrl: "views/emailConfirmation/emailConfirmation.html",
controller: "EmailConfirmationCtrl",
});
})
.controller("EmailConfirmationCtrl", function($scope, $location, $routeParams, Registration) {
"use strict";
$scope.verifying = true;
$scope.error = false;
$scope.email = $routeParams.email;
var token = $routeParams.token;
if (!angular.isDefined($scope.email) || !angular.isDefined(token)) {
$location.path("/register")
} else {
Registration.confirmEmail($scope.email, token).then(function() {
$scope.verifying = false;
}, function(resp) {
$scope.verifying = false;
$scope.error = resp.data.trim();
});
}
});
| angular.module("ccj16reg.view.emailConfirmation", ["ngRoute", "ngMaterial", "ccj16reg.registration"])
.config(function($routeProvider) {
"use strict";
$routeProvider.when("/confirmpreregistration", {
templateUrl: "views/emailConfirmation/emailConfirmation.html",
controller: "EmailConfirmationCtrl",
});
})
.controller("EmailConfirmationCtrl", function($scope, $location, $mdDialog, $routeParams, Registration) {
"use strict";
$scope.verifying = true;
$scope.error = false;
$scope.email = $routeParams.email;
var token = $routeParams.token;
if (!angular.isDefined($scope.email) || !angular.isDefined(token)) {
$location.path("/register")
} else {
Registration.confirmEmail($scope.email, token).then(function() {
$scope.verifying = false;
}, function(resp) {
$scope.verifying = false;
$scope.error = resp.data.trim();
});
}
});
|
Remove call to undefined method from service provider | <?php namespace Weidner\Goutte;
use Weidner\Goutte\Goutte;
use Illuminate\Support\ServiceProvider;
class GoutteServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->registerGoutte();
$this->app->alias('goutte', 'Goutte\Client');
}
/**
* Register the Goutte instance.
*
* @return void
*/
protected function registerGoutte()
{
$this->app->bindShared('goutte', function($app)
{
return new \Goutte\Client();
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return [ 'goutte' ];
}
}
| <?php namespace Weidner\Goutte;
use Weidner\Goutte\Goutte;
use Illuminate\Support\ServiceProvider;
class GoutteServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$this->package('weidner/goutte');
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->registerGoutte();
$this->app->alias('goutte', 'Goutte\Client');
}
/**
* Register the Goutte instance.
*
* @return void
*/
protected function registerGoutte()
{
$this->app->bindShared('goutte', function($app)
{
return new \Goutte\Client();
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return [ 'goutte' ];
}
}
|
Add Update Position For Hue Slider | let React = require("react")
let Colr = require("colr")
let cx = require("classnames")
let draggable = require('./higher_order_components/draggable')
let {errorList, sizeClassNames, formGroupCx, label} = require("../../util.js")
let {div, input, img} = React.DOM
@draggable
export default class extends React.Component {
static defaultProps = Object.assign(require("../../default_props.js"))
static propTypes = {
value: React.PropTypes.number.isRequired,
}
_updatePosition(clientX, clientY) {
let rect = React.findDOMNode(this).getBoundingClientRect()
let value = this.getScaledValue((rect.bottom - clientY) / rect.height)
this.props.onChange(value)
}
render() {
return div({
className: "slider vertical",
onMouseDown: this.startUpdates.bind(this),
onTouchStart: this.startUpdates.bind(this),
},
div({
className: "track",
}),
div({
className: "pointer",
style: {
"bottom": this.getPercentageValue(this.props.value),
},
})
)
}
} | let React = require("react")
let Colr = require("colr")
let cx = require("classnames")
let draggable = require('./higher_order_components/draggable')
let {errorList, sizeClassNames, formGroupCx, label} = require("../../util.js")
let {div, input, img} = React.DOM
@draggable
export default class extends React.Component {
static defaultProps = Object.assign(require("../../default_props.js"))
static propTypes = {
value: React.PropTypes.number.isRequired,
}
render() {
return div({
className: "slider vertical",
onMouseDown: this.startUpdates.bind(this),
onTouchStart: this.startUpdates.bind(this),
},
div({
className: "track",
}),
div({
className: "pointer",
style: {
"bottom": this.getPercentageValue(this.props.value),
},
})
)
}
} |
Disable incognito check because its not working | import './styles/styles.scss'
import React from 'react'
import ReactDOM from 'react-dom'
import { useRouterHistory } from 'react-router'
import { syncHistoryWithStore } from 'react-router-redux'
import { createHistory } from 'history'
import { Root } from './components/root'
import { initAuthAsync } from './core/auth'
import authRouteResolver from './core/auth/route-resolver'
import configureStore from './core/store'
import { fixScrollOn } from './page/fix-scroll'
import { checkIncognito } from './page/check-incognito'
// import * as appActions from 'src/core/app'
const history = useRouterHistory(createHistory)({basename: '/'})
const store = configureStore()
const syncedHistory = syncHistoryWithStore(history, store)
// Initial auth loading action
store.dispatch(initAuthAsync())
ReactDOM.render((
<Root history={syncedHistory} onEnter={authRouteResolver(store.getState)} store={store} />
), document.querySelector('.app-root'))
// Fix the scroll issues by default
fixScrollOn()
const isIncognito = checkIncognito()
if (isIncognito) {
// store.dispatch(appActions.isIncognito())
}
| import './styles/styles.scss'
import React from 'react'
import ReactDOM from 'react-dom'
import { useRouterHistory } from 'react-router'
import { syncHistoryWithStore } from 'react-router-redux'
import { createHistory } from 'history'
import { Root } from './components/root'
import { initAuthAsync } from './core/auth'
import authRouteResolver from './core/auth/route-resolver'
import configureStore from './core/store'
import { fixScrollOn } from './page/fix-scroll'
import { checkIncognito } from './page/check-incognito'
import * as appActions from 'src/core/app'
const history = useRouterHistory(createHistory)({basename: '/'})
const store = configureStore()
const syncedHistory = syncHistoryWithStore(history, store)
// Initial auth loading action
store.dispatch(initAuthAsync())
ReactDOM.render((
<Root history={syncedHistory} onEnter={authRouteResolver(store.getState)} store={store} />
), document.querySelector('.app-root'))
// Fix the scroll issues by default
fixScrollOn()
const isIncognito = checkIncognito()
if (isIncognito) {
store.dispatch(appActions.isIncognito())
}
|
Use __build__ syntax instead of os.environ | #!/usr/bin/env python
from setuptools import setup, find_packages
__version__ = '1.0'
# Jenkins will replace __build__ with a unique value.
__build__ = ''
setup(name='confab',
version=__version__ + __build__,
description='Configuration management with Fabric and Jinja2.',
author='Location Labs',
author_email='info@locationlabs.com',
url='http://github.com/locationlabs/confab',
license='Apache2',
packages=find_packages(exclude=['*.tests']),
setup_requires=[
'nose>=1.0'
],
install_requires=[
'Fabric>=1.4',
'Jinja2>=2.4',
'python-magic'
],
test_suite='confab.tests',
entry_points={
'console_scripts': [
'confab = confab.main:main',
]
},
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
import os
version = '1.0' + os.environ.get('BUILD_SUFFIX', '')
setup(name='confab',
version=version,
description='Configuration management with Fabric and Jinja2.',
author='Location Labs',
author_email='info@locationlabs.com',
url='http://github.com/locationlabs/confab',
license='Apache2',
packages=find_packages(exclude=['*.tests']),
setup_requires=[
'nose>=1.0'
],
install_requires=[
'Fabric>=1.4',
'Jinja2>=2.4',
'python-magic'
],
test_suite='confab.tests',
entry_points={
'console_scripts': [
'confab = confab.main:main',
]
},
)
|
Update webpack config to use nodeExternals | import path from 'path'
import nodeExternals from 'webpack-node-externals'
export default {
module: {
loaders: [{
test: /\.jsx?$/,
loaders: ['babel-loader'],
exclude: /node_modules/,
}, {
test: /\.json$/,
loader: 'json-loader',
},
{
test: /\.(png|woff|woff2|eot|ttf|svg)$/,
loader: 'url-loader?limit=100000',
},
],
},
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
libraryTarget: 'commonjs2',
},
resolve: {
extensions: ['', '.js', '.jsx'],
packageMains: ['webpack', 'browser', 'web', 'browserify', ['jam', 'main'], 'main'],
},
plugins: [
],
externals: [
nodeExternals({
whitelist: ['webpack-hot-middleware/client?path=http://localhost:3000/__webpack_hmr', 'normalize.css'],
}),
// put your node 3rd party libraries which can't be built with webpack here
// (mysql, mongodb, and so on..)
],
}
| import path from 'path'
export default {
module: {
loaders: [{
test: /\.jsx?$/,
loaders: ['babel-loader'],
exclude: /node_modules/,
}, {
test: /\.json$/,
loader: 'json-loader',
},
{
test: /\.(png|woff|woff2|eot|ttf|svg)$/,
loader: 'url-loader?limit=100000',
},
],
},
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
libraryTarget: 'commonjs2',
},
resolve: {
extensions: ['', '.js', '.jsx'],
packageMains: ['webpack', 'browser', 'web', 'browserify', ['jam', 'main'], 'main'],
},
plugins: [
],
externals: [
// put your node 3rd party libraries which can't be built with webpack here
// (mysql, mongodb, and so on..)
],
}
|
Revert "Added filters to stop WordPress from automatically adding p tags"
This reverts commit 28770297b88c997c8ec9e7952eeb88e77248f7d3. | <?php
namespace Roots\Sage\Extras;
use Roots\Sage\Config;
/**
* Add <body> classes
*/
function body_class($classes) {
// Add page slug if it doesn't exist
if (is_single() || is_page() && !is_front_page()) {
if (!in_array(basename(get_permalink()), $classes)) {
$classes[] = basename(get_permalink());
}
}
// Add class if sidebar is active
if (Config\display_sidebar()) {
$classes[] = 'sidebar-primary';
}
return $classes;
}
add_filter('body_class', __NAMESPACE__ . '\\body_class');
/**
* Clean up the_excerpt()
*/
function excerpt_more() {
return ' … <a href="' . get_permalink() . '">' . __('Continued', 'sage') . '</a>';
}
add_filter('excerpt_more', __NAMESPACE__ . '\\excerpt_more');
| <?php
namespace Roots\Sage\Extras;
use Roots\Sage\Config;
/**
* Add <body> classes
*/
function body_class($classes) {
// Add page slug if it doesn't exist
if (is_single() || is_page() && !is_front_page()) {
if (!in_array(basename(get_permalink()), $classes)) {
$classes[] = basename(get_permalink());
}
}
// Add class if sidebar is active
if (Config\display_sidebar()) {
$classes[] = 'sidebar-primary';
}
return $classes;
}
add_filter('body_class', __NAMESPACE__ . '\\body_class');
/**
* Clean up the_excerpt()
*/
function excerpt_more() {
return ' … <a href="' . get_permalink() . '">' . __('Continued', 'sage') . '</a>';
}
add_filter('excerpt_more', __NAMESPACE__ . '\\excerpt_more');
// stop WordPress from adding p tags to things
remove_filter ('the_content', 'wpautop');
remove_filter ('comment_text', 'wpautop');
|
Fix methods not using separator property | function CaseSeparated(separator) {
Object.defineProperty(this, "separator", {
value: separator,
enumerable: true,
configurable: false
});
}
CaseSeparated.prototype.parse = function(val) {
if(typeof(val) === "undefined" || val === null) {
return [];
}
return String(val).split(this.separator);
};
CaseSeparated.prototype.stringify = function(val) {
if(typeof(val) === "undefined" || val === null) {
return "";
}
if(Array.isArray(val)) {
return val.map(this.stringify).join(this.separator);
}
return String(val);
};
module.exports = CaseSeparated;
| function CaseSeparated(separator) {
Object.defineProperty(this, {
separator: {
value: separator,
enumerable: true,
configurable: false
}
});
}
CaseSeparated.prototype.parse = function(val, separator) {
if(typeof(val) === "undefined" || val === null) {
return [];
}
return String(val).split(separator);
};
CaseSeparated.prototype.stringify = function(val, separator) {
if(typeof(val) === "undefined" || val === null) {
return "";
}
if(Array.isArray(val)) {
return val.map(this.stringify).join(separator);
}
return String(val);
};
module.exports = CaseSeparated;
|
Add count query to base model | <?php
/**
* Basis for ORM classes
*/
abstract class BaseModel{
abstract static function displayName(): string;
static function displayNamePlural(): string{
return static::displayName().'s';
}
static function name(): string{
return strtolower(static::displayName());
}
static function slug(): string{
return preg_replace('/\\s+/', '-', strtolower(static::displayNamePlural()));
}
static function dbTableName(): string{
return 'quotes_'.preg_replace('/\\s/', '', strtolower(static::displayName()));
}
static function countQuery(): string{
return 'SELECT count(*) as count FROM '.static::dbTableName();
}
static function indexQuery(int $offset=-1): string{
$baseQuery = static::indexSelectQuery();
$query = $baseQuery;
if($offset >= 0){
$columnOffset = $offset * self::indexPageOffset();
$query = $baseQuery.' LIMIT '.self::indexPageOffset().' OFFSET '.$columnOffset;
}
return $query;
}
protected abstract static function indexSelectQuery(): string;
static function selectOneQuery(): string{
return '';
}
static function insertQuery(): string{
return '';
}
static function updateQuery(): string{
return '';
}
static function deleteQuery(): string{
return 'DELETE FROM '.static::dbTableName().' WHERE id=?';
}
abstract static function toString(array $model): string;
static function indexPageOffset(): int{
return 100;
}
} | <?php
/**
* Basis for ORM classes
*/
abstract class BaseModel{
abstract static function displayName(): string;
static function displayNamePlural(): string{
return static::displayName().'s';
}
static function name(): string{
return strtolower(static::displayName());
}
static function slug(): string{
return preg_replace('/\\s+/', '-', strtolower(static::displayNamePlural()));
}
static function dbTableName(): string{
return 'quotes_'.preg_replace('/\\s/', '', strtolower(static::displayName()));
}
static function indexQuery(int $offset=-1): string{
$baseQuery = static::indexSelectQuery();
$query = $baseQuery;
if($offset >= 0){
$columnOffset = $offset * self::indexPageOffset();
$query = $baseQuery.' LIMIT '.self::indexPageOffset().' OFFSET '.$columnOffset;
}
return $query;
}
protected abstract static function indexSelectQuery(): string;
static function selectOneQuery(): string{
return '';
}
static function insertQuery(): string{
return '';
}
static function updateQuery(): string{
return '';
}
static function deleteQuery(): string{
return 'DELETE FROM '.static::dbTableName().' WHERE id=?';
}
abstract static function toString(array $model): string;
static function indexPageOffset(): int{
return 100;
}
} |
Fix the cli batch processing yield | 'use strict';
var co6 = require('co6');
var fs = co6.promisifyAll(require('fs'));
var os = require('os');
var parse = require('./parse');
var server = require('../server');
/*
* Run the command line application.
*/
co6.main(function *() {
var options = parse(process.argv);
var source = options.source || 'MangaRack.txt';
var tasks = options.args.length ? args(options) : yield batch(source);
yield server(tasks, options.workers || os.cpus().length, console.log);
console.log('Completed!');
});
/**
* Process the arguments.
* @param {!Options} options
* @return {!Array.<!{address: string, !Options}>}
*/
function args(options) {
var tasks = [];
options.args.forEach(function (address) {
tasks.push({address: address, options: options});
});
console.log('meh');
return tasks;
}
/**
* Process the batch file.
* @param {string} path
* @return {!Array.<!{address: string, !Options}>}
*/
function *batch(path) {
var tasks = [];
if (!(yield fs.existsAsync(path))) return tasks;
(yield fs.readFileAsync(path, 'utf8')).split('\n').forEach(function (n) {
var lineOptions = parse(n.split(' '));
lineOptions.args.forEach(function (address) {
tasks.push({address: address, options: lineOptions});
});
});
return tasks;
}
| 'use strict';
var co6 = require('co6');
var fs = co6.promisifyAll(require('fs'));
var os = require('os');
var parse = require('./parse');
var server = require('../server');
/*
* Run the command line application.
*/
co6.main(function *() {
var options = parse(process.argv);
var source = options.source || 'MangaRack.txt';
var tasks = options.args.length ? args(options) : yield batch(source);
yield server(tasks, options.workers || os.cpus().length, console.log);
console.log('Completed!');
});
/**
* Process the arguments.
* @param {!Options} options
* @return {!Array.<!{address: string, !Options}>}
*/
function args(options) {
var tasks = [];
options.args.forEach(function (address) {
tasks.push({address: address, options: options});
});
console.log('meh');
return tasks;
}
/**
* Process the batch file.
* @param {string} filePath
* @return {!Array.<!{address: string, !Options}>}
*/
function *batch(filePath) {
var tasks = [];
if (!(yield fs.existsAsync(filePath))) return tasks;
yield fs.readFileAsync(filePath, 'utf8').split('\n').forEach(function (n) {
var lineOptions = parse(n.split(' '));
lineOptions.args.forEach(function (address) {
tasks.push({address: address, options: lineOptions});
});
});
return tasks;
}
|
Set a 1hr timeout for the update job | import sys
import time
import logging
logging.basicConfig(level=logging.DEBUG)
from redis import StrictRedis
from rq import Queue
from apscheduler.schedulers.blocking import BlockingScheduler
from d1lod import jobs
conn = StrictRedis(host='redis', port='6379')
q = Queue(connection=conn)
sched = BlockingScheduler()
@sched.scheduled_job('interval', minutes=1)
def queue_update_job():
q.enqueue(jobs.update_graph, timeout=3600) # 1hr timeout
@sched.scheduled_job('interval', minutes=1)
def queue_stats_job():
q.enqueue(jobs.calculate_stats)
@sched.scheduled_job('interval', minutes=1)
def queue_export_job():
q.enqueue(jobs.export_graph)
@sched.scheduled_job('interval', minutes=1)
def print_jobs_job():
sched.print_jobs()
# Wait a bit for Sesame to start
time.sleep(10)
# Queue the stats job first. This creates the repository before any other
# jobs are run.
q.enqueue(jobs.calculate_stats)
# Start the scheduler
sched.start()
| import sys
import time
import logging
logging.basicConfig(level=logging.DEBUG)
from redis import StrictRedis
from rq import Queue
from apscheduler.schedulers.blocking import BlockingScheduler
from d1lod import jobs
conn = StrictRedis(host='redis', port='6379')
q = Queue(connection=conn)
sched = BlockingScheduler()
@sched.scheduled_job('interval', minutes=1)
def queue_update_job():
q.enqueue(jobs.update_graph)
@sched.scheduled_job('interval', minutes=1)
def queue_stats_job():
q.enqueue(jobs.calculate_stats)
@sched.scheduled_job('interval', minutes=1)
def queue_export_job():
q.enqueue(jobs.export_graph)
@sched.scheduled_job('interval', minutes=1)
def print_jobs_job():
sched.print_jobs()
# Wait a bit for Sesame to start
time.sleep(10)
# Queue the stats job first. This creates the repository before any other
# jobs are run.
q.enqueue(jobs.calculate_stats)
# Start the scheduler
sched.start()
|
Move package spork/life to github.com/redforks/life | package main
import (
"fmt"
"net"
"os"
"sync"
"time"
)
var (
host string // The host address to scan
)
func init() {
if len(os.Args) != 2 {
fmt.Fprintf(os.Stderr, "Usage: %s host\n", os.Args[0])
os.Exit(1)
}
host = os.Args[1]
}
func main() {
d := net.Dialer{Timeout: 2 * time.Second}
p := make(chan struct{}, 500) // make 500 parallel connection
wg := sync.WaitGroup{}
c := func(port int) {
conn, err := d.Dial(`tcp`, fmt.Sprintf(`%s:%d`, host, port))
if err == nil {
conn.Close()
fmt.Printf("%d passed\n", port)
}
<-p
wg.Done()
}
wg.Add(65536)
for i := 0; i < 65536; i++ {
p <- struct{}{}
go c(i)
}
wg.Wait()
}
| package main
import (
"fmt"
"net"
"os"
"sync"
"time"
)
var (
host string // The host address to scan
)
func init() {
if len(os.Args) != 2 {
fmt.Fprintf(os.Stderr, "Usage: %s host\n", os.Args[0])
os.Exit(1)
}
host = os.Args[1]
}
func main() {
d := net.Dialer{Timeout: 10 * time.Second}
p := make(chan struct{}, 500) // make 500 parallel connection
wg := sync.WaitGroup{}
c := func(port int) {
conn, err := d.Dial(`tcp`, fmt.Sprintf(`%s:%d`, host, port))
if err == nil {
conn.Close()
fmt.Printf("%d passed\n", port)
}
<-p
wg.Done()
}
wg.Add(65536)
for i := 0; i < 65536; i++ {
p <- struct{}{}
go c(i)
}
wg.Wait()
}
|
Correct tests for PHP < 5.6 | <?php
/*
+--------------------------------------------------------------------------+
| Zephir |
| Copyright (c) 2013-present Zephir Team (https://zephir-lang.com/) |
| |
| This source file is subject the MIT license, that is bundled with this |
| package in the file LICENSE, and is available through the world-wide-web |
| at the following url: http://zephir-lang.com/license.html |
+--------------------------------------------------------------------------+
*/
namespace Extension\Oo\Scope;
use PHPUnit\Framework\TestCase;
use Test\Oo\Scopes\PrivateScopeTester;
class PrivateScopeTest extends TestCase
{
/** @test */
public function shouldCallPrivateMethod()
{
if (PHP_VERSION_ID < 50600) {
$this->markTestSkipped(
"Calling parent's private methods from the child's public ones doesn't provided for PHP < 5.6"
);
}
$this->assertSame('isPrivate', (new PrivateScopeTester())->run());
}
}
| <?php
/*
+--------------------------------------------------------------------------+
| Zephir |
| Copyright (c) 2013-present Zephir Team (https://zephir-lang.com/) |
| |
| This source file is subject the MIT license, that is bundled with this |
| package in the file LICENSE, and is available through the world-wide-web |
| at the following url: http://zephir-lang.com/license.html |
+--------------------------------------------------------------------------+
*/
namespace Extension\Oo\Scope;
use PHPUnit\Framework\TestCase;
use Test\Oo\Scopes\PrivateScopeTester;
class PrivateScopeTest extends TestCase
{
/** @test */
public function shouldCallPrivateMethod()
{
$this->assertSame('isPrivate', (new PrivateScopeTester())->run());
}
}
|
Hide wtfnode from browserify etc.
This reduces the browserified size by ~1MB (i.e. 99%) | 'use strict'
var IS_BROWSER = require('is-browser');
if (!IS_BROWSER) {
var r = require;
var wtfnode = (r)('wtfnode');
}
var Suite = require('./lib/suite');
var defaultSuite = new Suite();
defaultSuite.addLogging();
defaultSuite.addExit();
var runTriggered = false;
function it(name, fn, options) {
defaultSuite.addTest(name, fn, options);
if (!runTriggered) {
runTriggered = true;
setTimeout(function () {
defaultSuite.run().done(function () {
if (!IS_BROWSER) {
setTimeout(function () {
wtfnode.dump();
}, 5000).unref()
}
});
}, 0);
}
}
function run(fn, options) {
defaultSuite.addCode(fn, options);
}
module.exports = it
module.exports.run = run;
module.exports.disableColors = defaultSuite.disableColors.bind(defaultSuite);
module.exports.on = defaultSuite.on.bind(defaultSuite);
module.exports.Suite = Suite;
| 'use strict'
var IS_BROWSER = require('is-browser');
if (!IS_BROWSER) {
var wtfnode = require('wtfnode');
}
var Suite = require('./lib/suite');
var defaultSuite = new Suite();
defaultSuite.addLogging();
defaultSuite.addExit();
var runTriggered = false;
function it(name, fn, options) {
defaultSuite.addTest(name, fn, options);
if (!runTriggered) {
runTriggered = true;
setTimeout(function () {
defaultSuite.run().done(function () {
if (!IS_BROWSER) {
setTimeout(function () {
wtfnode.dump();
}, 5000).unref()
}
});
}, 0);
}
}
function run(fn, options) {
defaultSuite.addCode(fn, options);
}
module.exports = it
module.exports.run = run;
module.exports.disableColors = defaultSuite.disableColors.bind(defaultSuite);
module.exports.on = defaultSuite.on.bind(defaultSuite);
module.exports.Suite = Suite;
|
Add ping to keep connection alive | var fs = require('fs');
var path = require('path');
var xec = require('xbmc-event-client');
var keyboard = require('./lib/keyboard');
var kodikeys = function(opt) {
var defaults = {
port: 9777
}
opt = Object.assign({}, defaults, opt);
var kodi = new xec.XBMCEventClient('kodikeys', opt)
kodi.connect(function(errors, bytes) {
if (errors.length) {
console.error(`Connection failed to Kodi on $(opt.host), port ${opt.port}`)
console.error(errors[0].toString());
process.exit(1);
}
// init keyboard interactivity
keyboard.init(kodi);
// ping to keep connection alive
setInterval(kodi.ping.bind(kodi), 55 * 1000);
console.log(`connected to ${opt.host} port ${opt.port}`);
});
}
module.exports = kodikeys;
| var fs = require('fs');
var path = require('path');
var xec = require('xbmc-event-client');
var keyboard = require('./lib/keyboard');
var kodikeys = function(opt) {
var defaults = {
port: 9777
}
opt = Object.assign({}, defaults, opt);
var kodi = new xec.XBMCEventClient('kodikeys', opt)
kodi.connect(function(errors, bytes) {
if (errors.length) {
console.error(`Connection failed to Kodi on $(opt.host), port ${opt.port}`)
console.error(errors[0].toString());
process.exit(1);
}
// init keyboard interactivity
keyboard.init(kodi);
console.log(`connected to ${opt.host} port ${opt.port}`);
});
}
module.exports = kodikeys;
|
Change expected scan prop type to number | import React, {PropTypes} from 'react'
import {List, ListItem} from 'material-ui/List';
import Divider from 'material-ui/Divider';
const StatusListItem = props => {
let memberCount = props.teams.map(team => team.members.length).reduce((a, b) => a + b, 0)
let teamCount = props.teams.length
return (
<div>
<Divider/>
<ListItem
onClick={() => props.onClick()}
primaryText={props.name}
secondaryText={
<div>
Teams: {teamCount}
<br/>
Members: {memberCount}
</div>
}
secondaryTextLines={2}
rightAvatar= {
<div>
{props.scans}
</div>
}
/>
</div>
)
}
StatusListItem.propTypes = {
members: React.PropTypes.array,
name: React.PropTypes.string,
scans: React.PropTypes.number,
onClick: React.PropTypes.func
}
export default StatusListItem | import React, {PropTypes} from 'react'
import {List, ListItem} from 'material-ui/List';
import Divider from 'material-ui/Divider';
const StatusListItem = props => {
let memberCount = props.teams.map(team => team.members.length).reduce((a, b) => a + b, 0)
let teamCount = props.teams.length
return (
<div>
<Divider/>
<ListItem
onClick={() => props.onClick()}
primaryText={props.name}
secondaryText={
<div>
Teams: {teamCount}
<br/>
Members: {memberCount}
</div>
}
secondaryTextLines={2}
rightAvatar= {
<div>
{props.scans}
</div>
}
/>
</div>
)
}
StatusListItem.propTypes = {
members: React.PropTypes.array,
name: React.PropTypes.string,
scans: React.PropTypes.string,
onClick: React.PropTypes.func
}
export default StatusListItem |
Add support for notation images. | package org.openhealthtools.mdht.uml.hdf.ui.util;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExecutableExtension;
import org.eclipse.uml2.uml.Element;
import org.eclipse.uml2.uml.Property;
import org.openhealthtools.mdht.uml.common.notation.INotationProvider;
public class HDFAnnotationProvider implements INotationProvider, IExecutableExtension {
public final static int HL7_PROPERTY_ANNOTATION = IHL7Appearance.DISP_VOCABULARY | IHL7Appearance.DISP_UPDATE_MODE;
public String getPrintString(Element element) {
String printString = null;
if (element instanceof Property) {
printString = HDFPropertyNotation.getCustomLabel((Property)element, IHL7Appearance.DEFAULT_HL7_PROPERTY);
}
return printString;
}
public String getAnnotation(Element element) {
String annotation = null;
if (element instanceof Property) {
annotation = HDFPropertyNotation.getCustomLabel((Property)element, HL7_PROPERTY_ANNOTATION);
}
return annotation;
}
public Object getElementImage(Element element) {
return null;
}
public Object getAnnotationImage(Element element) {
return null;
}
public void setInitializationData(IConfigurationElement config, String propertyName, Object data)
throws CoreException {
// do nothing
}
}
| package org.openhealthtools.mdht.uml.hdf.ui.util;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExecutableExtension;
import org.eclipse.uml2.uml.Element;
import org.eclipse.uml2.uml.Property;
import org.openhealthtools.mdht.uml.common.notation.INotationProvider;
public class HDFAnnotationProvider implements INotationProvider, IExecutableExtension {
public final static int HL7_PROPERTY_ANNOTATION = IHL7Appearance.DISP_VOCABULARY | IHL7Appearance.DISP_UPDATE_MODE;
public String getPrintString(Element element) {
String printString = null;
if (element instanceof Property) {
printString = HDFPropertyNotation.getCustomLabel((Property)element, IHL7Appearance.DEFAULT_HL7_PROPERTY);
}
return printString;
}
public String getAnnotation(Element element) {
String annotation = null;
if (element instanceof Property) {
annotation = HDFPropertyNotation.getCustomLabel((Property)element, HL7_PROPERTY_ANNOTATION);
}
return annotation;
}
public void setInitializationData(IConfigurationElement config, String propertyName, Object data)
throws CoreException {
// do nothing
}
}
|
Fix test failures by restoring working directory in fixtures. | import os
import pytest
from hgtools import managers
def _ensure_present(mgr):
try:
mgr.version()
except Exception:
pytest.skip()
@pytest.fixture
def tmpdir_as_cwd(tmpdir):
with tmpdir.as_cwd():
yield tmpdir
@pytest.fixture
def hg_repo(tmpdir_as_cwd):
mgr = managers.MercurialManager()
_ensure_present(mgr)
mgr._invoke('init', '.')
os.makedirs('bar')
touch('bar/baz')
mgr._invoke('addremove')
mgr._invoke('ci', '-m', 'committed')
with open('bar/baz', 'w') as baz:
baz.write('content')
mgr._invoke('ci', '-m', 'added content')
return tmpdir_as_cwd
@pytest.fixture
def git_repo(tmpdir_as_cwd):
mgr = managers.GitManager()
_ensure_present(mgr)
mgr._invoke('init')
mgr._invoke('config', 'user.email', 'hgtools@example.com')
mgr._invoke('config', 'user.name', 'HGTools')
os.makedirs('bar')
touch('bar/baz')
mgr._invoke('add', '.')
mgr._invoke('commit', '-m', 'committed')
with open('bar/baz', 'w') as baz:
baz.write('content')
mgr._invoke('commit', '-am', 'added content')
return tmpdir_as_cwd
def touch(filename):
with open(filename, 'a'):
pass
| import os
import pytest
from hgtools import managers
def _ensure_present(mgr):
try:
mgr.version()
except Exception:
pytest.skip()
@pytest.fixture
def hg_repo(tmpdir):
tmpdir.chdir()
mgr = managers.MercurialManager()
_ensure_present(mgr)
mgr._invoke('init', '.')
os.makedirs('bar')
touch('bar/baz')
mgr._invoke('addremove')
mgr._invoke('ci', '-m', 'committed')
with open('bar/baz', 'w') as baz:
baz.write('content')
mgr._invoke('ci', '-m', 'added content')
return tmpdir
@pytest.fixture
def git_repo(tmpdir):
tmpdir.chdir()
mgr = managers.GitManager()
_ensure_present(mgr)
mgr._invoke('init')
mgr._invoke('config', 'user.email', 'hgtools@example.com')
mgr._invoke('config', 'user.name', 'HGTools')
os.makedirs('bar')
touch('bar/baz')
mgr._invoke('add', '.')
mgr._invoke('commit', '-m', 'committed')
with open('bar/baz', 'w') as baz:
baz.write('content')
mgr._invoke('commit', '-am', 'added content')
return tmpdir
def touch(filename):
with open(filename, 'a'):
pass
|
Move from /~username/ to /user/username/ | # Copyright 2013 Donald Stufft
#
# 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.
from __future__ import absolute_import, division, print_function
from __future__ import unicode_literals
from werkzeug.routing import Rule, EndpointPrefix
urls = [
EndpointPrefix("warehouse.accounts.views.", [
Rule(
"/user/<username>/",
methods=["GET"],
endpoint="user_profile",
),
]),
]
| # Copyright 2013 Donald Stufft
#
# 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.
from __future__ import absolute_import, division, print_function
from __future__ import unicode_literals
from werkzeug.routing import Rule, EndpointPrefix
urls = [
EndpointPrefix("warehouse.accounts.views.", [
Rule(
"/~<username>/",
methods=["GET"],
endpoint="user_profile",
),
]),
]
|
Switch to template literals for the help screen. | #!/usr/bin/env node
'use strict';
const fs = require('fs');
const minimist = require('minimist');
const pkg = require('./package.json');
const oust = require('.');
const argv = minimist(process.argv.slice(2));
function printHelp() {
console.log(`
${pkg.description}
Usage:
$ oust <filename> <type>
Example:
$ oust index.html scripts`);
}
if (argv.v || argv.version) {
console.log(pkg.version);
process.exit(0);
}
if (argv.h || argv.help || argv._.length === 0) {
printHelp();
process.exit(0);
}
const file = argv._[0];
const type = argv._[1];
fs.readFile(file, (err, data) => {
if (err) {
console.error('Error opening file:', err.message);
process.exit(1);
}
console.log(oust(data, type).join('\n'));
});
| #!/usr/bin/env node
'use strict';
const fs = require('fs');
const minimist = require('minimist');
const pkg = require('./package.json');
const oust = require('.');
const argv = minimist(process.argv.slice(2));
function printHelp() {
console.log([
pkg.description,
'',
'Usage',
' $ oust <filename> <type>',
'',
'Example',
' $ oust index.html scripts'
].join('\n'));
}
if (argv.v || argv.version) {
console.log(pkg.version);
process.exit(0);
}
if (argv.h || argv.help || argv._.length === 0) {
printHelp();
process.exit(0);
}
const file = argv._[0];
const type = argv._[1];
fs.readFile(file, (err, data) => {
if (err) {
console.error('Error opening file:', err.message);
process.exit(1);
}
console.log(oust(data, type).join('\n'));
});
|
Add EntryTagsSerializer for returning tags of an Entry | # -*- coding: utf-8 -*-
#
# (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
#
# See LICENSE comming with the source of 'trex' for details.
#
from rest_framework.serializers import (
HyperlinkedModelSerializer, HyperlinkedIdentityField,
)
from trex.models.project import Project, Entry, Tag
class ProjectSerializer(HyperlinkedModelSerializer):
class Meta:
model = Project
fields = ("url", "id", "name", "description", "active", "created")
class ProjectDetailSerializer(HyperlinkedModelSerializer):
entries = HyperlinkedIdentityField(view_name="project-entries-list")
class Meta:
model = Project
fields = ("id", "name", "description", "active", "created", "entries")
class EntryTagsSerializer(HyperlinkedModelSerializer):
class Meta:
model = Tag
fields = ("url", "id", "name")
class EntryProjectSerializer(HyperlinkedModelSerializer):
class Meta:
model = Project
fields = ("url", "id", "name")
class EntryDetailSerializer(HyperlinkedModelSerializer):
tags = EntryTagsSerializer(many=True)
project = EntryProjectSerializer()
class Meta:
model = Entry
fields = ("url", "id", "date", "duration", "description", "state",
"user_abbr", "user", "created", "project", "tags")
| # -*- coding: utf-8 -*-
#
# (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
#
# See LICENSE comming with the source of 'trex' for details.
#
from rest_framework.serializers import (
HyperlinkedModelSerializer, HyperlinkedIdentityField,
)
from trex.models.project import Project, Entry
class ProjectSerializer(HyperlinkedModelSerializer):
class Meta:
model = Project
fields = ("url", "id", "name", "description", "active", "created")
class ProjectDetailSerializer(HyperlinkedModelSerializer):
entries = HyperlinkedIdentityField(view_name="project-entries-list")
class Meta:
model = Project
fields = ("id", "name", "description", "active", "created", "entries")
class EntryProjectSerializer(HyperlinkedModelSerializer):
class Meta:
model = Project
fields = ("url", "id", "name")
class EntryDetailSerializer(HyperlinkedModelSerializer):
project = EntryProjectSerializer()
class Meta:
model = Entry
fields = ("url", "id", "date", "duration", "description", "state",
"user_abbr", "user", "created", "project")
|
Install the plotting template, too. | #!/usr/bin/env python
from setuptools import setup
setup(
name='Lobster',
version='1.0',
description='Opportunistic HEP computing tool',
author='Anna Woodard, Matthias Wolf',
url='https://github.com/matz-e/lobster',
packages=['lobster', 'lobster.cmssw'],
package_data={'lobster': [
'cmssw/data/job.py',
'cmssw/data/wrapper.sh',
'cmssw/data/mtab',
'cmssw/data/siteconfig/JobConfig/site-local-config.xml',
'cmssw/data/siteconfig/PhEDEx/storage.xml',
'cmssw/data/template.html'
]},
install_requires=[
'argparse',
'jinja2',
'nose',
'pyyaml',
'python-daemon'
],
entry_points={
'console_scripts': ['lobster = lobster.ui:boil']
}
)
| #!/usr/bin/env python
from setuptools import setup
setup(
name='Lobster',
version='1.0',
description='Opportunistic HEP computing tool',
author='Anna Woodard, Matthias Wolf',
url='https://github.com/matz-e/lobster',
packages=['lobster', 'lobster.cmssw'],
package_data={'lobster': [
'cmssw/data/job.py',
'cmssw/data/wrapper.sh',
'cmssw/data/mtab',
'cmssw/data/siteconfig/JobConfig/site-local-config.xml',
'cmssw/data/siteconfig/PhEDEx/storage.xml'
]},
install_requires=[
'argparse',
'jinja2',
'nose',
'pyyaml',
'python-daemon'
],
entry_points={
'console_scripts': ['lobster = lobster.ui:boil']
}
)
|
Fix legend title to respond to legend padding changes. | import {GuideTitleStyle} from './constants';
import guideMark from './guide-mark';
import {lookup} from './guide-util';
import {TextMark} from '../marks/marktypes';
import {LegendTitleRole} from '../marks/roles';
import {addEncode, encoder} from '../encode/encode-util';
export default function(spec, config, userEncode, dataRef) {
var zero = {value: 0},
encode = {}, enter;
encode.enter = enter = {
x: {field: {group: 'padding'}},
y: {field: {group: 'padding'}},
opacity: zero
};
addEncode(enter, 'align', lookup('titleAlign', spec, config));
addEncode(enter, 'baseline', lookup('titleBaseline', spec, config));
addEncode(enter, 'fill', lookup('titleColor', spec, config));
addEncode(enter, 'font', lookup('titleFont', spec, config));
addEncode(enter, 'fontSize', lookup('titleFontSize', spec, config));
addEncode(enter, 'fontWeight', lookup('titleFontWeight', spec, config));
addEncode(enter, 'limit', lookup('titleLimit', spec, config));
encode.exit = {
opacity: zero
};
encode.update = {
x: {field: {group: 'padding'}},
y: {field: {group: 'padding'}},
opacity: {value: 1},
text: encoder(spec.title)
};
return guideMark(TextMark, LegendTitleRole, GuideTitleStyle, null, dataRef, encode, userEncode);
}
| import {GuideTitleStyle} from './constants';
import guideMark from './guide-mark';
import {lookup} from './guide-util';
import {TextMark} from '../marks/marktypes';
import {LegendTitleRole} from '../marks/roles';
import {addEncode, encoder} from '../encode/encode-util';
export default function(spec, config, userEncode, dataRef) {
var zero = {value: 0},
encode = {}, enter;
encode.enter = enter = {
x: {field: {group: 'padding'}},
y: {field: {group: 'padding'}},
opacity: zero
};
addEncode(enter, 'align', lookup('titleAlign', spec, config));
addEncode(enter, 'baseline', lookup('titleBaseline', spec, config));
addEncode(enter, 'fill', lookup('titleColor', spec, config));
addEncode(enter, 'font', lookup('titleFont', spec, config));
addEncode(enter, 'fontSize', lookup('titleFontSize', spec, config));
addEncode(enter, 'fontWeight', lookup('titleFontWeight', spec, config));
addEncode(enter, 'limit', lookup('titleLimit', spec, config));
encode.exit = {
opacity: zero
};
encode.update = {
opacity: {value: 1},
text: encoder(spec.title)
};
return guideMark(TextMark, LegendTitleRole, GuideTitleStyle, null, dataRef, encode, userEncode);
}
|
Add route for updating a post | package main
import (
"net/http"
)
type ResponseWriter interface {
Header() http.Header
Write([]byte) (int, error)
WriteHeader(int)
}
type Route struct {
Name string
Method string
Pattern string
HandlerFunc http.HandlerFunc
}
type Routes []Route
var routes = Routes{
Route{
"Index",
"GET",
"/",
Index,
},
Route{
"PostIndex",
"GET",
"/api/posts",
PostIndex,
},
Route{
"PostCreate",
"POST",
"/api/posts",
PostCreate,
},
Route{
"PostShow",
"GET",
"/api/posts/{postId}",
PostShow,
},
Route{
"PostUpdate",
"PUT",
"/api/posts/{postId}",
PostUpdate,
},
Route{
"PostDelete",
"DELETE",
"/api/posts/{postId}",
PostDelete,
},
}
| package main
import (
"net/http"
)
type ResponseWriter interface {
Header() http.Header
Write([]byte) (int, error)
WriteHeader(int)
}
type Route struct {
Name string
Method string
Pattern string
HandlerFunc http.HandlerFunc
}
type Routes []Route
var routes = Routes{
Route{
"Index",
"GET",
"/",
Index,
},
Route{
"PostIndex",
"GET",
"/api/posts",
PostIndex,
},
Route{
"PostCreate",
"POST",
"/api/posts",
PostCreate,
},
Route{
"PostShow",
"GET",
"/api/posts/{postId}",
PostShow,
},
Route{
"PostDelete",
"DELETE",
"/api/posts/{postId}",
PostDelete,
},
}
|
Send person data in the request. | define(["application"], function(App) {
App.EditProfileModalView = Ember.View.extend({
actions: {
save: function () {
var person = this.get('controller.person')
, personData = this.get('controller.personData')
, newProperties = personData.getProperties([
'name', 'title', 'bio', 'website', 'github', 'twitter'
]);
/* Hide modal. */
this.$('#edit_profile_modal').modal('hide');
$.ajax({
url: App.API_BASE_URL + '/profile',
type: 'put',
data: {
person: personData.getProperties('name', 'title', 'twitter', 'github', 'website', 'bio')
}
});
/* Save profile changes. */
person.setProperties(newProperties);
}
},
templateName: 'views/edit_profile_modal'
});
});
| define(["application"], function(App) {
App.EditProfileModalView = Ember.View.extend({
actions: {
save: function () {
var person = this.get('controller.person')
, personData = this.get('controller.personData')
, newProperties = personData.getProperties([
'name', 'title', 'bio', 'website', 'github', 'twitter'
]);
/* Hide modal. */
this.$('#edit_profile_modal').modal('hide');
$.ajax({
url: App.API_BASE_URL + '/profile',
type: 'put',
data: {
person: {
}
}
});
/* Save profile changes. */
person.setProperties(newProperties);
}
},
templateName: 'views/edit_profile_modal'
});
}); |
[Tests] Remove safe_twig test missed in rebase | <?php
namespace Bolt\Tests\Provider;
use Bolt\Tests\BoltUnitTest;
use Bolt\Twig\Extension\BoltExtension;
use Twig_Environment as Environment;
/**
* @covers \Bolt\Provider\TwigServiceProvider
*
* @author Ross Riley <riley.ross@gmail.com>
* @author Carson Full <carsonfull@gmail.com>
*
* @covers \Bolt\Provider\TwigServiceProvider
*/
class TwigServiceProviderTest extends BoltUnitTest
{
public function testProvider()
{
$app = $this->getApp();
$this->assertNotEmpty($app['twig.options']['cache'], 'Cache path was not set');
$this->assertInstanceOf(Environment::class, $app['twig']);
$this->assertTrue($app['twig']->hasExtension(BoltExtension::class), 'Bolt\Twig\Extension\BoltExtension was not added to twig environment');
$this->assertContains('bolt', $app['twig.loader.bolt_filesystem']->getNamespaces(), 'bolt namespace was not added to filesystem loader');
}
public function testConfigCacheDisabled()
{
$app = $this->getApp(false);
$app['config']->set('general/caching/templates', false);
$this->assertArrayNotHasKey('cache', $app['twig.options']);
}
}
| <?php
namespace Bolt\Tests\Provider;
use Bolt\Tests\BoltUnitTest;
use Bolt\Twig\Extension\BoltExtension;
use Bolt\Twig\SafeEnvironment;
use Twig_Environment as Environment;
/**
* @covers \Bolt\Provider\TwigServiceProvider
*
* @author Ross Riley <riley.ross@gmail.com>
* @author Carson Full <carsonfull@gmail.com>
*
* @covers \Bolt\Provider\TwigServiceProvider
*/
class TwigServiceProviderTest extends BoltUnitTest
{
public function testProvider()
{
$app = $this->getApp();
$this->assertNotEmpty($app['twig.options']['cache'], 'Cache path was not set');
$this->assertInstanceOf(Environment::class, $app['twig']);
$this->assertTrue($app['twig']->hasExtension(BoltExtension::class), 'Bolt\Twig\Extension\BoltExtension was not added to twig environment');
$this->assertContains('bolt', $app['twig.loader.bolt_filesystem']->getNamespaces(), 'bolt namespace was not added to filesystem loader');
}
public function testLegacyProvider()
{
$app = $this->getApp();
$this->assertInstanceOf(SafeEnvironment::class, $app['safe_twig']);
}
public function testConfigCacheDisabled()
{
$app = $this->getApp(false);
$app['config']->set('general/caching/templates', false);
$this->assertArrayNotHasKey('cache', $app['twig.options']);
}
}
|
Change the xml parser to output gas mixture content | #! /usr/bin/python
import argparse
from xml.dom import minidom
O2=21
H2=0
parser = argparse.ArgumentParser(description='Parse a dive in xml formt.')
parser.add_argument('-f', '--file', required=True,
dest='path', help='path to xml file')
args = parser.parse_args()
path = args.path
doc = minidom.parse(path)
gas = doc.getElementsByTagName('DiveMixture')
for subNode in gas.item(0).childNodes:
if (subNode.nodeName == "Oxygen"):
O2=float(subNode.childNodes[0].nodeValue)
if (subNode.nodeName == "Helium"):
H2=float(subNode.childNodes[0].nodeValue)
nodes = doc.getElementsByTagName('Dive.Sample')
for node in nodes:
if node.hasChildNodes() and len(node.childNodes) > 8:
for subNode in node.childNodes:
if (subNode.nodeName == "Depth" and subNode.hasChildNodes()):
depth = (float(subNode.childNodes[0].nodeValue) / 10) + 1
if (subNode.nodeName == "Time" and subNode.hasChildNodes()):
time = float(subNode.childNodes[0].nodeValue) / 60
print ("%.2f %.2f %.2f %.2f" % (time , depth, O2, H2))
| #! /usr/bin/python
import argparse
from xml.dom import minidom
parser = argparse.ArgumentParser(description='Parse a dive in xml formt.')
parser.add_argument('-f', '--file', required=True,
dest='path', help='path to xml file')
args = parser.parse_args()
path = args.path
doc = minidom.parse(path)
nodes = doc.getElementsByTagName('Dive.Sample')
for node in nodes:
if node.hasChildNodes() and len(node.childNodes) > 8:
for subNode in node.childNodes:
if (subNode.nodeName == "Depth" and subNode.hasChildNodes()):
depth = (float(subNode.childNodes[0].nodeValue) / 10) + 1
if (subNode.nodeName == "Time" and subNode.hasChildNodes()):
time = float(subNode.childNodes[0].nodeValue) / 60
print ("%.2f %.2f" % (time , depth))
|
Change clickableimage to allow it to take styles when a new component is called elsewhere | import React, { Component } from 'react';
import { TouchableOpacity, Image, View } from 'react-native';
// import styles from './styles/ClickableImageStyle';
import PropTypes from 'prop-types';
import { StackNagivator } from 'react-navigation';
import FadeInView from '../animations/FadeInView';
export default class ClickableImage extends Component {
static propTypes = {
onPress: PropTypes.func,
text: PropTypes.object,
children: PropTypes.object,
navigation: PropTypes.object,
imageStyle: Image.propTypes.style,
touchStyle: View.propTypes.style
}
render() {
return (
<View>
<FadeInView>
<TouchableOpacity style={this.props.touchStyle} activeOpacity={.85} onPress={this.props.onPress}>
<Image style={this.props.imageStyle} source={this.props.text} />
</TouchableOpacity>
</FadeInView>
</View>
)
}
}
| import React, { Component } from 'react';
import { TouchableOpacity, Image, View } from 'react-native';
import styles from './styles/ClickableImageStyle';
import PropTypes from 'prop-types';
import { StackNagivator } from 'react-navigation';
import FadeInView from '../animations/FadeInView';
export default class ClickableImage extends Component {
static propTypes = {
onPress: PropTypes.func,
text: PropTypes.object,
children: PropTypes.object,
navigation: PropTypes.object
}
render() {
return (
<View>
<FadeInView>
<TouchableOpacity style={styles.touchableSize} activeOpacity={.85} onPress={this.props.onPress}>
<Image style={styles.image} source={this.props.text} />
</TouchableOpacity>
</FadeInView>
</View>
)
}
} |
Add *all* matching names from unicode directory to names catalog | <?php
# find all input images
$files1 = glob(dirname(__FILE__).'/../gemoji/images/emoji/*.png');
$files2 = glob(dirname(__FILE__).'/../gemoji/images/emoji/unicode/*.png');
echo "Calculating checksums ... ";
$map = array();
foreach ($files2 as $f) {
$sum = md5_file($f);
if (!isset($map[$sum])) {
$map[$sum] = array();
}
$map[$sum][] = $f;
}
echo "DONE\n";
echo "Matching up ............. ";
$out = array();
foreach ($files1 as $f){
$sum = md5_file($f);
$n_text = pathinfo($f, PATHINFO_FILENAME);
if ($map[$sum]){
foreach ($map[$sum] as $map_file) {
$n_code = pathinfo($map_file, PATHINFO_FILENAME);
#echo "$n_text -> $n_code\n";
$out[$n_code][] = $n_text;
}
}else{
#echo "$n_text -> ???????????????????????????\n";
$out['_'][] = $n_text;
}
}
echo "DONE\n";
echo "Writing names map ....... ";
$fh = fopen('catalog_names.php', 'w');
fwrite($fh, '<'.'?php $catalog_names = ');
fwrite($fh, var_export($out, true));
fwrite($fh, ";\n");
fclose($fh);
echo "DONE\n";
| <?php
# find all input images
$files1 = glob(dirname(__FILE__).'/../gemoji/images/emoji/*.png');
$files2 = glob(dirname(__FILE__).'/../gemoji/images/emoji/unicode/*.png');
echo "Calculating checksums ... ";
$map = array();
foreach ($files2 as $f) $map[md5_file($f)] = $f;
echo "DONE\n";
echo "Matching up ............. ";
$out = array();
foreach ($files1 as $f){
$sum = md5_file($f);
$n_text = pathinfo($f, PATHINFO_FILENAME);
if ($map[$sum]){
$n_code = pathinfo($map[$sum], PATHINFO_FILENAME);
#echo "$n_text -> $n_code\n";
$out[$n_code][] = $n_text;
}else{
#echo "$n_text -> ???????????????????????????\n";
$out['_'][] = $n_text;
}
}
echo "DONE\n";
echo "Writing names map ....... ";
$fh = fopen('catalog_names.php', 'w');
fwrite($fh, '<'.'?php $catalog_names = ');
fwrite($fh, var_export($out, true));
fwrite($fh, ";\n");
fclose($fh);
echo "DONE\n";
|
Remove comment to see outputs works in godoc | package fnlog_test
import (
"github.com/northbright/fnlog"
"log"
)
var (
noTagLog *log.Logger
)
func Example() {
iLog := fnlog.New("i")
wLog := fnlog.New("w")
eLog := fnlog.New("e")
noTagLog = fnlog.New("")
iLog.Printf("print infos")
wLog.Printf("print warnnings")
eLog.Printf("print errors")
noTagLog.Printf("print messages without tag")
// Output:
// 2015/06/09 14:32:59 unit_test.go:14 fnlog_test.Example(): i: print infos
// 2015/06/09 14:32:59 unit_test.go:15 fnlog_test.Example(): w: print warnnings
// 2015/06/09 14:32:59 unit_test.go:16 fnlog_test.Example(): e: print errors
// 2015/06/09 14:32:59 unit_test.go:17 fnlog_test.Example(): print messages without tag
}
| package fnlog_test
import (
"github.com/northbright/fnlog"
"log"
)
var (
noTagLog *log.Logger
)
func Example() {
iLog := fnlog.New("i")
wLog := fnlog.New("w")
eLog := fnlog.New("e")
// Global *log.Logger
noTagLog = fnlog.New("")
iLog.Printf("print infos")
wLog.Printf("print warnnings")
eLog.Printf("print errors")
noTagLog.Printf("print messages without tag")
// Output:
// 2015/06/09 14:32:59 unit_test.go:14 fnlog_test.Example(): i: print infos
// 2015/06/09 14:32:59 unit_test.go:15 fnlog_test.Example(): w: print warnnings
// 2015/06/09 14:32:59 unit_test.go:16 fnlog_test.Example(): e: print errors
// 2015/06/09 14:32:59 unit_test.go:17 fnlog_test.Example(): print messages without tag
}
|
Add support converter configuration for database | /*
Copyright 2015-2017 Artem Stasiuk
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.github.terma.gigaspacewebconsole.provider.executor;
import com.github.terma.gigaspacewebconsole.core.config.ConfigLocator;
import com.github.terma.gigaspacewebconsole.provider.ConverterHelper;
import java.util.Collections;
public class DatabaseExecutor {
private static final ConnectionFactory connectionFactory = new DatabaseConnectionFactory();
private static final ConverterHelper converterHelper = new ConverterHelper(ConfigLocator.CONFIG.user.converters);
public static final Executor INSTANCE = new Executor(
connectionFactory,
new ZeroExecutorPreprocessor(),
Collections.<ExecutorPlugin>singletonList(new SqlOnJsonPlugin(connectionFactory, converterHelper)),
converterHelper);
}
| /*
Copyright 2015-2017 Artem Stasiuk
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.github.terma.gigaspacewebconsole.provider.executor;
import com.github.terma.gigaspacewebconsole.provider.ConverterHelper;
import java.util.ArrayList;
import java.util.Collections;
public class DatabaseExecutor {
private static final ConnectionFactory connectionFactory = new DatabaseConnectionFactory();
private static final ConverterHelper converterHelper = new ConverterHelper(new ArrayList<String>());
public static final Executor INSTANCE = new Executor(
connectionFactory,
new ZeroExecutorPreprocessor(),
Collections.<ExecutorPlugin>singletonList(new SqlOnJsonPlugin(connectionFactory, converterHelper)),
converterHelper);
}
|
Correct the windows path in test of Windows path translator | import unittest
from malcolm.modules.ADCore.infos import FilePathTranslatorInfo
class TestInfo(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_file_path_translator_drive_mount(self):
info = FilePathTranslatorInfo("C", "/foo", "")
part_info = {"WINPATH": [info]}
win_path = info.translate_filepath(part_info,
"/foo/directory/file:name.xml")
assert "C:\\directory\\file_name.xml" == win_path
def test_file_path_translator_network_mount(self):
info = FilePathTranslatorInfo("", "/foo", "//dc")
part_info = {"WINPATH": [info]}
win_path = info.translate_filepath(part_info, "/foo/directory")
assert "\\\\dc\\foo\\directory" == win_path
| import unittest
from malcolm.modules.ADCore.infos import FilePathTranslatorInfo
class TestInfo(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_file_path_translator_drive_mount(self):
info = FilePathTranslatorInfo("C", "/foo", "")
part_info = {"WINPATH": [info]}
win_path = info.translate_filepath(part_info,
"/foo/directory/file:name.xml")
assert "C:\\directory\file_name.xml" == win_path
def test_file_path_translator_network_mount(self):
info = FilePathTranslatorInfo("", "/foo", "//dc")
part_info = {"WINPATH": [info]}
win_path = info.translate_filepath(part_info, "/foo/directory")
assert "\\\\dc\\foo\\directory" == win_path
|
Fix typo; Fix request never finish | # coding: utf-8
import json
import tornado.ioloop
import tornado.web
import Adafruit_BMP.BMP085 as BMP085
class SensorAccess(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self):
self.write(json.dumps(self.read_sensor()))
self.finish()
def read_sensor(self):
pass
class TempSensorAccess(SensorAccess):
def read_sensor(self):
sensor = BMP085.BMP085(mode=BMP085.BMP085_ULTRAHIGHRES)
return {
'temperature': sensor.read_temperature(),
'pressure': sensor.read_pressure(),
}
class IndexHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self):
self.write(json.dumps({
'index': 'pitools service'
}))
self.finish()
def start_server():
application = tornado.web.Application([
(r"/", IndexHandler),
(r"/sensors/env", TempSensorAccess),
])
application.listen(9876)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
start_server()
| # coding: utf-8
import json
import tornado.ioloop
import tornado.web
import Adafruit_BMP.BMP085 as BMP085
class SensorAccess(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self):
self.write(json.dumps(self.read_sensor()))
self.finish()
def read_sensor(self):
pass
class TempSensorAccess(SensorAccess):
def read_sensor(self):
sensor = BMP085.BMP085(mode=BMP085.BMP085_ULTRAHIGHRES)
return {
'temperature': sensor.read_temperature(),
'pressure': sensor.read_pressure(),
}
class IndexHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self):
self.write(json.dumps({
'inde': 'pitools service'
}))
def start_server():
application = tornado.web.Application([
(r"/", IndexHandler),
(r"/sensors/env", TempSensorAccess),
])
application.listen(9876)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
start_server()
|
Fix responsiveness of the customized config component | <div class="border-2 border-smoke rounded mb-8">
<div class="md:flex">
<div class="bg-smoke-lighter border-b-2 border-smoke md:w-1/2 md:border-b-0 md:border-r-2 md:border-smoke">
<div class="px-4 py-3 bg-white font-semibold border-b-2 border-smoke-light text-smoke-darker">Default values</div>
<pre class="bg-smoke markdown language-js"><code>{{ $default }}</code></pre>
</div>
<div class="bg-smoke-lighter md:w-1/2">
<div class="px-4 py-3 bg-white font-semibold border-b-2 border-smoke-light text-smoke-darker">Customized example</div>
<pre class="bg-smoke markdown language-js"><code>{{ $customized }}</code></pre>
</div>
</div>
</div>
| <div class="border-2 border-smoke rounded mb-8">
<div class="md:flex">
<div class="w-1/2 bg-smoke-lighter border-b-2 border-smoke md:border-b-0 md:border-r-2 md:border-smoke">
<div class="px-4 py-3 bg-white font-semibold border-b-2 border-smoke-light text-smoke-darker">Default values</div>
<pre class="bg-smoke markdown language-js"><code>{{ $default }}</code></pre>
</div>
<div class="w-1/2 bg-smoke-lighter">
<div class="px-4 py-3 bg-white font-semibold border-b-2 border-smoke-light text-smoke-darker">Customized example</div>
<pre class="bg-smoke markdown language-js"><code>{{ $customized }}</code></pre>
</div>
</div>
</div>
|
Clarify this is Mesos-related in PyPI description | import sys
from setuptools import setup
extra = {}
if sys.version_info >= (3,):
extra['use_2to3'] = True
setup(name='marathon',
version="0.2.8",
description='Marathon Client Library',
long_description="""Python interface to the Mesos Marathon REST API.""",
author='Mike Babineau',
author_email='michael.babineau@gmail.com',
install_requires=[ 'requests>=2.0.0' ],
url='https://github.com/thefactory/marathon-python',
packages=['marathon', 'marathon.models'],
license='MIT',
platforms='Posix; MacOS X; Windows',
classifiers=['Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries :: Python Modules'],
**extra
) | import sys
from setuptools import setup
extra = {}
if sys.version_info >= (3,):
extra['use_2to3'] = True
setup(name='marathon',
version="0.2.8",
description='Marathon Client Library',
long_description="""Python interface to the Marathon REST API.""",
author='Mike Babineau',
author_email='michael.babineau@gmail.com',
install_requires=[ 'requests>=2.0.0' ],
url='https://github.com/thefactory/marathon-python',
packages=['marathon', 'marathon.models'],
license='MIT',
platforms='Posix; MacOS X; Windows',
classifiers=['Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries :: Python Modules'],
**extra
) |
Add try catch to test | package se.kth.csc.controller;
import org.junit.Before;
import org.junit.Test;
import se.kth.csc.model.Account;
import se.kth.csc.persist.AccountStore;
import java.security.Principal;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class HomeControllerTest {
// System under test (SUT):
private HomeController homeController;
// Dependencies of this unit
private AccountStore accountStore;
@Before
public void setUp() throws Exception {
// Mock dependencies
accountStore = mock(AccountStore.class);
// Create SUT
homeController = new HomeController(accountStore);
}
@Test
public void testMakeMeAdmin() {
// Set up expected behavior of mocks
Principal principal = mock(Principal.class);
when(principal.getName()).thenReturn("testuser");
Account account = mock(Account.class);
when(accountStore.fetchAccountWithPrincipalName("testuser")).thenReturn(account);
// Run the system under test
String result = null;
try {
result = homeController.makeMeAdmin(principal);
} catch (ForbiddenException e) {
// Do nothing
}
// Verify that interactions with mocks happened
verify(account, atLeastOnce()).setAdmin(true);
// Verify actual returned results
assertEquals("redirect:/debug", result);
}
}
| package se.kth.csc.controller;
import org.junit.Before;
import org.junit.Test;
import se.kth.csc.model.Account;
import se.kth.csc.persist.AccountStore;
import java.security.Principal;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class HomeControllerTest {
// System under test (SUT):
private HomeController homeController;
// Dependencies of this unit
private AccountStore accountStore;
@Before
public void setUp() throws Exception {
// Mock dependencies
accountStore = mock(AccountStore.class);
// Create SUT
homeController = new HomeController(accountStore);
}
@Test
public void testMakeMeAdmin() {
// Set up expected behavior of mocks
Principal principal = mock(Principal.class);
when(principal.getName()).thenReturn("testuser");
Account account = mock(Account.class);
when(accountStore.fetchAccountWithPrincipalName("testuser")).thenReturn(account);
// Run the system under test
String result = homeController.makeMeAdmin(principal);
// Verify that interactions with mocks happened
verify(account, atLeastOnce()).setAdmin(true);
// Verify actual returned results
assertEquals("redirect:/debug", result);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.