text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Fix clicking on dots bug
|
import React, { Component, PropTypes } from 'react';
import {districtColors, partyData} from './Constants';
class Precinct extends Component {
renderDots(dots, party) {
const color = party ? partyData[party].color: "black";
// TODO(benkraft): make dots clickable too
return dots && dots.map(({x, y}, i) => <circle fill={color} key={i} cx={x} cy={y} r={0.03} />);
}
render() {
const {
district, dots, party,
onMouseDown, onMouseEnter, onMouseUp, onContextMenu,
...props} = this.props;
return <g {...{onMouseDown, onMouseEnter, onMouseUp, onContextMenu}}>
<rect stroke="black" strokeWidth="0.01" fill={districtColors[district]} {...props} />
{this.renderDots(dots, party)}
</g>;
}
}
Precinct.propTypes = {
x: PropTypes.number.isRequired,
y: PropTypes.number.isRequired,
width: PropTypes.number.isRequired,
height: PropTypes.number.isRequired,
district: PropTypes.number.isRequired,
party: PropTypes.string,
dots: PropTypes.arrayOf(PropTypes.shape({
x: PropTypes.number.isRequired,
y: PropTypes.number.isRequired,
})),
onMouseDown: PropTypes.func.isRequired,
onMouseEnter: PropTypes.func.isRequired,
onMouseUp: PropTypes.func.isRequired,
onContextMenu: PropTypes.func.isRequired,
};
export default Precinct;
|
import React, { Component, PropTypes } from 'react';
import {districtColors, partyData} from './Constants';
class Precinct extends Component {
renderDots(dots, party) {
const color = party ? partyData[party].color: "black";
// TODO(benkraft): make dots clickable too
return dots && dots.map(({x, y}, i) => <circle fill={color} key={i} cx={x} cy={y} r={0.03} />);
}
render() {
const {district, dots, party, ...props} = this.props;
return <g>
<rect stroke="black" strokeWidth="0.01" fill={districtColors[district]} {...props} />
{this.renderDots(dots, party)}
</g>;
}
}
Precinct.propTypes = {
x: PropTypes.number.isRequired,
y: PropTypes.number.isRequired,
width: PropTypes.number.isRequired,
height: PropTypes.number.isRequired,
district: PropTypes.number.isRequired,
party: PropTypes.string,
dots: PropTypes.arrayOf(PropTypes.shape({
x: PropTypes.number.isRequired,
y: PropTypes.number.isRequired,
})),
};
export default Precinct;
|
OAK-2954: Add MBean to enforce session refresh on all open sessions
Update package export version as required
git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1683423 13f79535-47bb-0310-9956-ffa450edef68
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
@Version("1.1.0")
@Export(optional = "provide:=true")
package org.apache.jackrabbit.oak.management;
import aQute.bnd.annotation.Version;
import aQute.bnd.annotation.Export;
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
@Version("1.0")
@Export(optional = "provide:=true")
package org.apache.jackrabbit.oak.management;
import aQute.bnd.annotation.Version;
import aQute.bnd.annotation.Export;
|
Apply revert to the draft page.
|
# -*- coding: utf-8 -*-
from cms.management.commands.subcommands.base import SubcommandsCommand
from cms.models import CMSPlugin
from cms.models.pagemodel import Page
from django.core.management.base import NoArgsCommand
class ModeratorOnCommand(NoArgsCommand):
help = 'Turn moderation on, run AFTER upgrading to 2.4'
def handle_noargs(self, **options):
"""
Ensure that the public pages look the same as their draft versions.
This is done by checking the content of the public pages, and reverting
the draft version to look the same.
The second stage is to go through the draft pages and publish the ones
marked as published.
The end result should be that the public pages and their draft versions
have the same plugins listed. If both versions exist and have content,
the public page has precedence. Otherwise, the draft version is used.
"""
for page in Page.objects.public():
if CMSPlugin.objects.filter(placeholder__page=page).count():
page.publisher_draft.revert()
for page in Page.objects.drafts().filter(published=True):
page.publish()
class ModeratorCommand(SubcommandsCommand):
help = 'Moderator utilities'
subcommands = {
'on': ModeratorOnCommand,
}
|
# -*- coding: utf-8 -*-
from cms.management.commands.subcommands.base import SubcommandsCommand
from cms.models import CMSPlugin
from cms.models.pagemodel import Page
from django.core.management.base import NoArgsCommand
class ModeratorOnCommand(NoArgsCommand):
help = 'Turn moderation on, run AFTER upgrading to 2.4'
def handle_noargs(self, **options):
"""
Ensure that the public pages look the same as their draft versions.
This is done by checking the content of the public pages, and reverting
the draft version to look the same.
The second stage is to go through the draft pages and publish the ones
marked as published.
The end result should be that the public pages and their draft versions
have the same plugins listed. If both versions exist and have content,
the public page has precedence. Otherwise, the draft version is used.
"""
for page in Page.objects.public():
if CMSPlugin.objects.filter(placeholder__page=page).count():
page.revert()
for page in Page.objects.drafts().filter(published=True):
page.publish()
class ModeratorCommand(SubcommandsCommand):
help = 'Moderator utilities'
subcommands = {
'on': ModeratorOnCommand,
}
|
Remove final of 'has' method
|
<?php
namespace Bauhaus;
use Bauhaus\Container\ItemNotFoundException;
class Container implements ContainerInterface
{
private $items = [];
public function __construct(array $items = [])
{
$this->items = $items;
}
public function has($label)
{
return array_key_exists($label, $this->items);
}
public function get($label)
{
if (false === $this->has($label)) {
throw new ItemNotFoundException($label);
}
return $this->items[$label];
}
final public function __get($label)
{
return $this->get($label);
}
final public function items(): array
{
return $this->items;
}
public function asArray(): array
{
throw new \RuntimeException('Method asArray not implemented');
}
}
|
<?php
namespace Bauhaus;
use Bauhaus\Container\ItemNotFoundException;
class Container implements ContainerInterface
{
private $items = [];
public function __construct(array $items = [])
{
$this->items = $items;
}
final public function has($label)
{
return array_key_exists($label, $this->items);
}
public function get($label)
{
if (false === $this->has($label)) {
throw new ItemNotFoundException($label);
}
return $this->items[$label];
}
final public function __get($label)
{
return $this->get($label);
}
final public function items(): array
{
return $this->items;
}
public function asArray(): array
{
throw new \RuntimeException('Method asArray not implemented');
}
}
|
Use sendAction when no return value is needed
[skip ci]
|
import Ember from 'ember';
import layout from './template';
import permissions from 'ember-osf/const/permissions';
export default Ember.Component.extend({
READ: permissions.READ,
WRITE: permissions.WRITE,
ADMIN: permissions.ADMIN,
layout: layout,
permissionChanges: {},
bibliographicChanges: {},
actions: {
addContributor(userId, permission, isBibliographic) {
this.sendAction('addContributor', userId, permission, isBibliographic);
},
removeContributor(contrib) {
this.sendAction('removeContributor', contrib);
},
permissionChange(contributor, permission) {
this.set(`permissionChanges.${contributor.id}`, permission.toLowerCase());
},
bibliographicChange(contributor, isBibliographic) {
this.set(`bibliographicChanges.${contributor.id}`, isBibliographic);
},
updateContributors() {
this.sendAction(
'editContributors',
this.get('contributors'),
this.get('permissionChanges'),
this.get('bibliographicChanges')
);
}
}
});
|
import Ember from 'ember';
import layout from './template';
import permissions from 'ember-osf/const/permissions';
export default Ember.Component.extend({
READ: permissions.READ,
WRITE: permissions.WRITE,
ADMIN: permissions.ADMIN,
layout: layout,
permissionChanges: {},
bibliographicChanges: {},
actions: {
addContributor(userId, permission, isBibliographic) {
this.sendAction('addContributor', userId, permission, isBibliographic);
},
removeContributor(contrib) {
this.sendAction('removeContributor', contrib);
},
permissionChange(contributor, permission) {
this.set(`permissionChanges.${contributor.id}`, permission.toLowerCase());
},
bibliographicChange(contributor, isBibliographic) {
this.set(`bibliographicChanges.${contributor.id}`, isBibliographic);
},
updateContributors() {
this.attrs.editContributors(
this.get('contributors'),
this.get('permissionChanges'),
this.get('bibliographicChanges')
);
}
}
});
|
Use absolute path for assets
|
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Lifecycle Building Center</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="description" content="">
<meta name="viewport" content="width=device-width" />
<link rel="stylesheet" type="text/css" href="/assets/style/bootstrap.min.css" media="screen,projection" />
</head>
<body>
<div class="navbar">
<div class="navbar-inner">
<div class="container">
<nav>
<ul class="nav">
<li>
<a href="#">Link</a>
</li>
<li>
<a href="#">Link</a>
</li>
<li>
<a href="#">Link</a>
</li>
<li>
<a href="#">Link</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<div class="container">
|
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Lifecycle Building Center</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="description" content="">
<meta name="viewport" content="width=device-width" />
<link rel="stylesheet" type="text/css" href="../../assets/style/bootstrap.min.css" media="screen,projection" />
</head>
<body>
<div class="navbar">
<div class="navbar-inner">
<div class="container">
<nav>
<ul class="nav">
<li>
<a href="#">Link</a>
</li>
<li>
<a href="#">Link</a>
</li>
<li>
<a href="#">Link</a>
</li>
<li>
<a href="#">Link</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<div class="container">
|
Make sure the StartupEvent is fired after the runtime config is set
|
package io.quarkus.arc.deployment;
import static io.quarkus.deployment.annotations.ExecutionTime.RUNTIME_INIT;
import java.util.List;
import io.quarkus.arc.runtime.ArcRecorder;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.annotations.Consume;
import io.quarkus.deployment.annotations.Record;
import io.quarkus.deployment.builditem.ApplicationStartBuildItem;
import io.quarkus.deployment.builditem.RuntimeConfigSetupCompleteBuildItem;
import io.quarkus.deployment.builditem.ServiceStartBuildItem;
import io.quarkus.deployment.builditem.ShutdownContextBuildItem;
public class LifecycleEventsBuildStep {
@Consume(RuntimeConfigSetupCompleteBuildItem.class)
@BuildStep
@Record(RUNTIME_INIT)
ApplicationStartBuildItem startupEvent(ArcRecorder recorder,
List<ServiceStartBuildItem> startList,
BeanContainerBuildItem beanContainer,
ShutdownContextBuildItem shutdown) {
recorder.handleLifecycleEvents(shutdown, beanContainer.getValue());
return new ApplicationStartBuildItem();
}
}
|
package io.quarkus.arc.deployment;
import static io.quarkus.deployment.annotations.ExecutionTime.RUNTIME_INIT;
import java.util.List;
import io.quarkus.arc.runtime.ArcRecorder;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.annotations.Record;
import io.quarkus.deployment.builditem.ApplicationStartBuildItem;
import io.quarkus.deployment.builditem.ServiceStartBuildItem;
import io.quarkus.deployment.builditem.ShutdownContextBuildItem;
public class LifecycleEventsBuildStep {
@BuildStep
@Record(RUNTIME_INIT)
ApplicationStartBuildItem startupEvent(ArcRecorder recorder,
List<ServiceStartBuildItem> startList,
BeanContainerBuildItem beanContainer,
ShutdownContextBuildItem shutdown) {
recorder.handleLifecycleEvents(shutdown, beanContainer.getValue());
return new ApplicationStartBuildItem();
}
}
|
Switch Django version from 1.0 to 1.1
|
"""Configuration."""
import logging
import os
import re
from google.appengine.ext.appstats import recording
logging.info('Loading %s from %s', __name__, __file__)
# Custom webapp middleware to add Appstats.
def webapp_add_wsgi_middleware(app):
app = recording.appstats_wsgi_middleware(app)
return app
# Appstats URL.
# TODO: Drop this once it is the default.
appstats_stats_url = '/_ah/stats'
# Custom Appstats path normalization.
def appstats_normalize_path(path):
if path.startswith('/user/'):
return '/user/X'
if path.startswith('/user_popup/'):
return '/user_popup/X'
if path.startswith('/rss/'):
i = path.find('/', 5)
if i > 0:
return path[:i] + '/X'
return re.sub(r'\d+', 'X', path)
# Declare the Django version we need.
from google.appengine.dist import use_library
use_library('django', '1.1')
# Fail early if we can't import Django 1.x. Log identifying information.
import django
logging.info('django.__file__ = %r, django.VERSION = %r',
django.__file__, django.VERSION)
assert django.VERSION[0] >= 1, "This Django version is too old"
|
"""Configuration."""
import logging
import os
import re
from google.appengine.ext.appstats import recording
logging.info('Loading %s from %s', __name__, __file__)
# Custom webapp middleware to add Appstats.
def webapp_add_wsgi_middleware(app):
app = recording.appstats_wsgi_middleware(app)
return app
# Appstats URL.
# TODO: Drop this once it is the default.
appstats_stats_url = '/_ah/stats'
# Custom Appstats path normalization.
def appstats_normalize_path(path):
if path.startswith('/user/'):
return '/user/X'
if path.startswith('/user_popup/'):
return '/user_popup/X'
if path.startswith('/rss/'):
i = path.find('/', 5)
if i > 0:
return path[:i] + '/X'
return re.sub(r'\d+', 'X', path)
# Declare the Django version we need.
from google.appengine.dist import use_library
use_library('django', '1.0')
# Fail early if we can't import Django 1.x. Log identifying information.
import django
logging.info('django.__file__ = %r, django.VERSION = %r',
django.__file__, django.VERSION)
assert django.VERSION[0] >= 1, "This Django version is too old"
|
Use try/finally to ensure oldValue is cleared
If any JS exception is thrown during event delivery the oldValue
should still be set to null to enable garbage collection.
Change-Id: I740db06e93162f86982ffd418c2072bfb4d5d75c
|
// Copyright (C) 2012 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.client.ui;
public class ListenableOldValue<T> extends ListenableValue<T> {
private T oldValue;
public T getOld() {
return oldValue;
}
public void set(final T value) {
try {
oldValue = get();
super.set(value);
} finally {
oldValue = null; // allow it to be gced before the next event
}
}
}
|
// Copyright (C) 2012 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.client.ui;
public class ListenableOldValue<T> extends ListenableValue<T> {
private T oldValue;
public T getOld() {
return oldValue;
}
public void set(final T value) {
oldValue = get();
super.set(value);
oldValue = null; // allow it to be gced before the next event
}
}
|
Select - update name to name[] when multiple=true
|
<?php
class Form_Select extends Form_Input
{
protected $_values;
protected $_value;
public function __construct($title, $value, array $values, $allowMultiple = false)
{
parent::__construct($title, null);
if ($allowMultiple)
{
$this->_attributes['multiple'] = 'multiple';
$this->_attributes['name'] .= '[]';
}
$this->_value = $value;
$this->_values = $values;
}
protected function _getInput()
{
$element = preg_replace('~^<input(.*)/>$~', 'select\1', parent::_getInput());
$options = '';
foreach ($this->_values as $value => $name)
{
$selected = (is_array($this->_value) && in_array($value, $this->_value) || $this->_value == $value);
$options .= '<option value="'. htmlspecialchars($value) .'"'.($selected ? ' selected' : '').'>'. gettext($name) .'</option>';
}
return <<<EOT
<{$element}>
{$options}
</select>
EOT;
}
}
|
<?php
class Form_Select extends Form_Input
{
protected $_values;
protected $_value;
public function __construct($title, $value, array $values, $allowMultiple = false)
{
parent::__construct($title, null);
if ($allowMultiple)
$this->_attributes['multiple'] = 'multiple';
$this->_value = $value;
$this->_values = $values;
}
protected function _getInput()
{
$element = preg_replace('~^<input(.*)/>$~', 'select\1', parent::_getInput());
$options = '';
foreach ($this->_values as $value => $name)
{
$selected = (is_array($this->_value) && in_array($value, $this->_value) || $this->_value == $value);
$options .= '<option value="'. htmlspecialchars($value) .'"'.($selected ? ' selected' : '').'>'. gettext($name) .'</option>';
}
return <<<EOT
<{$element}>
{$options}
</select>
EOT;
}
}
|
Refactor codes and revise main
|
"""Leetcode 172. Factorial Trailing Zeroes
Easy
URL: https://leetcode.com/problems/factorial-trailing-zeroes/
Given an integer n, return the number of trailing zeroes in n!.
Example 1:
Input: 3
Output: 0
Explanation: 3! = 6, no trailing zero.
Example 2:
Input: 5
Output: 1
Explanation: 5! = 120, one trailing zero.
Note: Your solution should be in logarithmic time complexity.
"""
class Solution(object):
def trailingZeroes(self, n):
"""
:type n: int
:rtype: int
Time complexity: O(log_5 n).
Space complexity: O(1).
"""
zeros = 0
current = n
while current // 5 > 0:
current = current // 5
zeros += current
return zeros
def main():
# Ans: 0
n = 3
print Solution().trailingZeroes(n)
# Ans: 6
n = 25
print Solution().trailingZeroes(n)
if __name__ == '__main__':
main()
|
"""Leetcode 172. Factorial Trailing Zeroes
Easy
URL: https://leetcode.com/problems/factorial-trailing-zeroes/
Given an integer n, return the number of trailing zeroes in n!.
Example 1:
Input: 3
Output: 0
Explanation: 3! = 6, no trailing zero.
Example 2:
Input: 5
Output: 1
Explanation: 5! = 120, one trailing zero.
Note: Your solution should be in logarithmic time complexity.
"""
class Solution(object):
def trailingZeroes(self, n):
"""
:type n: int
:rtype: int
Time complexity: O(log_5 n).
Space complexity: O(1).
"""
zeros = 0
temp = n
while temp // 5 > 0:
temp = temp // 5
zeros += temp
return zeros
def main():
# Ans: 0
n = 3
print Solution().trailingZeroes(n)
# Ans: 1
n = 5
print Solution().trailingZeroes(n)
if __name__ == '__main__':
main()
|
Revert "make the property protected instead of private"
This reverts commit 409669ec1686f71ae3804003540423e45d842f2e.
|
<?php
namespace WsdlToPhp\DomHandler;
class NameSpaceHandler extends AttributeHandler
{
/**
* @var \DOMNameSpaceNode
*/
private $nodeNameSpace;
/**
* @param \DOMNameSpaceNode $nameSpaceNode
* @param AbstractDomDocumentHandler $domDocumentHandler
* @param int $index
*/
public function __construct(\DOMNameSpaceNode $nameSpaceNode, AbstractDomDocumentHandler $domDocumentHandler, $index = -1)
{
parent::__construct(new \DOMAttr($nameSpaceNode->nodeName, $nameSpaceNode->nodeValue), $domDocumentHandler, $index);
$this->nodeNameSpace = $nameSpaceNode;
}
/**
* value is always with [http|https]:// so we need to keep the full value
* @param bool $withNamespace
* @param bool $withinItsType
* @param string $asType
* @return mixed
*/
public function getValue($withNamespace = false, $withinItsType = true, $asType = null)
{
return parent::getValue(true, $withinItsType, $asType);
}
/**
* @return null|string
*/
public function getValueNamespace()
{
return null;
}
}
|
<?php
namespace WsdlToPhp\DomHandler;
class NameSpaceHandler extends AttributeHandler
{
/**
* @var \DOMNameSpaceNode
*/
protected $nodeNameSpace;
/**
* @param \DOMNameSpaceNode $nameSpaceNode
* @param AbstractDomDocumentHandler $domDocumentHandler
* @param int $index
*/
public function __construct(\DOMNameSpaceNode $nameSpaceNode, AbstractDomDocumentHandler $domDocumentHandler, $index = -1)
{
parent::__construct(new \DOMAttr($nameSpaceNode->nodeName, $nameSpaceNode->nodeValue), $domDocumentHandler, $index);
$this->nodeNameSpace = $nameSpaceNode;
}
/**
* value is always with [http|https]:// so we need to keep the full value
* @param bool $withNamespace
* @param bool $withinItsType
* @param string $asType
* @return mixed
*/
public function getValue($withNamespace = false, $withinItsType = true, $asType = null)
{
return parent::getValue(true, $withinItsType, $asType);
}
/**
* @return null|string
*/
public function getValueNamespace()
{
return null;
}
}
|
[Promotion] Change misleading PromotionCouponRepository method name
|
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Component\Promotion\Repository;
use Doctrine\ORM\QueryBuilder;
use Sylius\Component\Promotion\Model\PromotionCouponInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;
/**
* @author Arkadiusz Krakowiak <arkadiusz.krakowiak@lakion.com>
*/
interface PromotionCouponRepositoryInterface extends RepositoryInterface
{
/**
* @param mixed $promotionId
*
* @return QueryBuilder
*/
public function createQueryBuilderByPromotionId($promotionId): QueryBuilder;
/**
* @param int $codeLength
*
* @return int
*/
public function countByCodeLength(int $codeLength): int;
/**
* @param string $code
* @param string $promotionCode
*
* @return PromotionCouponInterface|null
*/
public function findOneByCodeAndPromotionCode(string $code, string $promotionCode): ?PromotionCouponInterface;
/**
* @param string $promotionCode
*
* @return iterable
*/
public function createPaginatorForPromotion(string $promotionCode): iterable;
}
|
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Component\Promotion\Repository;
use Doctrine\ORM\QueryBuilder;
use Sylius\Component\Promotion\Model\PromotionCouponInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;
/**
* @author Arkadiusz Krakowiak <arkadiusz.krakowiak@lakion.com>
*/
interface PromotionCouponRepositoryInterface extends RepositoryInterface
{
/**
* @param mixed $promotionId
*
* @return QueryBuilder
*/
public function createQueryBuilderByPromotionId($promotionId): QueryBuilder;
/**
* @param int $codeLength
*
* @return int
*/
public function countByCodeLength(int $codeLength): int;
/**
* @param string $code
* @param string $promotionCode
*
* @return PromotionCouponInterface|null
*/
public function findOneByCodeAndPromotionCode(string $code, string $promotionCode): ?PromotionCouponInterface;
/**
* @param string $promotionCode
*
* @return iterable
*/
public function findByPromotionCode(string $promotionCode): iterable;
}
|
Add a class for sign button
What will make it easier to manipulate the theme
|
from django.forms import ModelForm
from django import forms
from django.forms.widgets import TextInput
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from braces.forms import UserKwargModelFormMixin
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from constance import config
from .models import Signature
class TelephoneInput(TextInput):
input_type = 'tel'
class SignatureForm(UserKwargModelFormMixin, ModelForm):
giodo = forms.BooleanField(widget=forms.CheckboxInput(), required=True)
def __init__(self, *args, **kwargs):
super(SignatureForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_action = reverse('petition:create')
self.helper.form_method = 'post'
self.helper.add_input(Submit('submit', _('Sign'), css_class="btn-sign btn-lg btn-block"))
self.fields['telephone'].widget = TelephoneInput()
self.fields['newsletter'].label = config.NEWSLETTER_TEXT
self.fields['giodo'].label = config.AGGREMENT_TEXT
class Meta:
model = Signature
fields = ['first_name', 'second_name', 'email', 'city', 'telephone', 'giodo', 'newsletter']
|
from django.forms import ModelForm
from django import forms
from django.forms.widgets import TextInput
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from braces.forms import UserKwargModelFormMixin
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from constance import config
from .models import Signature
class TelephoneInput(TextInput):
input_type = 'tel'
class SignatureForm(UserKwargModelFormMixin, ModelForm):
giodo = forms.BooleanField(widget=forms.CheckboxInput(), required=True)
def __init__(self, *args, **kwargs):
super(SignatureForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_action = reverse('petition:create')
self.helper.form_method = 'post'
self.helper.add_input(Submit('submit', _('Sign'), css_class="btn-lg btn-block"))
self.fields['telephone'].widget = TelephoneInput()
self.fields['newsletter'].label = config.NEWSLETTER_TEXT
self.fields['giodo'].label = config.AGGREMENT_TEXT
class Meta:
model = Signature
fields = ['first_name', 'second_name', 'email', 'city', 'telephone', 'giodo', 'newsletter']
|
Fix version resolve in browser - check if in node
|
/* global exports */
"use strict";
var fs = require('fs');
var path = require('path');
// module Docopt.FFI
/**
* Try and detect the version as indicated in the package.json neighbouring
* the main module. Uses `require.main` to detect the main module and traverses
* the parent directories in a search for a `package.json` using
* `require.main.paths`.
*/
exports.readPkgVersionImpl = function (Just) {
return function(Nothing) {
return function() {
if (!require.main) {
return Nothing;
} else if (require.main && require.main.paths /* in node? */){
for (var i=0; i < require.main.paths.length; i++) {
var xs = require.main.paths[i].split(path.sep);
if (xs.pop() === 'node_modules' && xs.length > 1) {
xs.push('package.json');
var p = xs.join(path.sep);
if (fs.existsSync(p)) {
return Just(JSON.parse(fs.readFileSync(p)).version);
}
}
}
return Nothing;
}
return Nothing;
}
}
};
|
/* global exports */
"use strict";
var fs = require('fs');
var path = require('path');
// module Docopt.FFI
/**
* Try and detect the version as indicated in the package.json neighbouring
* the main module. Uses `require.main` to detect the main module and traverses
* the parent directories in a search for a `package.json` using
* `require.main.paths`.
*/
exports.readPkgVersionImpl = function (Just) {
return function(Nothing) {
return function() {
if (!require.main) {
return Nothing;
} else {
for (var i=0; i < require.main.paths.length; i++) {
var xs = require.main.paths[i].split(path.sep);
if (xs.pop() === 'node_modules' && xs.length > 1) {
xs.push('package.json');
var p = xs.join(path.sep);
if (fs.existsSync(p)) {
return Just(JSON.parse(fs.readFileSync(p)).version);
}
}
}
return Nothing;
}
}
}
};
|
Disable join button before contest enrolment started
|
import React from 'react';
import moment from 'moment';
import Button from 'material-ui/Button';
import { Link } from 'react-router';
import { FormattedMessage } from 'react-intl';
import messages from './messages';
function ContestButton(props) {
const { canJoinStarted, signupDuration, start, id } = props.contest;
const enrolmentStart = moment(start);
const startTime = enrolmentStart.add(signupDuration, 'seconds');
const started = props.time.isAfter(startTime);
const canEnter = started || props.isOwner;
const canJoin = props.time.isAfter(enrolmentStart);
const showJoinButton = (!started || canJoinStarted) && !props.contest.joined && !props.isOwner;
return showJoinButton ? joinButton(canJoin, props.onClick) : enterButton(canEnter, id);
}
ContestButton.propTypes = {
contest: React.PropTypes.object.isRequired,
time: React.PropTypes.object.isRequired,
onClick: React.PropTypes.func,
isOwner: React.PropTypes.bool.isRequired,
};
export default ContestButton;
function enterButton(canEnter, contestId) {
const button = (
<Button raised color="primary" disabled={!canEnter}>
<FormattedMessage {...messages.enter} />
</Button>
);
return canEnter ? <Link to={`/contests/${contestId}`}>{button}</Link> : button;
}
function joinButton(canJoin, join) {
return (
<Button onClick={join} raised color="primary" disabled={!canJoin}>
<FormattedMessage {...messages.join} />
</Button>
);
}
|
import React from 'react';
import moment from 'moment';
import Button from 'material-ui/Button';
import { Link } from 'react-router';
import { FormattedMessage } from 'react-intl';
import messages from './messages';
function ContestButton(props) {
const { canJoinStarted, signupDuration, start, id } = props.contest;
const startTime = moment(start).add(signupDuration, 'seconds');
const started = props.time.isAfter(startTime);
const canEnter = started || props.isOwner;
const canJoin = (!started || canJoinStarted) && !props.contest.joined && !props.isOwner;
return canJoin ? joinButton(props.onClick) : enterButton(canEnter, id);
}
ContestButton.propTypes = {
contest: React.PropTypes.object.isRequired,
time: React.PropTypes.object.isRequired,
onClick: React.PropTypes.func,
isOwner: React.PropTypes.bool.isRequired,
};
export default ContestButton;
function enterButton(canEnter, contestId) {
const button = (
<Button raised color="primary" disabled={!canEnter}>
<FormattedMessage {...messages.enter} />
</Button>
);
return canEnter ? <Link to={`/contests/${contestId}`}>{button}</Link> : button;
}
function joinButton(join) {
return (
<Button onClick={join} raised color="primary">
<FormattedMessage {...messages.join} />
</Button>
);
}
|
Rename parameter DEFAULT_PROTOCOL to DEFAULT_URL_PROTOCOL
|
# -*- coding: utf-8 -*-
# standard library
import collections
# django
from django.utils.translation import ugettext_lazy as _
ParameterDefinition = collections.namedtuple(
'Parameter',
[
'name',
'default',
'kind',
'verbose_name',
]
)
class ParameterDefinitionList(object):
definitions = [
ParameterDefinition(
name='DEFAULT_URL_PROTOCOL',
default='https',
kind='str',
verbose_name=_('Default url protocol'),
),
]
choices = tuple((x.name, x.verbose_name) for x in definitions)
|
# -*- coding: utf-8 -*-
# standard library
import collections
# django
from django.utils.translation import ugettext_lazy as _
ParameterDefinition = collections.namedtuple(
'Parameter',
[
'name',
'default',
'kind',
'verbose_name',
]
)
class ParameterDefinitionList(object):
definitions = [
ParameterDefinition(
name='DEFAULT_PROTOCOL',
default='https',
kind='str',
verbose_name=_('default protocol: https'),
),
]
choices = tuple((x.name, x.verbose_name) for x in definitions)
|
Update help_text in api_auth initial migration
I'm updating the help_text in the original migration rather than
creating a new migration that doesn't affect the db, but does do a
bunch of SQL stuff in the migration.
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Token',
fields=[
('token', models.CharField(help_text='API token to use for authentication. Click on SAVE AND CONTINUE EDITING. The token will be generated and you can copy and paste it.', max_length=32, serialize=False, primary_key=True)),
('summary', models.CharField(help_text='Brief explanation of what will use this token', max_length=200)),
('enabled', models.BooleanField(default=False)),
('disabled_reason', models.TextField(default='', help_text='If disabled, explanation of why.', blank=True)),
('contact', models.CharField(default='', help_text='Contact information for what uses this token. Email address, etc', max_length=200, blank=True)),
('created', models.DateTimeField(auto_now_add=True)),
],
options={
},
bases=(models.Model,),
),
]
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Token',
fields=[
('token', models.CharField(help_text='API token to use for authentication. When creating a new token, leave this blank. Click on SAVE AND CONTINUE EDITING. The token will be generated and you can copy and paste it.', max_length=32, serialize=False, primary_key=True)),
('summary', models.CharField(help_text='Brief explanation of what will use this token', max_length=200)),
('enabled', models.BooleanField(default=False)),
('disabled_reason', models.TextField(default='', help_text='If disabled, explanation of why.', blank=True)),
('contact', models.CharField(default='', help_text='Contact information for what uses this token. Email address, etc', max_length=200, blank=True)),
('created', models.DateTimeField(auto_now_add=True)),
],
options={
},
bases=(models.Model,),
),
]
|
Format and mark as InternalAPI
|
package org.jctools.queues;
import org.jctools.util.InternalAPI;
import org.jctools.util.JvmInfo;
import org.jctools.util.UnsafeRefArrayAccess;
@InternalAPI
public final class PaddedCircularArrayOffsetCalculator
{
static final int REF_BUFFER_PAD;
static final long REF_ARRAY_BASE;
static
{
// 2 cache lines pad
REF_BUFFER_PAD = (JvmInfo.CACHE_LINE_SIZE * 2) >> UnsafeRefArrayAccess.REF_ELEMENT_SHIFT;
// Including the buffer pad in the array base offset
final int paddingOffset = REF_BUFFER_PAD << UnsafeRefArrayAccess.REF_ELEMENT_SHIFT;
REF_ARRAY_BASE = UnsafeRefArrayAccess.REF_ARRAY_BASE + paddingOffset;
}
@SuppressWarnings("unchecked")
public static <E> E[] allocate(int capacity)
{
return (E[]) new Object[capacity + REF_BUFFER_PAD * 2];
}
/**
* @param index desirable element index
* @param mask
* @return the offset in bytes within the array for a given index.
*/
protected static long calcElementOffset(long index, long mask)
{
return REF_ARRAY_BASE + ((index & mask) << UnsafeRefArrayAccess.REF_ELEMENT_SHIFT);
}
}
|
package org.jctools.queues;
import org.jctools.util.JvmInfo;
import org.jctools.util.UnsafeRefArrayAccess;
public final class PaddedCircularArrayOffsetCalculator {
static final int REF_BUFFER_PAD;
static final long REF_ARRAY_BASE;
static {
// 2 cache lines pad
REF_BUFFER_PAD = (JvmInfo.CACHE_LINE_SIZE * 2) >> UnsafeRefArrayAccess.REF_ELEMENT_SHIFT;
// Including the buffer pad in the array base offset
final int paddingOffset = REF_BUFFER_PAD << UnsafeRefArrayAccess.REF_ELEMENT_SHIFT;
REF_ARRAY_BASE = UnsafeRefArrayAccess.REF_ARRAY_BASE + paddingOffset;
}
private PaddedCircularArrayOffsetCalculator() {
}
@SuppressWarnings("unchecked")
public static <E> E[] allocate(int capacity) {
return (E[]) new Object[capacity + REF_BUFFER_PAD * 2];
}
/**
* @param index desirable element index
* @param mask
* @return the offset in bytes within the array for a given index.
*/
protected static long calcElementOffset(long index, long mask) {
return REF_ARRAY_BASE + ((index & mask) << UnsafeRefArrayAccess.REF_ELEMENT_SHIFT);
}
}
|
Add make console task mock utility method
|
<?php
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Aedart\Scaffold\Contracts\Tasks\ConsoleTask;
use Mockery as m;
/**
* Console Test
*
* Provides a few helpers for CLI / Console related
* testing
*
* @author Alin Eugen Deac <aedart@gmail.com>
*/
abstract class ConsoleTest extends BaseUnitTest
{
/********************************************************
* Helpers
*******************************************************/
/**
* Returns a console task mock
*
* @return m\MockInterface|ConsoleTask
*/
public function makeTaskMock()
{
return m::mock(ConsoleTask::class);
}
/**
* Returns input mock
*
* @return m\MockInterface|InputInterface
*/
public function makeInputMock()
{
return m::mock(InputInterface::class);
}
/**
* Returns output mock
*
* @return m\MockInterface|OutputInterface
*/
public function makeOutputMock()
{
return m::mock(OutputInterface::class);
}
}
|
<?php
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Mockery as m;
/**
* Console Test
*
* Provides a few helpers for CLI / Console related
* testing
*
* @author Alin Eugen Deac <aedart@gmail.com>
*/
abstract class ConsoleTest extends BaseUnitTest
{
/********************************************************
* Helpers
*******************************************************/
/**
* Returns input mock
*
* @return m\MockInterface|InputInterface
*/
public function makeInputMock()
{
return m::mock(InputInterface::class);
}
/**
* Returns output mock
*
* @return m\MockInterface|OutputInterface
*/
public function makeOutputMock()
{
return m::mock(OutputInterface::class);
}
}
|
Fix PHP 7.1 related failures
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\CacheWarmer;
/**
* Abstract cache warmer that knows how to write a file to the cache.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
abstract class CacheWarmer implements CacheWarmerInterface
{
protected function writeCacheFile($file, $content)
{
$tmpFile = @tempnam(dirname($file), basename($file));
if (false !== @file_put_contents($tmpFile, $content) && @rename($tmpFile, $file)) {
@chmod($file, 0666 & ~umask());
return;
}
throw new \RuntimeException(sprintf('Failed to write cache file "%s".', $file));
}
}
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\CacheWarmer;
/**
* Abstract cache warmer that knows how to write a file to the cache.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
abstract class CacheWarmer implements CacheWarmerInterface
{
protected function writeCacheFile($file, $content)
{
$tmpFile = tempnam(dirname($file), basename($file));
if (false !== @file_put_contents($tmpFile, $content) && @rename($tmpFile, $file)) {
@chmod($file, 0666 & ~umask());
return;
}
throw new \RuntimeException(sprintf('Failed to write cache file "%s".', $file));
}
}
|
Change DEVICE_OWNER to make it more Neutron compliant
Change-Id: Id7a2973928c6df9e134e7b91000e90f244066703
|
# 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.
PORT_STATUS_ACTIVE = 'ACTIVE'
PORT_STATUS_DOWN = 'DOWN'
DEVICE_OWNER = 'compute:kuryr'
NIC_NAME_LEN = 14
VETH_PREFIX = 'tap'
CONTAINER_VETH_PREFIX = 't_c'
# For VLAN type segmentation
MIN_VLAN_TAG = 1
MAX_VLAN_TAG = 4094
BINDING_SUBCOMMAND = 'bind'
DEFAULT_NETWORK_MTU = 1500
FALLBACK_VIF_TYPE = 'unbound'
UNBINDING_SUBCOMMAND = 'unbind'
VIF_DETAILS_KEY = 'binding:vif_details'
VIF_TYPE_KEY = 'binding:vif_type'
|
# 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.
PORT_STATUS_ACTIVE = 'ACTIVE'
PORT_STATUS_DOWN = 'DOWN'
DEVICE_OWNER = 'kuryr:container'
NIC_NAME_LEN = 14
VETH_PREFIX = 'tap'
CONTAINER_VETH_PREFIX = 't_c'
# For VLAN type segmentation
MIN_VLAN_TAG = 1
MAX_VLAN_TAG = 4094
BINDING_SUBCOMMAND = 'bind'
DEFAULT_NETWORK_MTU = 1500
FALLBACK_VIF_TYPE = 'unbound'
UNBINDING_SUBCOMMAND = 'unbind'
VIF_DETAILS_KEY = 'binding:vif_details'
VIF_TYPE_KEY = 'binding:vif_type'
|
Revert "fixed run_unit_test.php system commands"
This reverts commit dac7b56be5f32296cb6c98d72f15a65037017a33.
Conflicts:
tools/run_unit_tests.php
|
<?php
system('php vendor/phpunit/phpunit/phpunit --bootstrap config/bootstrap.php tools/unit_tests/classes/core/Dinkly.php');
system('php vendor/phpunit/phpunit/phpunit --bootstrap config/bootstrap.php tools/unit_tests/classes/core/DinklyBuilder.php');
system('php vendor/phpunit/phpunit/phpunit --bootstrap config/bootstrap.php tools/unit_tests/classes/core/DinklyDataCollection.php');
system('php vendor/phpunit/phpunit/phpunit --bootstrap config/bootstrap.php tools/unit_tests/classes/core/DinklyDataConfig.php');
system('php vendor/phpunit/phpunit/phpunit --bootstrap config/bootstrap.php tools/unit_tests/classes/core/DinklyDataConnector.php');
<<<<<<< HEAD
system('php vendor/phpunit/phpunit/phpunit --bootstrap config/bootstrap.php tools/unit_tests/classes/core/DinklyDataModel.php');
system('php vendor/phpunit/phpunit/phpunit --bootstrap config/bootstrap.php tools/unit_tests/classes/core/DinklyFlash.php');
=======
system('php vendor/phpunit/phpunit/phpunit --bootstrap config/bootstrap.php tools/unit_tests/classes/core/DinklyDataModel.php');
>>>>>>> parent of dac7b56... fixed run_unit_test.php system commands
|
<?php
system('php vendor/phpunit/phpunit/phpunit --bootstrap config/bootstrap.php tools/unit_tests/classes/core/Dinkly.php');
system('php vendor/phpunit/phpunit/phpunit --bootstrap config/bootstrap.php tools/unit_tests/classes/core/DinklyBuilder.php');
system('php vendor/phpunit/phpunit/phpunit --bootstrap config/bootstrap.php tools/unit_tests/classes/core/DinklyDataCollection.php');
system('php vendor/phpunit/phpunit/phpunit --bootstrap config/bootstrap.php tools/unit_tests/classes/core/DinklyDataConfig.php');
system('php vendor/phpunit/phpunit/phpunit --bootstrap config/bootstrap.php tools/unit_tests/classes/core/DinklyDataConnector.php');
system('php vendor/phpunit/phpunit/phpunit --bootstrap config/bootstrap.php tools/unit_tests/classes/core/DinklyDataModel.php');
system('php vendor/phpunit/phpunit/phpunit --bootstrap config/bootstrap.php tools/unit_tests/classes/core/DinklyFlash.php');
|
Fix missing type in array hydrator
|
<?php
/*
* Copyright 2014 Jack Sleight <http://jacksleight.com/>
* This source file is subject to the MIT license that is bundled with this package in the file LICENCE.
*/
namespace Coast\Doctrine\ORM\Internal\Hydration;
use Doctrine\ORM\Internal\Hydration\ArrayHydrator as DoctrineArrayHydrator;
class ArrayHydrator extends DoctrineArrayHydrator
{
protected function gatherRowData(array $data, array &$id, array &$nonemptyComponents)
{
$rowData = parent::gatherRowData($data, $id, $nonemptyComponents);
foreach ($rowData['data'] as $dqlAlias => $data) {
$class = $this->_rsm->aliasMap[$dqlAlias];
$meta = $this->getClassMetadata($class);
if ($meta->discriminatorMap) {
$class = isset($data[$meta->discriminatorColumn['name']])
? $meta->discriminatorMap[$data[$meta->discriminatorColumn['name']]]
: null;
}
$rowData['data'][$dqlAlias]['__CLASS__'] = $class;
}
return $rowData;
}
}
|
<?php
/*
* Copyright 2014 Jack Sleight <http://jacksleight.com/>
* This source file is subject to the MIT license that is bundled with this package in the file LICENCE.
*/
namespace Coast\Doctrine\ORM\Internal\Hydration;
use Doctrine\ORM\Internal\Hydration\ArrayHydrator as DoctrineArrayHydrator;
class ArrayHydrator extends DoctrineArrayHydrator
{
protected function gatherRowData(array $data, array &$id, array &$nonemptyComponents)
{
$rowData = parent::gatherRowData($data, $id, $nonemptyComponents);
foreach ($rowData['data'] as $dqlAlias => $data) {
$class = $this->_rsm->aliasMap[$dqlAlias];
$meta = $this->getClassMetadata($class);
if ($meta->discriminatorMap) {
$class = $meta->discriminatorMap[$data[$meta->discriminatorColumn['name']]];
}
$rowData['data'][$dqlAlias]['__CLASS__'] = $class;
}
return $rowData;
}
}
|
Add another Google Maps URL.
|
// These URL paths will be transformed to CN mirrors.
var mirrors = {
"//developers.google.com" : "//developers.google.cn",
"//firebase.google.com" : "//firebase.google.cn",
"//developer.android.com" : "//developer.android.google.cn",
"//angular.io" : "//angular.cn",
"//maps.google.com" : "//maps.google.cn",
"google.com/maps" : "google.cn/maps",
}
// These URL paths are not available on CN mirrors, therefore won't be transformed.
var whitelist = [
"//developers.google.com/groups",
"//developers.google.com/events",
"//firebase.google.com/support/contact/",
]
function mirrorUrl(url) {
// Check for whitelisting.
for (var key in whitelist) {
if (url.includes(whitelist[key])) {
return url;
}
}
// Check for mapping.
for (var key in mirrors) {
if (url.includes(key)) {
url = url.replace(key, mirrors[key]);
break;
}
}
return url;
}
|
// These URL paths will be transformed to CN mirrors.
var mirrors = {
"//developers.google.com" : "//developers.google.cn",
"//firebase.google.com" : "//firebase.google.cn",
"//developer.android.com" : "//developer.android.google.cn",
"//angular.io" : "//angular.cn",
"google.com/maps" : "google.cn/maps",
}
// These URL paths are not available on CN mirrors, therefore won't be transformed.
var whitelist = [
"//developers.google.com/groups",
"//developers.google.com/events",
"//firebase.google.com/support/contact/",
]
function mirrorUrl(url) {
// Check for whitelisting.
for (var key in whitelist) {
if (url.includes(whitelist[key])) {
return url;
}
}
// Check for mapping.
for (var key in mirrors) {
if (url.includes(key)) {
url = url.replace(key, mirrors[key]);
break;
}
}
return url;
}
|
Clear activity on pick image intents.
|
package org.beryl.intents;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.webkit.MimeTypeMap;
public class IntentHelper {
public static boolean canHandleIntent(final Context context, final Intent intent) {
if (intent != null) {
final PackageManager pm = context.getPackageManager();
if (pm != null) {
if (pm.queryIntentActivities(intent, 0).size() > 0) {
return true;
}
}
}
return false;
}
public static String getMimeTypeFromUrl(Uri url) {
return getMimeTypeFromUrl(url.getPath());
}
public static String getMimeTypeFromUrl(String url) {
final MimeTypeMap mimeMap = MimeTypeMap.getSingleton();
final String extension = MimeTypeMap.getFileExtensionFromUrl(url);
return mimeMap.getMimeTypeFromExtension(extension);
}
public static final Intent getContentByType(String mimeType) {
final Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(mimeType);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
return intent;
}
}
|
package org.beryl.intents;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.webkit.MimeTypeMap;
public class IntentHelper {
public static boolean canHandleIntent(final Context context, final Intent intent) {
if (intent != null) {
final PackageManager pm = context.getPackageManager();
if (pm != null) {
if (pm.queryIntentActivities(intent, 0).size() > 0) {
return true;
}
}
}
return false;
}
public static String getMimeTypeFromUrl(Uri url) {
return getMimeTypeFromUrl(url.getPath());
}
public static String getMimeTypeFromUrl(String url) {
final MimeTypeMap mimeMap = MimeTypeMap.getSingleton();
final String extension = MimeTypeMap.getFileExtensionFromUrl(url);
return mimeMap.getMimeTypeFromExtension(extension);
}
public static final Intent getContentByType(String mimeType) {
final Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(mimeType);
return intent;
}
}
|
Fix import in ssh connection
|
# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
################################################
import local
import paramiko_ssh
import ssh
class Connection(object):
''' Handles abstract connections to remote hosts '''
def __init__(self, runner):
self.runner = runner
def connect(self, host, port=None):
conn = None
transport = self.runner.transport
if transport == 'local':
conn = local.LocalConnection(self.runner, host)
elif transport == 'paramiko':
conn = paramiko_ssh.ParamikoConnection(self.runner, host, port)
elif transport == 'ssh':
conn = ssh.SSHConnection(self.runner, host, port)
if conn is None:
raise Exception("unsupported connection type")
return conn.connect()
|
# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
################################################
import local
import paramiko_ssh
import ssh
class Connection(object):
''' Handles abstract connections to remote hosts '''
def __init__(self, runner):
self.runner = runner
def connect(self, host, port=None):
conn = None
transport = self.runner.transport
if transport == 'local':
conn = local.LocalConnection(self.runner, host)
elif transport == 'paramiko':
conn = paramiko_ssh.ParamikoConnection(self.runner, host, port)
elif transport == 'ssh':
conn = SSHConnection(self.runner, host, port)
if conn is None:
raise Exception("unsupported connection type")
return conn.connect()
|
Update (function-list) to return a proper Desmond collection.
|
<?php
namespace Desmond\functions\core;
use Desmond\functions\DesmondFunction;
use Desmond\functions\FileOperations;
class FunctionList extends DesmondFunction
{
use \Desmond\TypeHelper;
public function id()
{
return 'function-list';
}
public function run(array $args)
{
$list = [
'define', 'let', 'do', 'if',
'lambda', 'load-file', 'eval',
'try'
];
foreach (FileOperations::getFunctionFiles() as $file) {
$class = sprintf('Desmond\\functions\\core\\%s', substr($file, 0, -4));
$function = new $class;
$list[] = $function->id();
}
return self::fromPhpType($list);
}
}
|
<?php
namespace Desmond\functions\core;
use Desmond\functions\DesmondFunction;
use Desmond\functions\FileOperations;
use Desmond\data_types\ListType;
class FunctionList extends DesmondFunction
{
public function id()
{
return 'function-list';
}
public function run(array $args)
{
$list = [
'define', 'let', 'do', 'if',
'lambda', 'load-file', 'eval',
'try'
];
foreach (FileOperations::getFunctionFiles() as $file) {
$class = sprintf('Desmond\\functions\\core\\%s', substr($file, 0, -4));
$function = new $class;
$list[] = $function->id();
}
return new ListType($list);
}
}
|
RM8864: Reset lost reason field on copy
|
/**
* Axelor Business Solutions
*
* Copyright (C) 2017 Axelor (<http://axelor.com>).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.axelor.apps.crm.db.repo;
import com.axelor.apps.crm.db.Opportunity;
public class OpportunityManagementRepository extends OpportunityRepository {
@Override
public Opportunity copy(Opportunity entity, boolean deep) {
entity.setSalesStageSelect(1);
entity.setLostReason(null);
return super.copy(entity, deep);
}
}
|
/**
* Axelor Business Solutions
*
* Copyright (C) 2017 Axelor (<http://axelor.com>).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.axelor.apps.crm.db.repo;
import com.axelor.apps.crm.db.Opportunity;
public class OpportunityManagementRepository extends OpportunityRepository {
@Override
public Opportunity copy(Opportunity entity, boolean deep) {
entity.setSalesStageSelect(1);
return super.copy(entity, deep);
}
}
|
Increase ngram size to four
|
INDEX_SETTINGS = {
"settings": {
"analysis": {
"analyzer": {
"default": {
"type": "custom",
"tokenizer": "standard",
"filter": [
"standard",
"lowercase",
"stop",
"kstem",
"ngram"
]
}
},
"filter": {
"ngram": {
"type": "ngram",
"min_gram": 4,
"max_gram": 15
}
}
}
}
}
|
INDEX_SETTINGS = {
"settings": {
"analysis": {
"analyzer": {
"default": {
"type": "custom",
"tokenizer": "standard",
"filter": [
"standard",
"lowercase",
"stop",
"kstem",
"ngram"
]
}
},
"filter": {
"ngram": {
"type": "ngram",
"min_gram": 3,
"max_gram": 15
}
}
}
}
}
|
Add more tests to YamlFile class
|
import unittest
import random
try:
from unittest import mock
except ImportError:
import mock
from conda_env import env
from conda_env.specs.yaml_file import YamlFileSpec
class TestYAMLFile(unittest.TestCase):
def test_no_environment_file(self):
spec = YamlFileSpec(name=None, filename='not-a-file')
self.assertEqual(spec.can_handle(), False)
def test_environment_file_exist(self):
with mock.patch.object(env, 'from_file', return_value={}):
spec = YamlFileSpec(name=None, filename='environment.yaml')
self.assertTrue(spec.can_handle())
def test_get_environment(self):
r = random.randint(100, 200)
with mock.patch.object(env, 'from_file', return_value=r):
spec = YamlFileSpec(name=None, filename='environment.yaml')
self.assertEqual(spec.environment, r)
def test_filename(self):
filename = "filename_{}".format(random.randint(100, 200))
with mock.patch.object(env, 'from_file') as from_file:
spec = YamlFileSpec(filename=filename)
spec.environment
from_file.assert_called_with(filename)
|
import unittest
try:
from unittest import mock
except ImportError:
import mock
from conda_env import env
from conda_env.specs.yaml_file import YamlFileSpec
class TestYAMLFile(unittest.TestCase):
def test_no_environment_file(self):
spec = YamlFileSpec(name=None, filename='not-a-file')
self.assertEqual(spec.can_handle(), False)
def test_environment_file_exist(self):
with mock.patch.object(env, 'from_file', return_value={}):
spec = YamlFileSpec(name=None, filename='environment.yaml')
self.assertTrue(spec.can_handle())
def test_get_environment(self):
with mock.patch.object(env, 'from_file', return_value={}):
spec = YamlFileSpec(name=None, filename='environment.yaml')
self.assertIsInstance(spec.environment, dict)
|
Bump version: 0.0.6 -> 0.0.7
[ci skip]
|
from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.0.7"
class ToolingCMakeUtilConan(ConanFile):
name = "tooling-cmake-util"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
requires = ("cmake-include-guard/master@smspillaz/cmake-include-guard",
"cmake-unit/master@smspillaz/cmake-unit",
"cmake-header-language/master@smspillaz/cmake-header-language")
url = "http://github.com/polysquare/tooling-cmake-util"
license = "MIT"
def source(self):
zip_name = "tooling-cmake-util.zip"
download("https://github.com/polysquare/"
"tooling-cmake-util/archive/{version}.zip"
"".format(version="v" + VERSION),
zip_name)
unzip(zip_name)
os.unlink(zip_name)
def package(self):
self.copy(pattern="*.cmake",
dst="cmake/tooling-cmake-util",
src="tooling-cmake-util-" + VERSION,
keep_path=True)
|
from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.0.6"
class ToolingCMakeUtilConan(ConanFile):
name = "tooling-cmake-util"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
requires = ("cmake-include-guard/master@smspillaz/cmake-include-guard",
"cmake-unit/master@smspillaz/cmake-unit",
"cmake-header-language/master@smspillaz/cmake-header-language")
url = "http://github.com/polysquare/tooling-cmake-util"
license = "MIT"
def source(self):
zip_name = "tooling-cmake-util.zip"
download("https://github.com/polysquare/"
"tooling-cmake-util/archive/{version}.zip"
"".format(version="v" + VERSION),
zip_name)
unzip(zip_name)
os.unlink(zip_name)
def package(self):
self.copy(pattern="*.cmake",
dst="cmake/tooling-cmake-util",
src="tooling-cmake-util-" + VERSION,
keep_path=True)
|
Change install directory for dev to mocks dir
|
var
env = process.env.NODE_ENV || 'development',
config;
config = {
production : {
db : {
URL : process.env['wac_service_mongodb_url']
},
componentsURL : 'http://50.116.26.197/components/all',
componentInstallDir : __dirname + '/components',
componentBuildDir : __dirname + '/build',
port : 80
},
development : {
db : {
URL : 'mongodb://localhost:27017/wac-service'
},
componentsURL : 'http://50.116.26.197/components/all',
componentInstallDir : __dirname + '/mocks/components',
componentBuildDir : __dirname + '/build',
port : 8000
},
test : {
db : {
URL : 'mongodb://localhost:27017/wac-service-test'
},
componentsURL : 'http://localhost:8000/mock/registry',
componentInstallDir : __dirname + '/mocks/components',
componentBuildDir : __dirname + '/test/build',
port : 8000
}
};
config = config[env];
// Helper environment methods
config.env = env;
config.isTest = env === 'test';
config.isDevelopment = env === 'development';
module.exports = config;
|
var
env = process.env.NODE_ENV || 'development',
config;
config = {
production : {
db : {
URL : process.env['wac_service_mongodb_url']
},
componentsURL : 'http://50.116.26.197/components/all',
componentInstallDir : __dirname + '/components',
componentBuildDir : __dirname + '/build',
port : 80
},
development : {
db : {
URL : 'mongodb://localhost:27017/wac-service'
},
componentsURL : 'http://50.116.26.197/components/all',
componentInstallDir : __dirname + '/components',
componentBuildDir : __dirname + '/build',
port : 8000
},
test : {
db : {
URL : 'mongodb://localhost:27017/wac-service-test'
},
componentsURL : 'http://localhost:8000/mock/registry',
componentInstallDir : __dirname + '/mocks/components',
componentBuildDir : __dirname + '/test/build',
port : 8000
}
};
config = config[env];
// Helper environment methods
config.env = env;
config.isTest = env === 'test';
config.isDevelopment = env === 'development';
module.exports = config;
|
Remove 'only' from Story tests
|
import { expect } from 'chai'
import { clean, run } from '../helper'
describe('Stories', () => {
beforeEach(clean)
it('should add stories to test cases', () => {
return run(['story']).then((results) => {
expect(results).to.have.lengthOf(1)
const result = results[0]
expect(result('ns2\\:test-suite > name').text()).to.be.equal('Suite with stories')
expect(result('test-case > name').eq(0).text()).to.be.equal('Test #1')
expect(result('test-case > name').eq(1).text()).to.be.equal('Test #2')
expect(result('test-case label[name="story"]').eq(0).attr('value')).to.be.equal('Story label for Test #1')
expect(result('test-case label[name="story"]').eq(1).attr('value')).to.be.equal('Story label for Test #2')
})
})
})
|
import { expect } from 'chai'
import { clean, run } from '../helper'
describe('Stories', () => {
beforeEach(clean)
it.only('should add stories to test cases', () => {
return run(['story']).then((results) => {
expect(results).to.have.lengthOf(1)
const result = results[0]
expect(result('ns2\\:test-suite > name').text()).to.be.equal('Suite with stories')
expect(result('test-case > name').eq(0).text()).to.be.equal('Test #1')
expect(result('test-case > name').eq(1).text()).to.be.equal('Test #2')
expect(result('test-case label[name="story"]').eq(0).attr('value')).to.be.equal('Story label for Test #1')
expect(result('test-case label[name="story"]').eq(1).attr('value')).to.be.equal('Story label for Test #2')
})
})
})
|
Check NIL channel.
This will happen if it did not yet get to starting to watch the directory.
|
package main
import (
"fmt"
"github.com/zero-boilerplate/go-api-helpers/service"
"path/filepath"
service2 "github.com/ayufan/golang-kardianos-service"
)
type app struct {
logger service2.Logger
watcherDoneChannel chan bool
}
func (a *app) OnStop() {
defer recover()
if a.watcherDoneChannel != nil {
close(a.watcherDoneChannel)
}
}
func (a *app) Run(logger service2.Logger) {
a.logger = logger
defer func() {
if r := recover(); r != nil {
a.logger.Errorf("Run app error: %s", getStringFromRecovery(r))
}
}()
userHomeDir := getUserHomeDir()
watchDir := filepath.Join(userHomeDir, ".script-watcher", "scripts")
if !doesDirExist(watchDir) {
panic(fmt.Sprintf("The watch dir '%s' does not exist", watchDir))
return
}
a.scanDirForExistingFile(watchDir)
a.startWatching(watchDir)
}
func main() {
a := &app{}
service.NewServiceRunnerBuilder("Script Watcher", a).WithOnStopHandler(a).WithServiceUserName_AsCurrentUser().Run()
}
|
package main
import (
"fmt"
"github.com/zero-boilerplate/go-api-helpers/service"
"path/filepath"
service2 "github.com/ayufan/golang-kardianos-service"
)
type app struct {
logger service2.Logger
watcherDoneChannel chan bool
}
func (a *app) OnStop() {
defer recover()
close(a.watcherDoneChannel)
}
func (a *app) Run(logger service2.Logger) {
a.logger = logger
defer func() {
if r := recover(); r != nil {
a.logger.Errorf("Run app error: %s", getStringFromRecovery(r))
}
}()
userHomeDir := getUserHomeDir()
watchDir := filepath.Join(userHomeDir, ".script-watcher", "scripts")
if !doesDirExist(watchDir) {
panic(fmt.Sprintf("The watch dir '%s' does not exist", watchDir))
return
}
a.scanDirForExistingFile(watchDir)
a.startWatching(watchDir)
}
func main() {
a := &app{}
service.NewServiceRunnerBuilder("Script Watcher", a).WithOnStopHandler(a).WithServiceUserName_AsCurrentUser().Run()
}
|
Fix unhandled rejection in test cases
|
import promisify from 'promisify-object'
import semverRegex from 'semver-regex'
const ghissues = promisify(require('ghissues'), ['createComment', 'list'])
import {logger} from '../logging'
function writeComment (authData, owner, project, pr, comment) {
return ghissues.createComment(authData, owner, project, pr, comment).then(
([comment]) => {
logger.debug('Comment added to PR#%d: %s', pr, comment.html_url)
},
(error) => {
logger.error('Error adding comment to PR#%d: %s', pr, error)
})
}
function getSemverComments (commentList) {
const commentBodies = commentList.map((comment) => comment.body)
const semverComments = commentBodies.filter((body) => semverRegex().test(body))
return semverComments
}
function checkAuthorization (authData, program) {
// Get issues to make sure GitHub authorization has been successful
return ghissues.list(authData, program.owner, program.project)
.then(() => {
logger.debug('GitHub Authorization success for user: %s', authData.user)
})
.then(() => {
return Promise.resolve(authData)
})
}
export {
checkAuthorization,
getSemverComments,
writeComment
}
|
import promisify from 'promisify-object'
import semverRegex from 'semver-regex'
const ghissues = promisify(require('ghissues'), ['createComment', 'list'])
import {logger} from '../logging'
function writeComment (authData, owner, project, pr, comment) {
return ghissues.createComment(authData, owner, project, pr, comment).then(
([comment]) => {
logger.debug('Comment added to PR#%d: %s', pr, comment.html_url)
},
(error) => {
logger.error('Error adding comment to PR#%d: %s', pr, error)
})
}
function getSemverComments (commentList) {
const commentBodies = commentList.map((comment) => comment.body)
const semverComments = commentBodies.filter((body) => semverRegex().test(body))
return semverComments
}
function checkAuthorization (authData, program) {
// Get issues to make sure GitHub authorization has been successful
const promise = ghissues.list(authData, program.owner, program.project)
promise.then(() => {
logger.debug('GitHub Authorization success for user: %s', authData.user)
})
return promise.then(() => {
return Promise.resolve(authData)
})
}
export {
checkAuthorization,
getSemverComments,
writeComment
}
|
Fix error in getting port from config
|
const express = require('express');
const morgan = require('morgan');
const compression = require('compression');
const config = require('./config');
const { generateTitle, lorem } = require('./lib/utils');
const app = express();
app.locals = Object.assign({}, app.locals, config.locals);
app.set('env', config.env);
app.set('view engine', 'pug');
app.use(compression());
app.use(morgan('dev'));
app.use('/css', express.static(config.outputDirs.stylesheets));
app.use('/img', express.static(config.outputDirs.images));
app.use('/js', express.static(config.outputDirs.scripts));
app.get('/', (req, res) => {
res.render('index');
});
app.get('/blog', (req, res) => {
const title = generateTitle(app.locals.title, 'Blog');
res.render('blog', {title});
});
app.get('/projects', (req, res) => {
const title = generateTitle(app.locals.title, 'Projects');
res.render('projects', {title});
});
if (app.get('env') === 'production') {
const server = app.listen(config.port, () => {
console.log('Starting app on port ', server.address().port);
});
} else {
app.listen(8000);
}
|
const express = require('express');
const morgan = require('morgan');
const compression = require('compression');
const config = require('./config');
const { generateTitle, lorem } = require('./lib/utils');
const app = express();
app.locals = Object.assign({}, app.locals, config.locals);
app.set('env', config.env);
app.set('view engine', 'pug');
app.use(compression());
app.use(morgan('dev'));
app.use('/css', express.static(config.outputDirs.stylesheets));
app.use('/img', express.static(config.outputDirs.images));
app.use('/js', express.static(config.outputDirs.scripts));
app.get('/', (req, res) => {
res.render('index');
});
app.get('/blog', (req, res) => {
const title = generateTitle(app.locals.title, 'Blog');
res.render('blog', {title});
});
app.get('/projects', (req, res) => {
const title = generateTitle(app.locals.title, 'Projects');
res.render('projects', {title});
});
if (app.get('env') === 'production') {
const server = app.listen(config.PORT, () => {
console.log('Starting app on port ', server.address().port);
});
} else {
app.listen(8000);
}
|
Fix for RSF-42, binding to empty String
|
/*
* Created on 13-Jan-2006
*/
package uk.org.ponder.rsf.components;
import uk.org.ponder.beanutil.BeanUtil;
/** A special class to hold EL references so they may be detected in the
* component tree. When held in this member, it is devoid of the packaging #{..}
* characters - they are removed and replaced by the parser in transit from
* XML form.
* @author Antranig Basman (amb26@ponder.org.uk)
*
*/
// TODO: in RSF 0.8 this class will be deprecated in favour of the version
// in PUC.
public class ELReference {
public ELReference() {}
public ELReference(String value) {
String stripped = BeanUtil.stripEL(value);
this.value = stripped == null? value : stripped;
if ("".equals(value)) {
throw new IllegalArgumentException(
"Cannot issue an EL reference to an empty path. For an empty binding please either supply null, or else provide a non-empty String as path");
}
}
public String value;
public static ELReference make(String value) {
return value == null? null : new ELReference(value);
}
}
|
/*
* Created on 13-Jan-2006
*/
package uk.org.ponder.rsf.components;
import uk.org.ponder.beanutil.BeanUtil;
/** A special class to hold EL references so they may be detected in the
* component tree. When held in this member, it is devoid of the packaging #{..}
* characters - they are removed and replaced by the parser in transit from
* XML form.
* @author Antranig Basman (amb26@ponder.org.uk)
*
*/
// TODO: in RSF 0.8 this class will be deprecated in favour of the version
// in PUC.
public class ELReference {
public ELReference() {}
public ELReference(String value) {
String stripped = BeanUtil.stripEL(value);
this.value = stripped == null? value : stripped;
}
public String value;
public static ELReference make(String value) {
return value == null? null : new ELReference(value);
}
}
|
Add concepts to parser-spi's requires
This is another tiny change for Eclipse's sake.
Change-Id: I2d50dedf232d63456f3574bc1f025f92d558a736
Signed-off-by: Robert Varga <91ae5aa8c7a9f7e57b701db766e23e544aaa6ae9@pantheon.tech>
|
/*
* Copyright (c) 2020 PANTHEON.tech, s.r.o. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
module org.opendaylight.yangtools.yang.parser.spi {
exports org.opendaylight.yangtools.yang.parser.spi;
exports org.opendaylight.yangtools.yang.parser.spi.meta;
exports org.opendaylight.yangtools.yang.parser.spi.source;
exports org.opendaylight.yangtools.yang.parser.spi.validation;
requires transitive org.opendaylight.yangtools.yang.model.api;
requires com.google.common;
requires org.opendaylight.yangtools.concepts;
requires org.opendaylight.yangtools.yang.common;
requires org.slf4j;
// Annotations
requires static com.github.spotbugs.annotations;
requires static org.eclipse.jdt.annotation;
}
|
/*
* Copyright (c) 2020 PANTHEON.tech, s.r.o. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
module org.opendaylight.yangtools.yang.parser.spi {
exports org.opendaylight.yangtools.yang.parser.spi;
exports org.opendaylight.yangtools.yang.parser.spi.meta;
exports org.opendaylight.yangtools.yang.parser.spi.source;
exports org.opendaylight.yangtools.yang.parser.spi.validation;
requires transitive org.opendaylight.yangtools.yang.model.api;
requires com.google.common;
requires org.opendaylight.yangtools.yang.common;
requires org.slf4j;
// Annotations
requires static com.github.spotbugs.annotations;
requires static org.eclipse.jdt.annotation;
}
|
Add new tracking methods to API
|
/*-
* Copyright 2015 Diamond Light Source Ltd.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.dawnsci.analysis.api;
public interface EventTracker {
/**
* This method is used to track events (log, action, exception etc) in the application.
*
* @param name
* Name of event to be tracked
* @throws Exception
*/
public void track(String name) throws Exception;
/**
* This method is used to track events from extension points given by their id and label
*
* @param id
* Unique id
* @param label
* Name
*/
public void track(String id, String label) throws Exception;
/**
* This method is used to track tool creation events given a tool name. It will track the event name with the prefix
* "/Tool/"
*
* @param name
* @throws Exception
*/
public void trackToolEvent(String name) throws Exception;
/**
* This method is used to track perspective launch events given a perspective name. It will track the event name
* with the prefix "/perspective/".
*
* @param name
* @throws Exception
*/
public void trackPerspectiveEvent(String name) throws Exception;
/**
* This method is used to track action events like a user click on a "run" button given the action's name. It will
* track the event name with the prefix "/Action/".
*
* @param name
* @throws Exception
*/
public void trackActionEvent(String name) throws Exception;
}
|
/*-
* Copyright 2015 Diamond Light Source Ltd.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.dawnsci.analysis.api;
public interface EventTracker {
/**
* This method is used to track events (log, action, exception etc) in the application.
*
* @param name
* Name of event to be tracked
* @throws Exception
*/
public void track(String name) throws Exception;
/**
* This method is used to track events from extension points given by their id and label
*
* @param id
* Unique id
* @param label
* Name
*/
public void track(String id, String label) throws Exception;
}
|
Convert md to rst readme specially for PyPi
|
from distutils.core import setup
with open('README.md') as readme:
with open('HISTORY.md') as history:
long_description = readme.read() + '\n\n' + history.read()
try:
import pypandoc
long_description = pypandoc.convert(long_description, 'rst')
except(IOError, ImportError):
long_description = long_description
VERSION = '1.0.1'
setup(
name='argparse-autogen',
py_modules=['argparse_autogen'],
version=VERSION,
url='https://github.com/sashgorokhov/argparse-autogen',
download_url='https://github.com/sashgorokhov/argparse-autogen/archive/v%s.zip' % VERSION,
keywords=['python', 'argparse', 'generate'],
classifiers=[],
long_description=long_description,
license='MIT License',
author='sashgorokhov',
author_email='sashgorokhov@gmail.com',
description="Parser with automatic creation of parsers and subparsers for paths.",
)
|
from distutils.core import setup
with open('README.md') as readme:
with open('HISTORY.md') as history:
long_description = readme.read() + '\n\n' + history.read()
VERSION = '1.0'
setup(
name='argparse-autogen',
py_modules=['argparse_autogen'],
version=VERSION,
url='https://github.com/sashgorokhov/argparse-autogen',
download_url='https://github.com/sashgorokhov/argparse-autogen/archive/v%s.zip' % VERSION,
keywords=['python', 'argparse', 'generate'],
classifiers=[],
long_description=long_description,
license='MIT License',
author='sashgorokhov',
author_email='sashgorokhov@gmail.com',
description="Parser with automatic creation of parsers and subparsers for paths.",
)
|
Fix bug on create a new application
|
<?php
Part::input($controller, 'Controller');
Part::input($objects, 'ModelSet');
Part::input($columns, 'int', 4);
$count = $objects->count();
$perColumn = ceil($count / $columns);
echo '<table>';
for($row = 0 ; $row < $perColumn ; $row++) {
echo '<tr>';
for($col = 0 ; $col < $columns ; $col++) {
$object = isset($objects[$perColumn*$col+$row]) ? $objects[$perColumn*$col+$row] : '';
$value = is_object($object) ? $object->name : '';
if($object instanceof RecessReflectorClass && $object->getPackage() != null) {
$prefix = $object->getPackage()->name . '.';
$linkTo = 'class';
} else {
$prefix = '';
$linkTo = 'package';
}
//$linkTo = get_class($object) == 'RecessReflectorClass' ? 'class' : 'package';
echo '<td><a href="', $controller->urlTo($linkTo . 'Info', $prefix . $value),'">', $value, '</a></td>';
}
echo '</tr>';
}
echo '</table>';
?>
|
<?php
Part::input($controller, 'Controller');
Part::input($objects, 'ModelSet');
Part::input($columns, 'int', 4);
$count = $objects->count();
$perColumn = ceil($count / $columns);
echo '<table>';
for($row = 0 ; $row < $perColumn ; $row++) {
echo '<tr>';
for($col = 0 ; $col < $columns ; $col++) {
$object = isset($objects[$perColumn*$col+$row]) ? $objects[$perColumn*$col+$row] : '';
$value = is_object($object) ? $object->name : '';
if($object instanceof RecessReflectorClass && $object->package() != null) {
$prefix = $object->package()->name . '.';
$linkTo = 'class';
} else {
$prefix = '';
$linkTo = 'package';
}
//$linkTo = get_class($object) == 'RecessReflectorClass' ? 'class' : 'package';
echo '<td><a href="', $controller->urlTo($linkTo . 'Info', $prefix . $value),'">', $value, '</a></td>';
}
echo '</tr>';
}
echo '</table>';
?>
|
Fix multiple bug IDs on presubmit.
BUG=#1212
TBR=nduca@chromium.org
Review URL: https://codereview.chromium.org/1282273002
|
# Copyright (c) 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import re
def CheckChangeLogBug(input_api, output_api):
if input_api.change.BUG is None or re.match(
'(\#\d+)(,\s*\#\d+)*$', input_api.change.BUG):
return []
err = output_api.PresubmitError(
('Invalid bug "%s". BUG= should either not be present or start with # '
'for a github issue.' % input_api.change.BUG))
return [err]
def RunChecks(input_api, output_api, excluded_paths):
results = []
results += input_api.canned_checks.PanProjectChecks(
input_api, output_api, excluded_paths=excluded_paths)
results += input_api.canned_checks.RunPylint(
input_api, output_api, black_list=excluded_paths)
results += CheckChangeLogBug(input_api, output_api)
return results
|
# Copyright (c) 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import re
def CheckChangeLogBug(input_api, output_api):
if input_api.change.BUG is None or re.match('\#\d+$', input_api.change.BUG):
return []
err = output_api.PresubmitError(
('Invalid bug "%s". BUG= should either not be present or start with # '
'for a github issue.' % input_api.change.BUG))
return [err]
def RunChecks(input_api, output_api, excluded_paths):
results = []
results += input_api.canned_checks.PanProjectChecks(
input_api, output_api, excluded_paths=excluded_paths)
results += input_api.canned_checks.RunPylint(
input_api, output_api, black_list=excluded_paths)
results += CheckChangeLogBug(input_api, output_api)
return results
|
Fix user and attempts sqlalchemia request.
|
# Copyright 2016 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from flask import Blueprint, render_template, request, session
from flask_login import login_required
from qa_app.models import Users, Attempts
views = Blueprint('views', __name__)
@views.before_request
def redirect_setup():
if request.path.startswith("/static"):
return
@views.route('/')
def index():
return render_template("index.html", page="Home")
@views.route('/profile')
@login_required
def profile():
user = Users.query.filter_by(email=session['email']).first()
attempts = Attempts.query.filter_by(user_id=user.id).all()
return render_template("profile.html", page="Profile", user=user, attempts=attempts)
|
# Copyright 2016 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from flask import Blueprint, render_template, request, session
from flask_login import login_required
from qa_app.models import Users, Attempts
views = Blueprint('views', __name__)
@views.before_request
def redirect_setup():
if request.path.startswith("/static"):
return
@views.route('/')
def index():
return render_template("index.html", page="Home")
@views.route('/profile')
@login_required
def profile():
user = Users.query(email=session['email']).first()
attempts = Attempts.query(user_id=user.id).all()
return render_template("profile.html", page="Profile", user=user, attempts=attempts)
|
Convert squashed migration to regular migration
This confuses the hell out of me every time
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.contrib.gis.db.models.fields
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Address',
fields=[
('uprn', models.CharField(primary_key=True, max_length=100, serialize=False)),
('address', models.TextField(blank=True)),
('postcode', models.CharField(db_index=True, max_length=15, blank=True)),
('location', django.contrib.gis.db.models.fields.PointField(null=True, srid=4326, blank=True)),
],
),
]
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.contrib.gis.db.models.fields
class Migration(migrations.Migration):
replaces = [('addressbase', '0001_initial'), ('addressbase', '0002_auto_20160611_1700'), ('addressbase', '0003_auto_20160611_2130'), ('addressbase', '0004_auto_20160611_2304'), ('addressbase', '0005_auto_20160612_0904')]
dependencies = [
]
operations = [
migrations.CreateModel(
name='Address',
fields=[
('uprn', models.CharField(primary_key=True, max_length=100, serialize=False)),
('address', models.TextField(blank=True)),
('postcode', models.CharField(db_index=True, max_length=15, blank=True)),
('location', django.contrib.gis.db.models.fields.PointField(null=True, srid=4326, blank=True)),
],
),
]
|
Make a correction to how the event link is created
|
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.apache.tapestry5.integration.app1.pages;
import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.Link;
import org.apache.tapestry5.PersistenceConstants;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.ioc.annotations.Inject;
public class ActionViaLinkDemo
{
@Persist(PersistenceConstants.FLASH)
private String message;
@Inject
private ComponentResources resources;
Object[]
onPassivate()
{
return new Object[]{};
}
public String getMessage()
{
return message;
}
void onUpdateMessage(String message)
{
this.message = message;
}
public String getActionURL()
{
Link link = resources.createEventLink("UpdateMessage", "from getActionURL()");
return link.toURI();
}
}
|
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.apache.tapestry5.integration.app1.pages;
import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.Link;
import org.apache.tapestry5.PersistenceConstants;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.ioc.annotations.Inject;
public class ActionViaLinkDemo
{
@Persist(PersistenceConstants.FLASH)
private String message;
@Inject
private ComponentResources resources;
Object[]
onPassivate()
{
return new Object[] { };
}
public String getMessage()
{
return message;
}
void onUpdateMessage(String message)
{
getActionURL();
this.message = message;
}
public String getActionURL()
{
Link link = resources.createEventLink("UpdateMessage", false, "from getActionURL()");
return link.toURI();
}
}
|
Speed up account creation by lowering password security
Reduce saltRounds to 8 saves ~50ms per password hash generation.
|
var bcrypt = require('bcrypt');
var mongoose = require('mongoose');
const saltRounds = 8;
var userSchema = new mongoose.Schema({
signupDate: { type: Date, default: Date.now },
username: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
name: { type: String }
});
userSchema.pre('save', function(next) {
if (!this.isModified('password')) {
return next();
}
bcrypt.hash(this.password, saltRounds, function(err, hash) {
if (err) {
console.log(err);
return next(err);
}
this.password = hash;
next();
}.bind(this));
});
userSchema.methods.checkPassword = function(password, cb) {
bcrypt.compare(password, this.password, function(err, result) {
if (err) {
console.log(err);
return next(err);
}
cb(result);
});
};
module.exports = mongoose.model('User', userSchema);
|
var bcrypt = require('bcrypt');
var mongoose = require('mongoose');
const saltRounds = 10;
var userSchema = new mongoose.Schema({
signupDate: { type: Date, default: Date.now },
username: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
name: { type: String }
});
userSchema.pre('save', function(next) {
if (!this.isModified('password')) {
return next();
}
bcrypt.hash(this.password, saltRounds, function(err, hash) {
if (err) {
console.log(err);
return next(err);
}
this.password = hash;
next();
}.bind(this));
});
userSchema.methods.checkPassword = function(password, cb) {
bcrypt.compare(password, this.password, function(err, result) {
if (err) {
console.log(err);
return next(err);
}
cb(result);
});
};
module.exports = mongoose.model('User', userSchema);
|
Remove 'Or Login with' text from the list view. Make it more reusable.
|
@unless(Butler::providers()->isEmpty())
<div class="row">
<div class="col-sm-4 col-sm-offset-4 text-center">
@foreach (\Butler::providers() as $code => $details)
<a href="{{ route('butler.redirect', $code) }}" class="btn btn-default btn-block {{ $details->class }}">
@if ($details->icon)
<i class="{{ $details->icon }}"></i>
@endif
{{ $details->name }}
</a>
@endforeach
</div>
</div>
@endunless
|
@unless(Butler::providers()->isEmpty())
<div class="row">
<div class="col-sm-4 col-sm-offset-4 text-center">
<h4>Or, login with</h4>
@foreach (\Butler::providers() as $code => $details)
<a href="{{ route('butler.redirect', $code) }}" class="btn btn-default btn-block {{ $details->class }}">
@if ($details->icon)
<i class="{{ $details->icon }}"></i>
@endif
{{ $details->name }}
</a>
@endforeach
</div>
</div>
@endunless
|
Fix prefix for windows azure
|
var path = require('path');
module.exports = function (start, opts) {
var modules = opts.moduleDirectory || 'node_modules';
var prefix = '/';
if (/^([A-Za-z]:)/.test(start)) {
prefix = '';
} else if (/^\\\\/.test(start)) {
prefix = '\\\\';
}
var splitRe = process.platform === 'win32' ? /[\/\\]/ : /\/+/;
var parts = start.split(splitRe);
var dirs = [];
for (var i = parts.length - 1; i >= 0; i--) {
if (parts[i] === modules) continue;
var dir = path.join(
path.join.apply(path, parts.slice(0, i + 1)),
modules
);
dirs.push(prefix + dir);
}
return dirs.concat(opts.paths);
}
|
var path = require('path');
module.exports = function (start, opts) {
var modules = opts.moduleDirectory || 'node_modules';
var splitRe = process.platform === 'win32' ? /[\/\\]/ : /\/+/;
var parts = start.split(splitRe);
var dirs = [];
for (var i = parts.length - 1; i >= 0; i--) {
if (parts[i] === modules) continue;
var dir = path.join(
path.join.apply(path, parts.slice(0, i + 1)),
modules
);
if (!parts[0].match(/([A-Za-z]:)/)) {
dir = '/' + dir;
}
dirs.push(dir);
}
return dirs.concat(opts.paths);
}
|
[MIG] Change the version of module.
|
# -*- coding: utf-8 -*-
# Copyright (C) 2009 Renato Lima - Akretion
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
'name': 'Brazilian Localisation ZIP Codes',
'license': 'AGPL-3',
'author': 'Akretion, Odoo Community Association (OCA)',
'version': '9.0.1.0.0',
'depends': [
'l10n_br_base',
],
'data': [
'views/l10n_br_zip_view.xml',
'views/res_partner_view.xml',
'views/res_company_view.xml',
'views/res_bank_view.xml',
'wizard/l10n_br_zip_search_view.xml',
'security/ir.model.access.csv',
],
'test': [
'test/zip_demo.yml'
],
'category': 'Localization',
'installable': True,
}
|
# -*- coding: utf-8 -*-
# Copyright (C) 2009 Renato Lima - Akretion
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
'name': 'Brazilian Localisation ZIP Codes',
'license': 'AGPL-3',
'author': 'Akretion, Odoo Community Association (OCA)',
'version': '8.0.1.0.1',
'depends': [
'l10n_br_base',
],
'data': [
'views/l10n_br_zip_view.xml',
'views/res_partner_view.xml',
'views/res_company_view.xml',
'views/res_bank_view.xml',
'wizard/l10n_br_zip_search_view.xml',
'security/ir.model.access.csv',
],
'test': ['test/zip_demo.yml'],
'category': 'Localization',
'installable': False,
}
|
Add a comment to custom yaml_safe_load() method.
|
# Copyright 2020 The StackStorm Authors.
# Copyright 2019 Extreme Networks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
import yaml
try:
from yaml import CSafeLoader as YamlSafeLoader
except ImportError:
from yaml import SafeLoader as YamlSafeLoader
__all__ = ["ALLOWED_EXTS", "PARSER_FUNCS"]
# NOTE: We utilize CSafeLoader if available since it uses C extensions and is faster.
#
# SafeLoader / CSafeLoader are both safe to use and don't allow loading arbitrary Python objects.
#
# That's the actual class which is used internally by ``yaml.safe_load()``, but we can't use that
# method directly since we want to use C extension if available (CSafeLoader) for faster parsing.
#
# See pyyaml docs for details https://pyyaml.org/wiki/PyYAMLDocumentation
def yaml_safe_load(stream):
return yaml.load(stream, Loader=YamlSafeLoader)
ALLOWED_EXTS = [".yaml", ".yml"]
PARSER_FUNCS = {".yml": yaml_safe_load, ".yaml": yaml_safe_load}
|
# Copyright 2020 The StackStorm Authors.
# Copyright 2019 Extreme Networks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
import yaml
try:
from yaml import CSafeLoader as YamlSafeLoader
except ImportError:
from yaml import SafeLoader as YamlSafeLoader
__all__ = ["ALLOWED_EXTS", "PARSER_FUNCS"]
# NOTE: We utilize CSafeLoader if available since it uses C extensions and is faster.
def yaml_safe_load(stream):
return yaml.load(stream, Loader=YamlSafeLoader)
ALLOWED_EXTS = [".yaml", ".yml"]
PARSER_FUNCS = {".yml": yaml_safe_load, ".yaml": yaml_safe_load}
|
Add new Stripe webhook config values
See https://github.com/laravel/cashier/pull/565
|
<?php
return [
/*
|--------------------------------------------------------------------------
| Third Party Services
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Stripe, Mailgun, SparkPost and others. This file provides a sane
| default location for this type of information, allowing packages
| to have a conventional place to find your various credentials.
|
*/
'mailgun' => [
'domain' => env('MAILGUN_DOMAIN'),
'secret' => env('MAILGUN_SECRET'),
],
'ses' => [
'key' => env('SES_KEY'),
'secret' => env('SES_SECRET'),
'region' => env('SES_REGION', 'us-east-1'),
],
'sparkpost' => [
'secret' => env('SPARKPOST_SECRET'),
],
'stripe' => [
'model' => App\User::class,
'key' => env('STRIPE_KEY'),
'secret' => env('STRIPE_SECRET'),
'webhook' => [
'secret' => env('STRIPE_WEBHOOK_SECRET'),
'tolerance' => env('STRIPE_WEBHOOK_TOLERANCE', 300),
],
],
];
|
<?php
return [
/*
|--------------------------------------------------------------------------
| Third Party Services
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Stripe, Mailgun, SparkPost and others. This file provides a sane
| default location for this type of information, allowing packages
| to have a conventional place to find your various credentials.
|
*/
'mailgun' => [
'domain' => env('MAILGUN_DOMAIN'),
'secret' => env('MAILGUN_SECRET'),
],
'ses' => [
'key' => env('SES_KEY'),
'secret' => env('SES_SECRET'),
'region' => env('SES_REGION', 'us-east-1'),
],
'sparkpost' => [
'secret' => env('SPARKPOST_SECRET'),
],
'stripe' => [
'model' => App\User::class,
'key' => env('STRIPE_KEY'),
'secret' => env('STRIPE_SECRET'),
],
];
|
Use new currentActionSet in async
|
import fetch from 'isomorphic-fetch';
export function invalidateReddit({ reddit }) {}
export function requestPosts({ reddit }) {}
export function receivePosts({ reddit, json }) {
return {
reddit,
posts: json.data.children.map(child => child.data),
receivedAt: Date.now()
};
}
function fetchPosts({ reddit }, { currentActionSet }) {
currentActionSet.requestPosts({ reddit });
fetch(`http://www.reddit.com/r/${reddit}.json`)
.then(response => response.json())
.then(json => currentActionSet.receivePosts({ reddit, json }))
;
}
export const introspection = {
shouldFetchPosts({ reddit }) {
return arguments[0];
}
}
export function fetchPostsIfNeeded({ reddit }, { currentActionSet, getConsensus }) {
if (getConsensus({
introspectionID: 'shouldFetchPosts',
payload: { reddit },
booleanOr: true
})) {
fetchPosts({ reddit }, { currentActionSet });
};
}
|
import fetch from 'isomorphic-fetch';
export function invalidateReddit({ reddit }) {
return arguments[0];
}
function requestPosts({ reddit }) {
return arguments[0];
}
function receivePosts({ reddit, json }) {
return {
reddit,
posts: json.data.children.map(child => child.data),
receivedAt: Date.now()
};
}
function fetchPosts({ reddit }, { dispatch }) {
dispatch({
actionID: 'requestPosts',
payload: requestPosts({ reddit })
});
fetch(`http://www.reddit.com/r/${reddit}.json`)
.then(response => response.json())
.then(json => dispatch({
actionID: 'receivePosts',
payload: receivePosts({ reddit, json })
}));
}
export const introspection = {
shouldFetchPosts({ reddit }) {
return arguments[0];
}
}
export function fetchPostsIfNeeded({ reddit }, { dispatch, getConsensus }) {
if (getConsensus({
introspectionID: 'shouldFetchPosts',
payload: { reddit },
booleanOr: true
})) {
//currentActionSet.fetchPosts({ reddit });
fetchPosts({ reddit }, { dispatch });
};
}
|
Fix some code style idiosyncrasies
|
'use strict';
const Fs = require('fs');
const Hoek = require('hoek');
const Thurston = require('thurston');
const Items = require('items');
const Some = require('lodash.some');
const internals = {
defaults: {
pattern: ['bytes', 'filename', 'headers', 'path']
}
};
internals.validate = function (payload, cache) {
const keys = internals.defaults.pattern;
return function (item, next) {
if (!(Hoek.contain(payload[item], keys))) {
return next();
}
cache[item] = Fs.createReadStream(payload[item].path, { start: 0, end: 2 });
next();
};
};
exports.validate = function (payload, options, next) {
const keys = internals.defaults.pattern;
if (!Some(payload, (v) => Hoek.contain(v, keys))) {
return next();
}
const items = Object.keys(payload);
const res = {};
const iterator = internals.validate(payload, res);
Items.serial(items, iterator, () => {
Thurston.validate(res, options, (err) => {
if (err) {
return next(err);
}
next(null, payload);
});
});
};
|
'use strict';
const Fs = require('fs');
const Hoek = require('hoek');
const Thurston = require('thurston');
const Items = require('items');
const Some = require('lodash.some');
const internals = {
defaults: {
pattern: ['bytes', 'filename', 'headers', 'path']
}
};
internals.validate = function (payload, cache) {
const keys = internals.defaults.pattern;
return function (item, next) {
if (!(Hoek.contain(payload[item], keys))) {
return next();
}
cache[item] = Fs.createReadStream(payload[item].path, { start: 0, end: 2 });
next();
};
};
exports.validate = function (payload, options, next) {
const keys = internals.defaults.pattern;
if (!Some(payload, (v) => Hoek.contain(v, keys))) {
return next();
}
const items = Object.keys(payload);
const res = {};
const iterator = internals.validate(payload, res);
Items.serial(items, iterator, () => {
Thurston.validate(res, options, (err) => {
if (err) {
return next(err);
}
return next(null, payload);
});
});
};
|
Upgrade libchromiumcontent to loose iframe sandbox.
|
#!/usr/bin/env python
import platform
import sys
NODE_VERSION = 'v0.11.13'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = 'afb4570ceee2ad10f3caf5a81335a2ee11ec68a5'
ARCH = {
'cygwin': '32bit',
'darwin': '64bit',
'linux2': platform.architecture()[0],
'win32': '32bit',
}[sys.platform]
DIST_ARCH = {
'32bit': 'ia32',
'64bit': 'x64',
}[ARCH]
TARGET_PLATFORM = {
'cygwin': 'win32',
'darwin': 'darwin',
'linux2': 'linux',
'win32': 'win32',
}[sys.platform]
|
#!/usr/bin/env python
import platform
import sys
NODE_VERSION = 'v0.11.13'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = '432720d4613e3aac939f127fe55b9d44fea349e5'
ARCH = {
'cygwin': '32bit',
'darwin': '64bit',
'linux2': platform.architecture()[0],
'win32': '32bit',
}[sys.platform]
DIST_ARCH = {
'32bit': 'ia32',
'64bit': 'x64',
}[ARCH]
TARGET_PLATFORM = {
'cygwin': 'win32',
'darwin': 'darwin',
'linux2': 'linux',
'win32': 'win32',
}[sys.platform]
|
Add missing typehint on chain sender
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Messenger\Transport;
use Symfony\Component\Messenger\Envelope;
/**
* @author Tobias Schultze <http://tobion.de>
*/
class ChainSender implements SenderInterface
{
private $senders;
/**
* @param SenderInterface[] $senders
*/
public function __construct(iterable $senders)
{
$this->senders = $senders;
}
/**
* {@inheritdoc}
*/
public function send(Envelope $message): void
{
foreach ($this->senders as $sender) {
$sender->send($message);
}
}
}
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Messenger\Transport;
/**
* @author Tobias Schultze <http://tobion.de>
*/
class ChainSender implements SenderInterface
{
private $senders;
/**
* @param SenderInterface[] $senders
*/
public function __construct(iterable $senders)
{
$this->senders = $senders;
}
/**
* {@inheritdoc}
*/
public function send($message): void
{
foreach ($this->senders as $sender) {
$sender->send($message);
}
}
}
|
Fix for [ticket:281]. Do not forward livebookmarks request.
git-svn-id: 87d19257dd11500985d055ec4730e446075a5f07@1261 78c7df6f-8922-0410-bcd3-9426b1ad491b
|
# Copyright (c) 2006-2007 Open Source Applications Foundation
# Copyright (c) 2008-2009 Mikeal Rogers <mikeal.rogers@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.
import wsgi, convergence
forwarding_conditions = [
lambda e : 'google.com/safebrowsing/downloads' not in e['reconstructed_url'],
lambda e : 'mozilla.org/en-US/firefox/livebookmarks.html' not in e['reconstructed_url'],
]
def add_forward_condition(condition):
forwarding_conditions.append(condition)
def remove_forward_condition(condition):
while condition in forwarding_conditions:
forwarding_conditions.remove(condition)
|
# Copyright (c) 2006-2007 Open Source Applications Foundation
# Copyright (c) 2008-2009 Mikeal Rogers <mikeal.rogers@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.
import wsgi, convergence
forwarding_conditions = [lambda e : 'google.com/safebrowsing/downloads' not in e['reconstructed_url']]
def add_forward_condition(condition):
forwarding_conditions.append(condition)
def remove_forward_condition(condition):
while condition in forwarding_conditions:
forwarding_conditions.remove(condition)
|
Replace str_contains with strpos method to support PHP 7
|
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Bundle\ShopBundle\SectionResolver;
use Sylius\Bundle\CoreBundle\SectionResolver\SectionInterface;
use Sylius\Bundle\CoreBundle\SectionResolver\UriBasedSectionResolverInterface;
final class ShopUriBasedSectionResolver implements UriBasedSectionResolverInterface
{
/** @var string */
private $shopCustomerAccountUri;
public function __construct(string $shopCustomerAccountUri = 'account')
{
$this->shopCustomerAccountUri = $shopCustomerAccountUri;
}
public function getSection(string $uri): SectionInterface
{
if (strpos($uri, $this->shopCustomerAccountUri) !== false) {
return new ShopCustomerAccountSubSection();
}
return new ShopSection();
}
}
|
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Bundle\ShopBundle\SectionResolver;
use Sylius\Bundle\CoreBundle\SectionResolver\SectionInterface;
use Sylius\Bundle\CoreBundle\SectionResolver\UriBasedSectionResolverInterface;
final class ShopUriBasedSectionResolver implements UriBasedSectionResolverInterface
{
/** @var string */
private $shopCustomerAccountUri;
public function __construct(string $shopCustomerAccountUri = 'account')
{
$this->shopCustomerAccountUri = $shopCustomerAccountUri;
}
public function getSection(string $uri): SectionInterface
{
if (str_contains($uri, $this->shopCustomerAccountUri)) {
return new ShopCustomerAccountSubSection();
}
return new ShopSection();
}
}
|
Fix missing id of project in discussion of activities
|
/*****************************************************************************/
/* ActivityDiscuss: Event Handlers */
/*****************************************************************************/
Template.ActivityDiscuss.events({
});
/*****************************************************************************/
/* ActivityDiscuss: Helpers */
/*****************************************************************************/
Template.ActivityDiscuss.helpers({
thisRoomId: function() {
return thisProject._id + '-' + thisActivity.id;
},
thisUsername: function() {
return Meteor.user().username;
},
thisName: function() {
var name = Meteor.user().profile.firstName + ' ' + Meteor.user().profile.lastName;
return name;
},
thisGravatar: function() {
var url = Gravatar.imageUrl(Meteor.user().emails[0].address, {
size: 34,
default: 'mm'
});
return url;
}
});
/*****************************************************************************/
/* ActivityDiscuss: Lifecycle Hooks */
/*****************************************************************************/
Template.ActivityDiscuss.onCreated(function () {
});
Template.ActivityDiscuss.onRendered(function () {
});
Template.ActivityDiscuss.onDestroyed(function () {
});
|
/*****************************************************************************/
/* ActivityDiscuss: Event Handlers */
/*****************************************************************************/
Template.ActivityDiscuss.events({
});
/*****************************************************************************/
/* ActivityDiscuss: Helpers */
/*****************************************************************************/
Template.ActivityDiscuss.helpers({
thisRoomId: function() {
return this.project + '-' + thisActivity.id;
},
thisUsername: function() {
return Meteor.user().username;
},
thisName: function() {
var name = Meteor.user().profile.firstName + ' ' + Meteor.user().profile.lastName;
return name;
},
thisGravatar: function() {
var url = Gravatar.imageUrl(Meteor.user().emails[0].address, {
size: 34,
default: 'mm'
});
return url;
}
});
/*****************************************************************************/
/* ActivityDiscuss: Lifecycle Hooks */
/*****************************************************************************/
Template.ActivityDiscuss.onCreated(function () {
});
Template.ActivityDiscuss.onRendered(function () {
});
Template.ActivityDiscuss.onDestroyed(function () {
});
|
Remove _k parameter from url. This is used for old browsers.
|
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.js';
import Home from './components/Home';
import Programs from './components/Programs';
import Program from './components/Program';
import Login from './components/Login';
import Register from './components/Register';
import { Router, Route, IndexRoute } from 'react-router';
import auth from './auth';
import createHistory from 'history/lib/createHashHistory';
let history = createHistory({
queryKey: false
});
const requireAuth = (nextState, replaceState) => {
if (!auth.loggedIn()) {
replaceState({ nextPathname: nextState.location.pathname }, '/login');
}
};
ReactDOM.render(
<Router history={history}>
<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="programs" component={Programs} onEnter={requireAuth} />
<Route path="programs/:id" component={Program} />
<Route path="login" component={Login} />
<Route path="register" component={Register} />
</Route>
</Router>
, document.getElementById('root')
);
|
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.js';
import Home from './components/Home';
import Programs from './components/Programs';
import Program from './components/Program';
import Login from './components/Login';
import Register from './components/Register';
import { Router, Route, browserHistory, IndexRoute } from 'react-router';
import auth from './auth';
const requireAuth = (nextState, replaceState) => {
if (!auth.loggedIn()) {
replaceState({ nextPathname: nextState.location.pathname }, '/login');
}
};
ReactDOM.render(
<Router history={browserHistory}>
<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="programs" component={Programs} onEnter={requireAuth} />
<Route path="programs/:id" component={Program} />
<Route path="login" component={Login} />
<Route path="register" component={Register} />
</Route>
</Router>
, document.getElementById('root')
);
|
Replace hardcoded coordinates with randomly generated values
|
import Prop from 'props/prop';
import canvas from 'canvas';
import collision from 'lib/collision';
import events from 'lib/events';
export default class Ball extends Prop {
constructor() {
const width = 10;
const height = 10;
const x = (canvas.width / 2) - (width / 2);
const y = (canvas.height / 2) - (height / 2);
super(x, y, width, height);
this.speed = 2;
this.createRandomDirection();
console.log('this.direction', this.direction);
}
createRandomDirection() {
// Generate random number from -3 - 3, not including 0.
function create() {
const number = Math.floor(Math.random() * 3) + 1;
const positive = !!Math.round(Math.random());
return positive ? number : -(number);
}
this.direction = {
x: create(),
y: create(),
};
}
rebound() {
const calculate = (num) => num <= 0 ? Math.abs(num) : -(num);
this.direction.x = calculate(this.direction.x);
this.direction.y = calculate(this.direction.y);
}
fire() {
const move = () => {
this.move(this.direction.x, this.direction.y);
events.publish('ballMove', this);
if (!collision.isOutOfBounds(this)) {
return requestAnimationFrame(move);
}
};
requestAnimationFrame(move);
}
}
|
import Prop from 'props/prop';
import canvas from 'canvas';
import collision from 'lib/collision';
import events from 'lib/events';
// Maybe make these coords an array so we can easily multiply without lodash _.mapValues for speed.
const coords = {
northEast: {
x: 1,
y: -1,
},
southEast: {
x: 1,
y: 1,
},
southWest: {
x: -1,
y: 1,
},
northWest: {
x: -1,
y: -1,
},
};
export default class Ball extends Prop {
constructor() {
const width = 10;
const height = 10;
const x = (canvas.width / 2) - (width / 2);
const y = (canvas.height / 2) - (height / 2);
super(x, y, width, height);
this.speed = 2;
this.direction = coords.northWest;
}
rebound() {
const calculate = (num) => num <= 0 ? Math.abs(num) : -(num);
this.direction.x = calculate(this.direction.x);
this.direction.y = calculate(this.direction.y);
}
fire() {
const move = () => {
this.move(this.direction.x, this.direction.y);
events.publish('ballMove', this);
if (!collision.isOutOfBounds(this)) {
return requestAnimationFrame(move);
}
};
requestAnimationFrame(move);
}
}
|
Access weights using new interface.
|
#!/usr/bin/env python
import climate
import matplotlib.pyplot as plt
import theanets
from utils import load_cifar, plot_layers, plot_images
g = climate.add_arg_group('CIFAR Example')
g.add_argument('--features', type=int, default=32, metavar='N',
help='train a model using N^2 hidden-layer features')
def main(args):
train, valid, _ = load_cifar()
e = theanets.Experiment(
theanets.Autoencoder,
layers=(3072, args.features ** 2, 3072))
e.train(train, valid)
plot_layers([e.network.get_weights(1), e.network.get_weights('out')], channels=3)
plt.tight_layout()
plt.show()
valid = valid[:100]
plot_images(valid, 121, 'Sample data', channels=3)
plot_images(e.network.predict(valid), 122, 'Reconstructed data', channels=3)
plt.tight_layout()
plt.show()
if __name__ == '__main__':
climate.call(main)
|
#!/usr/bin/env python
import climate
import matplotlib.pyplot as plt
import theanets
from utils import load_cifar, plot_layers, plot_images
g = climate.add_arg_group('CIFAR Example')
g.add_argument('--features', type=int, default=32, metavar='N',
help='train a model using N^2 hidden-layer features')
def main(args):
train, valid, _ = load_cifar()
e = theanets.Experiment(
theanets.Autoencoder,
layers=(3072, args.features ** 2, 3072))
e.train(train, valid)
plot_layers(e.network.weights, channels=3)
plt.tight_layout()
plt.show()
valid = valid[:100]
plot_images(valid, 121, 'Sample data', channels=3)
plot_images(e.network.predict(valid), 122, 'Reconstructed data', channels=3)
plt.tight_layout()
plt.show()
if __name__ == '__main__':
climate.call(main)
|
Update the PyPI version to 7.0.17.
|
# -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='7.0.17',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
|
# -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='7.0.16',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
|
Fix minor issue (jackson security)
|
package fr.insee.rmes.api.utils;
import javax.ws.rs.core.MediaType;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
public class ResponseUtils {
private static Logger logger = LogManager.getLogger(ResponseUtils.class);
public static String produceResponse(Object obj, String header) {
ObjectMapper mapper = new ObjectMapper();
String response = "";
if (header != null && header.equals(MediaType.APPLICATION_XML)) {
mapper = new XmlMapper();
}
else {
mapper = new ObjectMapper();
}
try {
response = mapper.writeValueAsString(obj);
response = response.replaceAll("<", "<");
} catch (Exception e) {
logger.error(e.getMessage());
}
return response;
}
}
|
package fr.insee.rmes.api.utils;
import javax.ws.rs.core.MediaType;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
public class ResponseUtils {
private static Logger logger = LogManager.getLogger(ResponseUtils.class);
public static String produceResponse(Object obj, String header) {
ObjectMapper mapper = new ObjectMapper();
String response = "";
if (header != null && header.equals(MediaType.APPLICATION_XML)) {
mapper = new XmlMapper();
}
else {
mapper = new ObjectMapper();
}
try {
response = mapper.writeValueAsString(obj);
} catch (Exception e) {
logger.error(e.getMessage());
}
return response;
}
}
|
Use reflection to extract Netty's default level
See gh-27046
|
/*
* Copyright 2012-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.autoconfigure.netty;
import io.netty.util.ResourceLeakDetector;
import io.netty.util.ResourceLeakDetector.Level;
import org.junit.jupiter.api.Test;
import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link NettyProperties}
*
* @author Brian Clozel
*/
class NettyPropertiesTests {
@Test
void defaultValueShouldMatchNettys() {
NettyProperties properties = new NettyProperties();
ResourceLeakDetector.Level defaultLevel = (Level) ReflectionTestUtils.getField(ResourceLeakDetector.class,
"DEFAULT_LEVEL");
assertThat(ResourceLeakDetector.Level.valueOf(properties.getLeakDetection().name())).isEqualTo(defaultLevel);
}
}
|
/*
* Copyright 2012-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.autoconfigure.netty;
import io.netty.util.ResourceLeakDetector;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link NettyProperties}
*
* @author Brian Clozel
*/
class NettyPropertiesTests {
@Test
void defaultValueShouldMatchNettys() {
NettyProperties properties = new NettyProperties();
assertThat(ResourceLeakDetector.Level.valueOf(properties.getLeakDetection().name()))
.isEqualTo(ResourceLeakDetector.getLevel());
}
}
|
Add timer to check for new mail
|
// @ngInject
module.exports = function($scope, $stateParams, EmailState, API, $interval) {
var vm = this;
vm.emails = [];
vm.label = 'inbox';
vm.emailFilter = EmailState.filter;
vm.fetchEmails = function(label) {
vm.label = label || 'inbox';
var request = vm.label === 'inbox' ? API.getInbox : API.getLabel;
request(vm.label).then(function(email) {
vm.email = email.data;
EmailState.setLabel(label);
EmailState.setMail(vm.email);
});
};
vm.showTrashMessage = function() {
return vm.label === 'trash';
};
vm.showStarredMessage = function() {
return vm.label === 'starred';
};
vm.showOtherMessage = function() {
return !vm.showTrashMessage() && !vm.showStarredMessage();
};
$scope.$watch(
function() { return $stateParams.label; },
vm.fetchEmails
);
$interval(function() {
vm.fetchEmails($stateParams.label);
}, 5000);
};
|
// @ngInject
module.exports = function($scope, $stateParams, EmailState, API) {
var vm = this;
vm.emails = [];
vm.label = 'inbox';
vm.emailFilter = EmailState.filter;
vm.fetchEmails = function(label) {
vm.label = label || 'inbox';
var request = vm.label === 'inbox' ? API.getInbox : API.getLabel;
request(vm.label).then(function(email) {
vm.email = email.data;
EmailState.setLabel(label);
EmailState.setMail(vm.email);
});
};
vm.showTrashMessage = function() {
return vm.label === 'trash';
};
vm.showStarredMessage = function() {
return vm.label === 'starred';
};
vm.showOtherMessage = function() {
return !vm.showTrashMessage() && !vm.showStarredMessage();
};
$scope.$watch(
function() { return $stateParams.label; },
vm.fetchEmails
);
};
|
Fix test error with YamlSource
|
<?php
namespace Neos\Flow\Tests\Functional\Configuration\Fixtures;
/*
* This file is part of the Neos.Flow package.
*
* (c) Contributors of the Neos Project - www.neos.io
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
use Neos\Flow\Annotations as Flow;
class RootDirectoryIgnoringYamlSource extends \Neos\Flow\Configuration\Source\YamlSource
{
/**
* Loads the specified configuration file and returns its content as an
* array. If the file does not exist or could not be loaded, an empty
* array is returned
*
* @param string $pathAndFilename Full path and filename of the file to load, excluding the file extension (ie. ".yaml")
* @param boolean $allowSplitSource If TRUE, the type will be used as a prefix when looking for configuration files
* @return array
* @throws \Neos\Flow\Configuration\Exception\ParseErrorException
*/
public function load($pathAndFilename, $allowSplitSource = false): array
{
if (strpos($pathAndFilename, FLOW_PATH_CONFIGURATION) === 0) {
return [];
} else {
return parent::load($pathAndFilename, $allowSplitSource);
}
}
}
|
<?php
namespace Neos\Flow\Tests\Functional\Configuration\Fixtures;
/*
* This file is part of the Neos.Flow package.
*
* (c) Contributors of the Neos Project - www.neos.io
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
use Neos\Flow\Annotations as Flow;
class RootDirectoryIgnoringYamlSource extends \Neos\Flow\Configuration\Source\YamlSource
{
/**
* Loads the specified configuration file and returns its content as an
* array. If the file does not exist or could not be loaded, an empty
* array is returned
*
* @param string $pathAndFilename Full path and filename of the file to load, excluding the file extension (ie. ".yaml")
* @param boolean $allowSplitSource If TRUE, the type will be used as a prefix when looking for configuration files
* @return array
* @throws \Neos\Flow\Configuration\Exception\ParseErrorException
*/
public function load($pathAndFilename, $allowSplitSource = false)
{
if (strpos($pathAndFilename, FLOW_PATH_CONFIGURATION) === 0) {
return [];
} else {
return parent::load($pathAndFilename, $allowSplitSource);
}
}
}
|
Add possibility to add custom plugin prefix
Summary: The problem with a fixed prefix is that babel 7 uses a scoped packages and every (standard) plugin is now part of that scope so the prefix is no longer `babel-plugin-` but instead `babel/plugin-`. There are more changes. This one will at least fix most of them.
Reviewed By: davidaurelio
Differential Revision: D7085102
fbshipit-source-id: b927998c611b71b3265e1cb3f6df537b14f9cb25
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
/**
* Manually resolve all default Babel plugins.
* `babel.transform` will attempt to resolve all base plugins relative to
* the file it's compiling. This makes sure that we're using the plugins
* installed in the react-native package.
*/
function resolvePlugins(plugins, prefix) {
return plugins.map(plugin => resolvePlugin(plugin, prefix));
}
/**
* Manually resolve a single Babel plugin.
*/
function resolvePlugin(plugin, prefix = 'babel-plugin-') {
// Normalise plugin to an array.
if (!Array.isArray(plugin)) {
plugin = [plugin];
}
// Only resolve the plugin if it's a string reference.
if (typeof plugin[0] === 'string') {
plugin[0] = require(prefix + plugin[0]);
plugin[0] = plugin[0].__esModule ? plugin[0].default : plugin[0];
}
return plugin;
}
module.exports = resolvePlugins;
module.exports.resolvePlugin = resolvePlugin;
module.exports.resolvePluginAs = (prefix, plugin) =>
resolvePlugin(plugin, prefix);
module.exports.resolvePluginsAs = (prefix, plugins) =>
resolvePlugins(plugins, prefix);
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
/**
* Manually resolve all default Babel plugins.
* `babel.transform` will attempt to resolve all base plugins relative to
* the file it's compiling. This makes sure that we're using the plugins
* installed in the react-native package.
*/
function resolvePlugins(plugins) {
return plugins.map(resolvePlugin);
}
/**
* Manually resolve a single Babel plugin.
*/
function resolvePlugin(plugin) {
// Normalise plugin to an array.
if (!Array.isArray(plugin)) {
plugin = [plugin];
}
// Only resolve the plugin if it's a string reference.
if (typeof plugin[0] === 'string') {
plugin[0] = require('babel-plugin-' + plugin[0]);
plugin[0] = plugin[0].__esModule ? plugin[0].default : plugin[0];
}
return plugin;
}
module.exports = resolvePlugins;
module.exports.resolvePlugin = resolvePlugin;
|
[YAKHMI-870] SCTUnit: Create abstract SGenGenerator for SCTUnit
-added generated Code
|
package org.yakindu.sct.generator.core;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.xtext.generator.JavaIoFileSystemAccess;
import org.yakindu.sct.model.sgen.GeneratorEntry;
import com.google.inject.Inject;
import com.google.inject.Injector;
/**
* @author oliver bohl
*
*/
public abstract class AbstractSGenGenerator implements ISCTGenerator {
@Inject protected IWorkspaceRoot root;
@Inject protected JavaIoFileSystemAccess fsa;
@Inject protected Injector injector;
protected abstract void generateContent(GeneratorEntry entry,
JavaIoFileSystemAccess fsa, String targetProjectPath);
public void generate(GeneratorEntry entry) {
// Does actually nothing
// generateInternal(entry);
}
// private void generateInternal(GeneratorEntry entry) {
//
//
// String targetProject = GeneratorUtils.getTargetProject(entry).toString();
// targetProject = targetProject.substring(1);
//
// IProject targetProjectRoot = root.getProject(targetProject);
//
// if(targetProjectRoot.exists() && targetProjectRoot.isOpen()){
// String targetFolder =
// GeneratorUtils.getTargetFolder(entry).toString();
// fsa.setOutputPath(IFileSystemAccess.DEFAULT_OUTPUT, targetFolder);
//
// String targetProjectPath = targetProject.replaceAll("\\.", "/");
// generateContent(entry, fsa, targetProjectPath);
// }
// }
}
|
package org.yakindu.sct.generator.core;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.xtext.generator.JavaIoFileSystemAccess;
import org.yakindu.sct.model.sgen.GeneratorEntry;
import com.google.inject.Inject;
import com.google.inject.Injector;
/**
* @author oliver bohl
*
*/
public abstract class AbstractSGenGenerator implements ISCTGenerator {
@Inject protected IWorkspaceRoot root;
@Inject protected JavaIoFileSystemAccess fsa;
@Inject protected Injector injector;
protected abstract void generateContent(GeneratorEntry entry,
JavaIoFileSystemAccess fsa, String targetProjectPath);
public void generate(GeneratorEntry entry) {
// Does actually nothing
// generateInternal(entry);
}
// private void generateInternal(GeneratorEntry entry) {
//
//
// String targetProject = GeneratorUtils.getTargetProject(entry).toString();
// targetProject = targetProject.substring(1);
//
// IProject targetProjectRoot = root.getProject(targetProject);
//
// if(targetProjectRoot.exists() && targetProjectRoot.isOpen()){
// String targetFolder =
// GeneratorUtils.getTargetFolder(entry).toString();
// fsa.setOutputPath(IFileSystemAccess.DEFAULT_OUTPUT, targetFolder);
//
// String targetProjectPath = targetProject.replaceAll("\\.", "/");
// generateContent(entry, fsa, targetProjectPath);
// }
// }
}
|
Create a new object instead of modifying original
Fixing the root problem will require more severe changes, basically
avoiding passing objects by reference to prevent this kind of bugs.
|
var _ = require('underscore');
var StylesFactory = require('../../styles-factory');
var StyleFormDefaultModel = require('../style-form-default-model');
module.exports = StyleFormDefaultModel.extend({
parse: function (r) {
var geom = r.geom;
var attrs = {
fill: r.fill,
stroke: r.stroke,
blending: r.blending,
resolution: r.resolution
};
var isAggregatedType = _.contains(StylesFactory.getAggregationTypes(), r.type);
if (isAggregatedType || (geom && geom.getSimpleType() === 'polygon')) {
if (attrs.fill.size) {
attrs.fill = _.omit(attrs.fill, 'size');
}
}
if (geom && geom.getSimpleType() === 'line') {
attrs = _.omit(attrs.fill);
}
if (r.type === 'heatmap') {
attrs = _.omit(attrs, 'stroke', 'blending');
} else {
attrs = _.omit(attrs, 'resolution');
}
return attrs;
},
_onChange: function () {
this._styleModel.set(_.clone(this.attributes));
}
});
|
var _ = require('underscore');
var StylesFactory = require('../../styles-factory');
var StyleFormDefaultModel = require('../style-form-default-model');
module.exports = StyleFormDefaultModel.extend({
parse: function (r) {
var geom = r.geom;
var attrs = {
fill: r.fill,
stroke: r.stroke,
blending: r.blending,
resolution: r.resolution
};
var isAggregatedType = _.contains(StylesFactory.getAggregationTypes(), r.type);
if (isAggregatedType || (geom && geom.getSimpleType() === 'polygon')) {
delete attrs.fill.size;
}
if (geom && geom.getSimpleType() === 'line') {
delete attrs.fill;
}
if (r.type === 'heatmap') {
attrs = _.omit(attrs, 'stroke', 'blending');
} else {
attrs = _.omit(attrs, 'resolution');
}
return attrs;
},
_onChange: function () {
this._styleModel.set(_.clone(this.attributes));
}
});
|
Return active dir for use by clients.
|
"""
Helper functions for pushing content to a staging directory, moving the old directory aside, and moving the staging directory into place.
"""
from fabric.api import env
from fabric.operations import sudo
from . import debug
from os import path
import time
import re
def make_staging_directory(basename = "project", parent = "/opt"):
dir_tmp = path.join(parent,basename) + time.strftime("_%Y%m%d_%H%M%S") + ".deploying"
sudo('mkdir -p %s' % dir_tmp)
sudo("chown %s:%s %s" % (env.user, env.group, dir_tmp))
return dir_tmp
def flip(staging_dir):
active_dir = re.sub(r'_[0-9]{8}_[0-9]{6}.deploying','',staging_dir)
retired_dir = active_dir + time.strftime("_%Y%m%d_%H%M%S") + ".retired"
debug("Flipping directory name.")
sudo("mv %s %s.retired" % (active_dir,retired_dir), quiet=True)
sudo("mv %s %s" % (staging_dir,active_dir))
return active_dir
|
"""
Helper functions for pushing content to a staging directory, moving the old directory aside, and moving the staging directory into place.
"""
from fabric.api import env
from fabric.operations import sudo
from . import debug
from os import path
import time
import re
def make_staging_directory(basename = "project", parent = "/opt"):
dir_tmp = path.join(parent,basename) + time.strftime("_%Y%m%d_%H%M%S") + ".deploying"
sudo('mkdir -p %s' % dir_tmp)
sudo("chown %s:%s %s" % (env.user, env.group, dir_tmp))
return dir_tmp
def flip(staging_dir):
active_dir = re.sub(r'_[0-9]{8}_[0-9]{6}.deploying','',staging_dir)
retired_dir = active_dir + time.strftime("_%Y%m%d_%H%M%S") + ".retired"
debug("Flipping directory name.")
sudo("mv %s %s.retired" % (active_dir,retired_dir), quiet=True)
sudo("mv %s %s" % (staging_dir,active_dir))
|
Update the script to create EC2 instance.
This creates an EC2 i3.8xlarge.
|
import boto3
import botocore
import time
ec2 = boto3.resource('ec2', region_name='us-east-1')
client = boto3.client('ec2')
# Create a security group
try:
sg = ec2.create_security_group(GroupName='jupyter', Description='EC2 for Jupyter Notebook')
response = client.authorize_security_group_ingress(GroupName='jupyter', IpPermissions=[{'PrefixListIds': [], 'UserIdGroupPairs': [], 'IpRanges': [{'CidrIp': '0.0.0.0/0'}], 'IpProtocol': 'tcp', 'Ipv6Ranges': [{'CidrIpv6': '::/0'}], 'ToPort': 8888, 'FromPort': 8888}])
print("create a security group")
except botocore.exceptions.ClientError as e:
sg = client.describe_security_groups(GroupNames=['jupyter'])
print("the security group exist")
o = ec2.create_instances(ImageId='ami-622a0119', MinCount=1, MaxCount=1, InstanceType='i3.8xlarge', SecurityGroups=['jupyter'])
print_res = False
while (not print_res):
time.sleep(1)
for i in ec2.instances.filter(InstanceIds=[o[0].id]):
if i.public_ip_address is not None:
print("The public IP address: " + str(i.public_ip_address))
print_res = True
|
import boto3
import botocore
import time
ec2 = boto3.resource('ec2', region_name='us-east-1')
client = boto3.client('ec2')
# Create a security group
try:
sg = ec2.create_security_group(GroupName='jupyter', Description='EC2 for Jupyter Notebook')
response = client.authorize_security_group_ingress(GroupName='jupyter', IpPermissions=[{'PrefixListIds': [], 'UserIdGroupPairs': [], 'IpRanges': [{'CidrIp': '0.0.0.0/0'}], 'IpProtocol': 'tcp', 'Ipv6Ranges': [{'CidrIpv6': '::/0'}], 'ToPort': 8888, 'FromPort': 8888}])
print("create a security group")
except botocore.exceptions.ClientError as e:
sg = client.describe_security_groups(GroupNames=['jupyter'])
print("the security group exist")
o = ec2.create_instances(ImageId='ami-e36637f5', MinCount=1, MaxCount=1, InstanceType='i3.xlarge', SecurityGroups=['jupyter'])
print_res = False
while (not print_res):
time.sleep(1)
for i in ec2.instances.filter(InstanceIds=[o[0].id]):
if i.public_ip_address is not None:
print("The public IP address: " + str(i.public_ip_address))
print_res = True
|
Make mutation hoc accept mutations without arguments
|
/*
HoC that provides a simple mutation that expects a single JSON object in return
Example usage:
export default withMutation({
name: 'getEmbedlyData',
args: {url: 'String'},
})(EmbedlyURL);
*/
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
export default function withMutation({name, args}) {
let mutation;
if (args) {
const args1 = _.map(args, (type, name) => `$${name}: ${type}`); // e.g. $url: String
const args2 = _.map(args, (type, name) => `${name}: $${name}`); // e.g. $url: url
mutation = `
mutation ${name}(${args1}) {
${name}(${args2})
}
`
} else {
mutation = `
mutation ${name} {
${name}
}
`
}
return graphql(gql`${mutation}`, {
props: ({ownProps, mutate}) => ({
[name]: (vars) => {
return mutate({
variables: vars,
});
}
}),
});
}
|
/*
HoC that provides a simple mutation that expects a single JSON object in return
Example usage:
export default withMutation({
name: 'getEmbedlyData',
args: {url: 'String'},
})(EmbedlyURL);
*/
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
export default function withMutation({name, args}) {
const args1 = _.map(args, (type, name) => `$${name}: ${type}`); // e.g. $url: String
const args2 = _.map(args, (type, name) => `${name}: $${name}`); // e.g. $url: url
return graphql(gql`
mutation ${name}(${args1}) {
${name}(${args2})
}
`, {
props: ({ownProps, mutate}) => ({
[name]: (vars) => {
return mutate({
variables: vars,
});
}
}),
});
}
|
Add allow/deny for post editing/deleting
|
Posts = new Mongo.Collection('posts');
Posts.allow({
update: function(userId, post) {
return ownsDocument(userId, post);
},
remove: function(userId, post) {
return ownsDocument(userId, post);
}
});
Posts.deny({
update: function(userId, post, fieldNames) {
return (_.without(fieldNames, 'url', 'title').length > 0);
}
});
Meteor.methods({
postInsert: function(postAttributes) {
check(Meteor.userId(), String);
check(postAttributes, {
title: String,
url: String
});
var postWithSameLink = Posts.findOne({ url: postAttributes.url });
if (postWithSameLink) {
return {
postExists: true,
_id: postWithSameLink._id
};
}
var user = Meteor.user();
var post = _.extend(postAttributes, {
userId: user._id,
author: user.username,
submitted: new Date()
});
var postId = Posts.insert(post);
return {
_id: postId
};
}
})
|
Posts = new Mongo.Collection('posts');
Meteor.methods({
postInsert: function(postAttributes) {
check(Meteor.userId(), String);
check(postAttributes, {
title: String,
url: String
});
var postWithSameLink = Posts.findOne({ url: postAttributes.url });
if (postWithSameLink) {
return {
postExists: true,
_id: postWithSameLink._id
};
}
var user = Meteor.user();
var post = _.extend(postAttributes, {
userId: user._id,
author: user.username,
submitted: new Date()
});
var postId = Posts.insert(post);
return {
_id: postId
};
}
})
|
Use a dynamic url to secure webhook
|
import json
import os
import ieeebot
from flask import Flask, request, abort
from storage import Storage
app = Flask(__name__)
app.config['PROPAGATE_EXCEPTIONS'] = True
ieeebot.logger.debug(ieeebot.TOKEN)
ieeebot.logger.debug(ieeebot.DATABASE_FILE)
@app.route('/webhook/<token>', methods=['POST'])
def hello(token=None):
if token == ieeebot.TOKEN:
update = request.get_json(force=True)
ieeebot.logger.info(str(update))
if update['update_id'] > ieeebot.last_update_id:
ieeebot.last_update_id = update['update_id']
ieeebot.process_update(update)
return "", 200
else:
return "", 400
if __name__ == "__main__":
app.run(debug = True)
|
import json
import os
import ieeebot
from flask import Flask, request, abort
from storage import Storage
app = Flask(__name__)
app.config['PROPAGATE_EXCEPTIONS'] = True
ieeebot.logger.debug(ieeebot.TOKEN)
ieeebot.logger.debug(ieeebot.DATABASE_FILE)
@app.route('/ieeetestbot', methods=['POST'])
def hello():
update = request.get_json(force=True)
#ieeebot.logger.info(str(update))
if update['update_id'] > ieeebot.last_update_id:
ieeebot.last_update_id = update['update_id']
ieeebot.process_update(update)
return "", 200
if __name__ == "__main__":
app.run(debug = True)
|
Fix js style on RailsRouteBuilder
|
import PathBuilder from './path-builder'
class RailsRouteBuilder {
constructor (configs = {}) {
// TODO
// Make an option for switching to GET for destroy actions
this.pathBuilder = new PathBuilder()
}
//
// RESTful Actions
//
index (...args) {
this.list(args)
}
list (resource, params) {
let path = resource
return this.pathBuilder.get(path, params)
}
show (resource, params) {
let path = `${resource}/:id`
return this.pathBuilder.get(path, params)
}
destroy (resource, params) {
let path = `${resource}/:id`
return this.pathBuilder.delete(path, params)
}
create (resource, params) {
let path = resource
return this.pathBuilder.post(path, params)
}
update (resource, params) {
let path = `${resource}/:id`
return this.pathBuilder.patch(path, params)
}
new (resource, params) {
let path = `${resource}/:id/new`
return this.pathBuilder.get(path, params)
}
edit (resource, params) {
let path = `${resource}/:id/edit`
return this.pathBuilder.get(path, params)
}
}
export default RailsRouteBuilder
|
import Axios from 'axios'
import PathBuilder from './path-builder'
class RailsRouteBuilder {
constructor (configs = {}) {
// TODO
// Make an option for switching to GET for destroy actions
this.pathBuilder = new PathBuilder
}
//
// RESTful Actions
//
index (...args) {
this.list(args)
}
list (resource, params) {
let path = resource
return this.pathBuilder.get(path, params)
}
show (resource, params) {
let path = `${resource}/:id`
return this.pathBuilder.get(path, params)
}
destroy (resource, params) {
let path = `${resource}/:id`
return this.pathBuilder.delete(path, params)
}
create (resource, params) {
let path = resource
return this.pathBuilder.post(path, params)
}
update (resource, params) {
let path = `${resource}/:id`
return this.pathBuilder.patch(path, params)
}
new (resource, params) {
let path = `${resource}/:id/new`
return this.pathBuilder.get(path, params)
}
edit (resource, params) {
let path = `${resource}/:id/edit`
return this.pathBuilder.get(path, params)
}
}
export default RailsRouteBuilder
|
Update tests to remove pgf.preamble
|
import matplotlib
import fishbowl
original = True
updated = False
def test_context_set():
fishbowl.reset_style()
with fishbowl.style(axes='minimal', palette='gourami', font='Arbitrary'):
assert matplotlib.rcParams['axes.spines.left'] == updated
def test_context_reset():
fishbowl.reset_style()
with fishbowl.style(axes='minimal', palette='gourami', font='Arbitrary'):
pass
assert matplotlib.rcParams['axes.spines.left'] == original
def test_set():
fishbowl.reset_style()
fishbowl.set_style(font='Arbitrary')
assert matplotlib.rcParams['axes.spines.left'] == updated
def test_reset():
fishbowl.set_style(font='Arbitrary')
fishbowl.reset_style()
assert matplotlib.rcParams['axes.spines.left'] == original
|
import matplotlib
import fishbowl
original = []
updated = [r'\usepackage{mathspec}',
r'\setallmainfonts(Digits,Latin,Greek){Arbitrary}']
def test_context_set():
fishbowl.reset_style()
with fishbowl.style(axes='minimal', palette='gourami', font='Arbitrary'):
assert matplotlib.rcParams['pgf.preamble'] == updated
def test_context_reset():
fishbowl.reset_style()
with fishbowl.style(axes='minimal', palette='gourami', font='Arbitrary'):
pass
assert matplotlib.rcParams['pgf.preamble'] == original
def test_set():
fishbowl.reset_style()
fishbowl.set_style(font='Arbitrary')
assert matplotlib.rcParams['pgf.preamble'] == updated
def test_reset():
fishbowl.set_style(font='Arbitrary')
fishbowl.reset_style()
assert matplotlib.rcParams['pgf.preamble'] == original
|
Update JednostkaAdministracyjnaFilter for new django-filters
|
import django_filters
from django.shortcuts import get_object_or_404
from django.utils.translation import ugettext_lazy as _
try:
from django_filters import rest_framework as filters
except ImportError: # Back-ward compatible for django-rest-framework<3.7
from rest_framework import filters
from rest_framework import viewsets
from teryt_tree.models import JednostkaAdministracyjna
from teryt_tree.rest_framework_ext.serializers import \
JednostkaAdministracyjnaSerializer
def custom_area_filter(queryset, _, value):
if not value:
return queryset
return queryset.area(get_object_or_404(JednostkaAdministracyjna, pk=value))
class JednostkaAdministracyjnaFilter(filters.FilterSet):
area = django_filters.CharFilter(
method=custom_area_filter,
label=_("Area")
)
class Meta:
model = JednostkaAdministracyjna
fields = ['name', 'category', 'category__level', 'area']
class JednostkaAdministracyjnaViewSet(viewsets.ModelViewSet):
queryset = (JednostkaAdministracyjna.objects.
select_related('category').
prefetch_related('children').
all())
serializer_class = JednostkaAdministracyjnaSerializer
filter_backends = (filters.DjangoFilterBackend,)
filter_class = JednostkaAdministracyjnaFilter
|
import django_filters
from django.shortcuts import get_object_or_404
try:
from django_filters import rest_framework as filters
except ImportError: # Back-ward compatible for django-rest-framework<3.7
from rest_framework import filters
from rest_framework import viewsets
from teryt_tree.models import JednostkaAdministracyjna
from teryt_tree.rest_framework_ext.serializers import JednostkaAdministracyjnaSerializer
def custom_area_filter(queryset, _, value):
if not value:
return queryset
return queryset.area(get_object_or_404(JednostkaAdministracyjna, pk=value))
class JednostkaAdministracyjnaFilter(filters.FilterSet):
area = django_filters.CharFilter(action=custom_area_filter)
class Meta:
model = JednostkaAdministracyjna
fields = ['name', 'category', 'category__level', 'area']
class JednostkaAdministracyjnaViewSet(viewsets.ModelViewSet):
queryset = (JednostkaAdministracyjna.objects.
select_related('category').
prefetch_related('children').
all())
serializer_class = JednostkaAdministracyjnaSerializer
filter_backends = (filters.DjangoFilterBackend,)
filter_class = JednostkaAdministracyjnaFilter
|
Make sure commit finishes before tagging
|
var request = require('request'),
fs = require('fs'),
path = require('path'),
exec = require('child_process').exec,
version = require('../package.json').version;
var urlStub = 'http://code.angularjs.org/',
files = ['/angular.min.js', '/angular.min.js.map'];
function getFile (index) {
var file = files[index],
writer = fs.createWriteStream('lib' + file);
writer.on('finish', function () {
console.log(file.substr(1), 'fetched and written');
if (index < files.length - 1) {
getFile(index + 1);
} else {
testAndTag();
}
});
request(urlStub + version + file).pipe(writer);
};
function testAndTag () {
console.log('running tests');
exec('npm test', function (error, stdout, stderr) {
if (error !== null) {
console.log('test error: ' + error);
} else {
exec('git commit -am "Angular v' + version + ' with Browserify support"', function (err) {
if (error === null) {
exec('git tag v' + version);
}
});
}
});
}
getFile(0);
|
var request = require('request'),
fs = require('fs'),
path = require('path'),
exec = require('child_process').exec,
version = require('../package.json').version;
var urlStub = 'http://code.angularjs.org/',
files = ['/angular.min.js', '/angular.min.js.map'];
function getFile (index) {
var file = files[index],
writer = fs.createWriteStream('lib' + file);
writer.on('finish', function () {
console.log(file.substr(1), 'fetched and written');
if (index < files.length - 1) {
getFile(index + 1);
} else {
testAndTag();
}
});
request(urlStub + version + file).pipe(writer);
};
function testAndTag () {
console.log('running tests');
exec('npm test', function (error, stdout, stderr) {
if (error !== null) {
console.log('test error: ' + error);
} else {
exec('git commit -am "Angular v' + version + ' with Browserify support"');
exec('git tag v' + version);
}
});
}
getFile(0);
|
Use .set() rather than direct assignment
|
from django.core.management.base import BaseCommand, CommandError
from judge.models import Language
class Command(BaseCommand):
help = 'allows the problems allowed to be submitted in the <source> language to be submitted in <target> language'
def add_arguments(self, parser):
parser.add_argument('source', help='language to copy from')
parser.add_argument('target', help='language to copy to')
def handle(self, *args, **options):
try:
source = Language.objects.get(key=options['source'])
except Language.DoesNotExist:
raise CommandError('Invalid source language: %s' % options['source'])
try:
target = Language.objects.get(key=options['target'])
except Language.DoesNotExist:
raise CommandError('Invalid target language: %s' % options['target'])
target.problem_set.set(source.problem_set.all())
|
from django.core.management.base import BaseCommand, CommandError
from judge.models import Language
class Command(BaseCommand):
help = 'allows the problems allowed to be submitted in the <source> language to be submitted in <target> language'
def add_arguments(self, parser):
parser.add_argument('source', help='language to copy from')
parser.add_argument('target', help='language to copy to')
def handle(self, *args, **options):
try:
source = Language.objects.get(key=options['source'])
except Language.DoesNotExist:
raise CommandError('Invalid source language: %s' % options['source'])
try:
target = Language.objects.get(key=options['target'])
except Language.DoesNotExist:
raise CommandError('Invalid target language: %s' % options['target'])
target.problem_set = source.problem_set.all()
|
Remove a left over comment from when getConfigValidityReport just returned a true/false rather than actual error messages.
|
'use strict';
module.exports = {
port: 8080,
googlePlacesApiKey: '', // define this in local.js
/**
* Shortcut function to get only the isValid property from config validity report.
* @returns {boolean}
*/
isValid: function() {
return this.getConfigValidityReport().isValid;
},
/**
* Generates a "report" on whether or not the config is valid. Report contains all error messages
* as well as a simple "isValid" property.
*/
getConfigValidityReport: function() {
// Assume zero errors and valid by default.
var summary = { errors: [], isValid: true };
// Check the configuration parameters. Return false on invalid config.
if (!this.googlePlacesApiKey) {
summary.errors.push("Places API key was not defined. Please supply a Google Places API Key and try again. Refer to README file for more information.");
}
// TODO: Add any additional checks here.
// Set the isValid flag to false if errors present.
if (summary.errors.length !== 0) {
summary.isValid = false;
}
return summary;
}
};
|
'use strict';
module.exports = {
port: 8080,
googlePlacesApiKey: '', // define this in local.js
/**
* Shortcut function to get only the isValid property from config validity report.
* @returns {boolean}
*/
isValid: function() {
return this.getConfigValidityReport().isValid;
},
/**
* Generates a "report" on whether or not the config is valid. Report contains all error messages
* as well as a simple "isValid" property.
*/
getConfigValidityReport: function() {
// Assume zero errors and valid by default.
var summary = { errors: [], isValid: true };
// Check the configuration parameters. Return false on invalid config.
if (!this.googlePlacesApiKey) {
summary.errors.push("Places API key was not defined. Please supply a Google Places API Key and try again. Refer to README file for more information.");
}
// TODO: Add any additional checks here.
// Set the isValid flag to false if errors present.
if (summary.errors.length !== 0) {
summary.isValid = false;
}
// All checks completed successfully. Config appears valid!
return summary;
}
};
|
Fix shapes in SWF assets on NPM
|
module.exports = require("./../../_gen/openfl/utils/AssetLibrary");
// TODO: Put elsewhere?
var internal = {
FilterType: require ("../../_gen/openfl/_internal/swf/FilterType").default,
ShapeCommand: require ("../../_gen/openfl/_internal/swf/ShapeCommand").default,
SWFLiteLibrary: require ("../../_gen/openfl/_internal/swf/SWFLiteLibrary").default,
BitmapSymbol: require ("../../_gen/openfl/_internal/symbols/BitmapSymbol").default,
ButtonSymbol: require ("../../_gen/openfl/_internal/symbols/ButtonSymbol").default,
DynamicTextSymbol: require ("../../_gen/openfl/_internal/symbols/DynamicTextSymbol").default,
FontSymbol: require ("../../_gen/openfl/_internal/symbols/FontSymbol").default,
ShapeSymbol: require ("../../_gen/openfl/_internal/symbols/ShapeSymbol").default,
SpriteSymbol: require ("../../_gen/openfl/_internal/symbols/SpriteSymbol").default,
StaticTextRecord: require ("../../_gen/openfl/_internal/symbols/StaticTextRecord").default,
StaticTextSymbol: require ("../../_gen/openfl/_internal/symbols/StaticTextSymbol").default,
SWFSymbol: require ("../../_gen/openfl/_internal/symbols/SWFSymbol").default,
Frame: require ("../../_gen/openfl/_internal/timeline/Frame").default,
FrameObject: require ("../../_gen/openfl/_internal/timeline/FrameObject").default,
FrameObjectType: require ("../../_gen/openfl/_internal/timeline/FrameObjectType").default
}
module.exports._internal = internal;
|
module.exports = require("./../../_gen/openfl/utils/AssetLibrary");
// TODO: Put elsewhere?
var internal = {
SWFLiteLibrary: require ("../../_gen/openfl/_internal/swf/SWFLiteLibrary").default,
BitmapSymbol: require ("../../_gen/openfl/_internal/symbols/BitmapSymbol").default,
ButtonSymbol: require ("../../_gen/openfl/_internal/symbols/ButtonSymbol").default,
DynamicTextSymbol: require ("../../_gen/openfl/_internal/symbols/DynamicTextSymbol").default,
FontSymbol: require ("../../_gen/openfl/_internal/symbols/FontSymbol").default,
ShapeSymbol: require ("../../_gen/openfl/_internal/symbols/ShapeSymbol").default,
SpriteSymbol: require ("../../_gen/openfl/_internal/symbols/SpriteSymbol").default,
StaticTextRecord: require ("../../_gen/openfl/_internal/symbols/StaticTextRecord").default,
StaticTextSymbol: require ("../../_gen/openfl/_internal/symbols/StaticTextSymbol").default,
SWFSymbol: require ("../../_gen/openfl/_internal/symbols/SWFSymbol").default,
Frame: require ("../../_gen/openfl/_internal/timeline/Frame").default,
FrameObject: require ("../../_gen/openfl/_internal/timeline/FrameObject").default,
FrameObjectType: require ("../../_gen/openfl/_internal/timeline/FrameObjectType").default
}
module.exports._internal = internal;
|
Add method for getting PIL image
Also change function names to be uniform throughout
|
import json
import os
import random
import requests
from io import BytesIO
from PIL import Image
# GLOBALS
endpoint = "https://www.googleapis.com/customsearch/v1"
searchid = "013060195084513904668:z7-hxk7q35k"
# Retrieve my API key from a secret file
with open(os.path.join(os.path.dirname(__file__), "API_KEY.txt"), "r") as f:
API_KEY = f.read()
# API
def getImageUrl(search):
""" Get a ramdom image URL from the first 10 google images results for a
given search term """
r = requests.get(endpoint, params={
"key": API_KEY,
"cx": searchid,
"searchType": "image",
"q": search,
})
data = json.loads(r.text) # Load JSON responses
results = data["items"] # Find the images returned
result = random.choice(results) # Pick a random one
return result["link"] # Return its link
def getImage(search):
""" Get a PIL image for a given search term """
url = getImageUrl(search) # Get an image URL
req = requests.get(url) # Download image
b = BytesIO(req.content) # Load into file-like object
return Image.open(b) # Open and return
if __name__ == "__main__":
getImage("cow").show()
|
import json
import os
import random
import requests
from PIL import Image
# GLOBALS
endpoint = "https://www.googleapis.com/customsearch/v1"
searchid = "013060195084513904668:z7-hxk7q35k"
# Retrieve my API key from a secret file
with open(os.path.join(os.path.dirname(__file__), "API_KEY.txt"), "r") as f:
API_KEY = f.read()
# API
def get_image(search):
""" Get a ramdom image URL from the first 10 google images results for a
given search term """
r = requests.get(endpoint, params={
"key": API_KEY,
"cx": searchid,
"searchType": "image",
"q": search,
})
data = json.loads(r.text) # Load JSON responses
results = data["items"] # Find the images returned
result = random.choice(results) # Pick a random one
return result["link"] # Return its link
if __name__ == "__main__":
print(get_image("cow"))
|
Make the tenacity propertykeys resource path a publicly accessible static final.
|
package com.yammer.tenacity.client;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.sun.jersey.api.client.Client;
import javax.ws.rs.core.MediaType;
import java.net.URI;
public class TenacityClient {
private final Client client;
public static final String TENACITY_PROPERTYKEYS_PATH = "/tenacity/propertykeys";
public TenacityClient(Client client) {
this.client = client;
}
public Optional<ImmutableList<String>> getTenacityPropertyKeys(URI root) {
return Optional.of(ImmutableList.copyOf(client.resource(root)
.path(TENACITY_PROPERTYKEYS_PATH)
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(String[].class)));
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TenacityClient that = (TenacityClient) o;
if (!client.equals(that.client)) return false;
return true;
}
@Override
public int hashCode() {
return client.hashCode();
}
}
|
package com.yammer.tenacity.client;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.sun.jersey.api.client.Client;
import javax.ws.rs.core.MediaType;
import java.net.URI;
public class TenacityClient {
private final Client client;
public TenacityClient(Client client) {
this.client = client;
}
public Optional<ImmutableList<String>> getTenacityPropertyKeys(URI root) {
return Optional.of(ImmutableList.copyOf(client.resource(root)
.path("/tenacity/propertykeys")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(String[].class)));
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TenacityClient that = (TenacityClient) o;
if (!client.equals(that.client)) return false;
return true;
}
@Override
public int hashCode() {
return client.hashCode();
}
}
|
Fix event_dispatcher replacement in DependencyInjection
|
<?php
/**
* @LICENSE_TEXT
*/
namespace EventBand\Bundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
/**
* Class InitBandPass
*
* @author Kirill chEbba Chebunin <iam@chebba.org>
*/
class ReplaceDispatcherPass implements CompilerPassInterface
{
/**
* {@inheritDoc}
*/
public function process(ContainerBuilder $container)
{
if ($container->hasAlias('event_dispatcher')) {
$container->setAlias('event_band.internal_dispatcher', $container->getAlias('event_dispatcher'));
} else {
$dispatcher = $container->getDefinition('event_dispatcher');
$dispatcher->setPublic(false);
$container->setDefinition('event_band.internal_dispatcher', $dispatcher);
}
$container->setDefinition('event_dispatcher', $container->getDefinition('event_band.dispatcher'));
$container->removeDefinition('event_band.dispatcher');
$container->setAlias('event_band.dispatcher', 'event_dispatcher');
}
}
|
<?php
/**
* @LICENSE_TEXT
*/
namespace EventBand\Bundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
/**
* Class InitBandPass
*
* @author Kirill chEbba Chebunin <iam@chebba.org>
*/
class ReplaceDispatcherPass implements CompilerPassInterface
{
/**
* {@inheritDoc}
*/
public function process(ContainerBuilder $container)
{
$dispatcher = $container->getDefinition('event_dispatcher');
$dispatcher->setPublic(false);
$container->setDefinition('event_band.internal_dispatcher', $dispatcher);
$container->setDefinition('event_dispatcher', $container->getDefinition('event_band.dispatcher'));
$container->removeDefinition('event_band.dispatcher');
$container->setAlias('event_band.dispatcher', 'event_dispatcher');
}
}
|
Use 'stable' Django version for intersphinx
This will ensure documentation references always point at the latest version.
|
import os
import sys
import sphinx_rtd_theme
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
sys.path.insert(0, os.path.abspath("../.."))
import django
django.setup()
project = "django-postgres-extra"
copyright = "2019, Sector Labs"
author = "Sector Labs"
extensions = [
"sphinx_rtd_theme",
"sphinx.ext.intersphinx",
"sphinx.ext.autodoc",
"sphinx.ext.coverage",
"sphinx.ext.napoleon",
]
templates_path = ["_templates"]
exclude_patterns = []
html_theme = "sphinx_rtd_theme"
intersphinx_mapping = {
"django": ("https://docs.djangoproject.com/en/stable/", "https://docs.djangoproject.com/en/stable/_objects/"),
}
|
import os
import sys
import sphinx_rtd_theme
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
sys.path.insert(0, os.path.abspath("../.."))
import django
django.setup()
project = "django-postgres-extra"
copyright = "2019, Sector Labs"
author = "Sector Labs"
extensions = [
"sphinx_rtd_theme",
"sphinx.ext.intersphinx",
"sphinx.ext.autodoc",
"sphinx.ext.coverage",
"sphinx.ext.napoleon",
]
templates_path = ["_templates"]
exclude_patterns = []
html_theme = "sphinx_rtd_theme"
intersphinx_mapping = {
"django": ("https://docs.djangoproject.com/en/2.2/", "https://docs.djangoproject.com/en/2.2/_objects/"),
}
|
Update comments in the layout test
|
from seleniumbase import BaseCase
class VisualLayoutTest(BaseCase):
def test_applitools_helloworld(self):
self.open('https://applitools.com/helloworld?diff1')
print('Creating baseline in "visual_baseline" folder...')
self.check_window(name="helloworld", baseline=True)
self.click('a[href="?diff1"]')
# Verify html tags match previous version
self.check_window(name="helloworld", level=1)
# Verify html tags + attributes match previous version
self.check_window(name="helloworld", level=2)
# Verify html tags + attributes + values match previous version
self.check_window(name="helloworld", level=3)
# Change the page enough for a Level-3 comparison to fail
self.click("button")
self.check_window(name="helloworld", level=1)
self.check_window(name="helloworld", level=2)
with self.assertRaises(Exception):
self.check_window(name="helloworld", level=3)
# Now that we know the Exception was raised as expected,
# let's print out the comparison results by running in Level-0.
# (NOTE: Running with level-0 will print but NOT raise an Exception.)
self.check_window(name="helloworld", level=0)
|
from seleniumbase import BaseCase
class VisualLayoutTest(BaseCase):
def test_applitools_helloworld(self):
self.open('https://applitools.com/helloworld?diff1')
print('Creating baseline in "visual_baseline" folder...')
self.check_window(name="helloworld", baseline=True)
self.click('a[href="?diff1"]')
# Verify html tags match previous version
self.check_window(name="helloworld", level=1)
# Verify html tags + attributes match previous version
self.check_window(name="helloworld", level=2)
# Verify html tags + attributes + values match previous version
self.check_window(name="helloworld", level=3)
# Change the page enough for a Level-3 comparison to fail
self.click("button")
self.check_window(name="helloworld", level=1)
self.check_window(name="helloworld", level=2)
with self.assertRaises(Exception):
self.check_window(name="helloworld", level=3)
# Now that we know the exception was raised as expected,
# let's print out the comparison results by running in Level-0.
self.check_window(name="helloworld", level=0)
|
Add option for name and path of cloudConfig.yml file
This change adds a command line option to the dns script to specify
the name and location of the `cloudConfig.yml` file.
Signed-off-by: Nicolas Bock <4ad6fd604400c7892c7a2cb53bf674987bcaa405@suse.com>
|
#!/usr/bin/env python
import argparse
import yaml
def parse_commandline():
parser = argparse.ArgumentParser()
parser.add_argument(
"--dns-servers",
metavar="NAME",
help="A list of nameservers",
nargs="+",
default=[])
parser.add_argument(
"--ntp-servers",
metavar="NAME",
help="A list of ntp servers",
nargs="+",
default=[])
parser.add_argument(
"--cloud-config",
metavar="FILE",
help="The cloudConfig.yml FILE",
default="cloudConfig.yml")
return parser.parse_args()
if __name__ == "__main__":
options = parse_commandline()
print(options)
with open(options.cloud_config) as f:
data = yaml.load(f.read(), Loader=yaml.SafeLoader)
data['cloud']['dns-settings'] = dict(nameservers=options.dns_servers)
data['cloud']['ntp-servers'] = options.ntp_servers
with open(options.cloud_config, 'w') as f:
f.write(yaml.safe_dump(data, default_flow_style=False))
|
#!/usr/bin/env python
import argparse
import yaml
def parse_commandline():
parser = argparse.ArgumentParser()
parser.add_argument(
"--dns-servers",
metavar="NAME",
help="A list of nameservers",
nargs="+",
default=[])
parser.add_argument(
"--ntp-servers",
metavar="NAME",
help="A list of ntp servers",
nargs="+",
default=[])
return parser.parse_args()
if __name__ == "__main__":
options = parse_commandline()
print(options)
with open('cloudConfig.yml') as f:
data = yaml.load(f.read(), Loader=yaml.SafeLoader)
data['cloud']['dns-settings'] = dict(nameservers=options.dns_servers)
data['cloud']['ntp-servers'] = options.ntp_servers
with open('cloudConfig.yml', 'w') as f:
f.write(yaml.safe_dump(data, default_flow_style=False))
|
Print statistics easier to parse
|
package com.nurkiewicz.monkeys.actions;
import com.nurkiewicz.monkeys.behaviours.Cheater;
import com.nurkiewicz.monkeys.behaviours.Grudger;
import com.nurkiewicz.monkeys.behaviours.Sucker;
import com.nurkiewicz.monkeys.simulation.Population;
import com.nurkiewicz.monkeys.simulation.Statistics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Clock;
import java.time.Duration;
public class Probe extends Action {
private static final Logger log = LoggerFactory.getLogger(Probe.class);
private final Population population;
public Probe(Clock simulationTime, Duration delay, Population population) {
super(simulationTime, delay);
this.population = population;
}
@Override
public void run() {
final Statistics stats = population.statistics();
final Integer suckers = stats.getPerType().getOrDefault(Sucker.class.getSimpleName(), 0);
final Integer grudgers = stats.getPerType().getOrDefault(Grudger.class.getSimpleName(), 0);
final Integer cheaters = stats.getPerType().getOrDefault(Cheater.class.getSimpleName(), 0);
System.out.println(cheaters + "\t" + grudgers + "\t" + suckers);
}
}
|
package com.nurkiewicz.monkeys.actions;
import com.google.common.collect.ImmutableSet;
import com.nurkiewicz.monkeys.simulation.Population;
import com.nurkiewicz.monkeys.simulation.Statistics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Clock;
import java.time.Duration;
import java.util.Set;
public class Probe extends Action {
private static final Logger log = LoggerFactory.getLogger(Probe.class);
private final Population population;
public Probe(Clock simulationTime, Duration delay, Population population) {
super(simulationTime, delay);
this.population = population;
}
@Override
public void run() {
final Statistics stats = population.statistics();
log.info("At {} population: {}", getSchedule(), stats);
}
}
|
Disable redux logger in test environment
|
import {createHistory} from 'history';
import {createStore, applyMiddleware, compose, combineReducers} from 'redux';
import thunkMiddleware from 'redux-thunk';
import {reduxReactRouter} from 'redux-react-router';
import routes from './routes';
import reducers from './reducers';
export default function createAppStore(initialState) {
let finalCreateStore = createStore;
if (process.env.NODE_ENV === 'development') {
const logger = require('redux-logger');
finalCreateStore = compose(
applyMiddleware(logger()),
)(finalCreateStore);
}
if (process.env.NODE_ENV !== 'production') {
const {devTools, persistState} = require('redux-devtools');
finalCreateStore = compose(
devTools(),
persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/))
)(finalCreateStore);
}
finalCreateStore = compose(
applyMiddleware(
thunkMiddleware
),
reduxReactRouter({
routes,
createHistory,
}),
)(finalCreateStore);
return finalCreateStore(combineReducers(reducers), initialState);
}
|
import {createHistory} from 'history';
import {createStore, applyMiddleware, compose, combineReducers} from 'redux';
import thunkMiddleware from 'redux-thunk';
import {reduxReactRouter} from 'redux-react-router';
import routes from './routes';
import reducers from './reducers';
export default function createAppStore(initialState) {
let finalCreateStore = createStore;
if (process.env.NODE_ENV !== 'production') {
const {devTools, persistState} = require('redux-devtools');
const logger = require('redux-logger');
finalCreateStore = compose(
applyMiddleware(logger()),
devTools(),
persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/))
)(finalCreateStore);
}
finalCreateStore = compose(
applyMiddleware(
thunkMiddleware
),
reduxReactRouter({
routes,
createHistory,
}),
)(finalCreateStore);
return finalCreateStore(combineReducers(reducers), initialState);
}
|
Update the version to 1.6.1
|
__version_info__ = {
'major': 1,
'minor': 6,
'micro': 1,
'releaselevel': 'final',
'serial': 1
}
def get_version(short=False):
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro'] and not short:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final' and not short:
vers.append('%s%i' % (__version_info__['releaselevel'][0], __version_info__['serial']))
return ''.join(vers)
__version__ = get_version()
default_app_config = 'categories.apps.CategoriesConfig'
|
__version_info__ = {
'major': 1,
'minor': 6,
'micro': 0,
'releaselevel': 'final',
'serial': 1
}
def get_version(short=False):
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro'] and not short:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final' and not short:
vers.append('%s%i' % (__version_info__['releaselevel'][0], __version_info__['serial']))
return ''.join(vers)
__version__ = get_version()
default_app_config = 'categories.apps.CategoriesConfig'
|
Add a URL to urlpatterns for home page
|
"""bookshop URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from books import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^admin/', admin.site.urls),
]
|
"""bookshop URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
]
|
Update export csv function to close file when finished
|
from s3v3 import *
import csv
# ORIGINAL VERSION - Leaves file open
# def write_to_file(filename, data_sample):
# example = csv.writer(open(filename, 'w', encoding='utf-8'), dialect='excel') # example is the variable of the new file that is open and which we can write to (using utf-8 encoding and an excel dialect).
# example.writerows(data_sample) # write rows is going to take the rows in the data sample and write them to the example (i.e. the file name we passed in)
# NEW VERSION - Closes file at end
def write_to_file(filename, data_sample):
with open(filename, 'w', encoding='utf-8', newline='') as csvfile:
example = csv.writer(csvfile, dialect='excel')
example.writerows(data_sample)
write_to_file("_data/s4-silk_ties.csv", silk_ties) # this is going to create a new csv located in the _data directory, named s4-silk_ties.csv and it is going to contain all of that data from the silk_ties list which we created in s3v2 (silk_ties = filter_col_by_string(data_from_csv, "material", "_silk"))
# returned an error because the directory and the file did not exist. Going to create the directory and try again to see if it will create the file. It worked! It needs a directory, but it can create the file from scratch
|
from s3v3 import *
import csv
def write_to_file(filename, data_sample):
example = csv.writer(open(filename, 'w', encoding='utf-8'), dialect='excel') # example is the variable of the new file that is open and which we can write to (using utf-8 encoding and an excel dialect).
example.writerows(data_sample) # write rows is going to take the rows in the data sample and write them to the example (i.e. the file name we passed in)
write_to_file("_data/s4-silk_ties.csv", silk_ties) # this is going to create a new csv located in the _data directory, named s4-silk_ties.csv and it is going to contain all of that data from the silk_ties list which we created in s3v2 (silk_ties = filter_col_by_string(data_from_csv, "material", "_silk"))
# returned an error because the directory and the file did not exist. Going to create the directory and try again to see if it will create the file. It worked! It needs a directory, but it can create the file from scratch
|
Fix clientside tests to use plugin interface
|
'use strict';
/*jshint asi: true */
var browserify = require('browserify');
var proxyquire = require('../..');
var vm = require('vm');
function run(name) {
var src = '';
browserify()
.plugin(proxyquire.plugin)
.require(require.resolve('../..'), { expose: 'proxyquireify' })
.require(require.resolve('./' + name), { entry: true })
.bundle()
.on('error', function error(err) { console.error(err); process.exit(1); })
.on('data', function (data) { src += data })
.on('end', function () {
// require('fs').writeFileSync(require('path').join(__dirname, '../../examples/bundle.js'), src, 'utf-8')
vm.runInNewContext(src, {
setTimeout : setTimeout
, clearInterval : clearInterval
, console : console
, window : {}
} );
});
}
run('independent-overrides')
run('manipulating-overrides')
run('noCallThru')
run('argument-validation')
|
'use strict';
/*jshint asi: true */
var proxyquire = require('../..');
var vm = require('vm');
function run(name) {
var src = '';
proxyquire.browserify()
.require(require.resolve('../..'), { expose: 'proxyquireify' })
.require(require.resolve('./' + name), { entry: true })
.bundle()
.on('error', function error(err) { console.error(err); process.exit(1); })
.on('data', function (data) { src += data })
.on('end', function () {
// require('fs').writeFileSync(require('path').join(__dirname, '../../examples/bundle.js'), src, 'utf-8')
vm.runInNewContext(src, {
setTimeout : setTimeout
, clearInterval : clearInterval
, console : console
, window : {}
} );
});
}
run('independent-overrides')
run('manipulating-overrides')
run('noCallThru')
run('argument-validation')
|
Move todos into issues tracking on GitHub
|
#!/usr/bin/env python
import sys
def longest_duplicated_substring(string):
"""Return the longest duplicated substring.
Keyword Arguments:
string -- the string to examine for duplicated substrings
This approach examines each possible pair of starting points
for duplicated substrings. If the characters at those points are
the same, the match is extended up to the maximum length for those
points. Each new longest duplicated substring is recorded as the
best found so far.
This solution is optimal for the naive brute-force approach and
runs in O(n^3).
"""
lds = ""
string_length = len(string)
for i in range(string_length):
for j in range(i+1,string_length):
for substring_length in range(string_length-j):
if string[i+substring_length] != string[j+substring_length]:
break
elif substring_length + 1 > len(lds):
lds = string[i:i+substring_length+1]
return lds
if __name__ == "__main__":
print(longest_duplicated_substring(' '.join(map(str, sys.argv[1:]))))
|
#!/usr/bin/env python
import sys
# O(n^4) approach: generate all possible substrings and
# compare each for equality.
def longest_duplicated_substring(string):
"""Return the longest duplicated substring.
Keyword Arguments:
string -- the string to examine for duplicated substrings
This approach examines each possible pair of starting points
for duplicated substrings. If the characters at those points are
the same, the match is extended up to the maximum length for those
points. Each new longest duplicated substring is recorded as the
best found so far.
This solution is optimal for the naive brute-force approach and
runs in O(n^3).
"""
lds = ""
string_length = len(string)
for i in range(string_length):
for j in range(i+1,string_length):
# Alternate approach with while loop here and max update outside.
# Can also break length check into function.
for substring_length in range(string_length-j):
if string[i+substring_length] != string[j+substring_length]:
break
elif substring_length + 1 > len(lds):
lds = string[i:i+substring_length+1]
return lds
if __name__ == "__main__":
print(longest_duplicated_substring(' '.join(map(str, sys.argv[1:]))))
|
Change mobx dependency version requirement from 2.3.x to 2.x
|
import { Tracker } from 'meteor/tracker';
import { checkNpmVersions } from 'meteor/tmeasday:check-npm-versions';
checkNpmVersions({
'mobx': '2.x'
}, 'space:tracker-mobx-autorun');
const { autorun } = require('mobx');
export default (trackerMobxAutorun) => {
let mobxDisposer = null;
let computation = null;
let hasBeenStarted;
return {
start() {
let isFirstRun = true;
computation = Tracker.autorun(() => {
if (mobxDisposer) {
mobxDisposer();
isFirstRun = true;
}
mobxDisposer = autorun(() => {
if (isFirstRun) {
trackerMobxAutorun();
} else {
computation.invalidate();
}
isFirstRun = false;
});
});
hasBeenStarted = true;
},
stop() {
if (hasBeenStarted) {
computation.stop();
mobxDisposer();
}
}
};
};
|
import { Tracker } from 'meteor/tracker';
import { checkNpmVersions } from 'meteor/tmeasday:check-npm-versions';
checkNpmVersions({
'mobx': '2.3.x'
}, 'space:tracker-mobx-autorun');
const { autorun } = require('mobx');
export default (trackerMobxAutorun) => {
let mobxDisposer = null;
let computation = null;
let hasBeenStarted;
return {
start() {
let isFirstRun = true;
computation = Tracker.autorun(() => {
if (mobxDisposer) {
mobxDisposer();
isFirstRun = true;
}
mobxDisposer = autorun(() => {
if (isFirstRun) {
trackerMobxAutorun();
} else {
computation.invalidate();
}
isFirstRun = false;
});
});
hasBeenStarted = true;
},
stop() {
if (hasBeenStarted) {
computation.stop();
mobxDisposer();
}
}
};
};
|
Set Animated GIFs to repeat
|
package com.github.rtyley.android.screenshot.paparazzo.processors;
import com.madgag.gif.fmsware.AnimatedGifEncoder;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Map;
public class AnimatedGifCreator implements ScreenshotProcessor {
private final AnimatedGifEncoder gifEncoder;
private final File file;
public AnimatedGifCreator(File file) {
this.file = file;
gifEncoder = new AnimatedGifEncoder();
gifEncoder.setDelay(500);
gifEncoder.setRepeat(0);
}
@Override
public void process(BufferedImage image, Map<String, String> requestData) {
if (!gifEncoder.isStarted()) {
gifEncoder.start(file.getAbsolutePath());
}
gifEncoder.addFrame(image);
}
@Override
public void finish() {
gifEncoder.finish();
}
}
|
package com.github.rtyley.android.screenshot.paparazzo.processors;
import com.madgag.gif.fmsware.AnimatedGifEncoder;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Map;
public class AnimatedGifCreator implements ScreenshotProcessor {
private final AnimatedGifEncoder gifEncoder;
private final File file;
public AnimatedGifCreator(File file) {
this.file = file;
gifEncoder = new AnimatedGifEncoder();
gifEncoder.setDelay(500);
}
@Override
public void process(BufferedImage image, Map<String, String> requestData) {
if (!gifEncoder.isStarted()) {
gifEncoder.start(file.getAbsolutePath());
}
gifEncoder.addFrame(image);
}
@Override
public void finish() {
gifEncoder.finish();
}
}
|
Comment out preload as fetch headers
|
const fs = require('fs')
const path = require('path')
const promisify = require('util').promisify
const writeFile = promisify(fs.writeFile)
const globby = require('globby')
;(async () => {
// const posts = require('./dist/content/posts/index.json')
const files = await globby('./dist/**/*.{css,mjs}')
const headers = []
for (const file of files) {
const relative = path.relative('./dist', file)
switch (path.extname(relative)) {
case '.css':
headers.push(` Link: </${relative}>; rel=preload; as=style`)
break
case '.mjs':
headers.push(` Link: </${relative}>; rel=modulepreload; as=script`)
break
}
}
const lines = []
for (const path of ['/', '/posts/*']) {
lines.push(path)
// if (path === '/') {
// lines.push(` Link: </content/posts/${posts[posts.length - 1].slug}.md>; rel=preload; as=fetch`)
// }
lines.push(...headers)
}
// for (const post of posts) {
// lines.push(`/posts/${post.slug}`, ` Link: </content/posts/${post.slug}.md>; rel=preload; as=fetch`)
// }
await writeFile('./dist/_headers', lines.join('\n'))
})()
|
const fs = require('fs')
const path = require('path')
const promisify = require('util').promisify
const writeFile = promisify(fs.writeFile)
const globby = require('globby')
;(async () => {
const posts = require('./dist/content/posts/index.json')
const files = await globby('./dist/**/*.{css,mjs}')
const headers = []
for (const file of files) {
const relative = path.relative('./dist', file)
switch (path.extname(relative)) {
case '.css':
headers.push(` Link: </${relative}>; rel=preload; as=style`)
break
case '.mjs':
headers.push(` Link: </${relative}>; rel=modulepreload; as=script`)
break
}
}
const lines = []
for (const path of ['/', '/posts/*']) {
lines.push(path)
if (path === '/') {
lines.push(` Link: </content/posts/${posts[posts.length - 1].slug}.md>; rel=preload; as=fetch`)
}
lines.push(...headers)
}
for (const post of posts) {
lines.push(`/posts/${post.slug}`, ` Link: </content/posts/${post.slug}.md>; rel=preload; as=fetch`)
}
await writeFile('./dist/_headers', lines.join('\n'))
})()
|
Resolve the promise once we know the model is valid
|
import Ember from 'ember';
export default Ember.Controller.extend({
form: function() {
return this.store.createRecord('ssh-key');
},
actions: {
deleteKey: function(key) {
this.store.find('ssh-key', key.id).then(function(key) {
key.destroyRecord();
});
},
save: function(deferred) {
var self = this;
// Create a new record based on the values in the form
var key = this.get('key');
var name = this.get('name');
var sshKey = this.store.createRecord('ssh-key', {
name: name,
key: key
});
// validate the record
sshKey.validate();
if (sshKey.get('isValid')) {
// resolve the deferred promise
deferred.resolve();
sshKey.save().then(function() {
// clear the form
self.set('key', '');
self.set('name', '');
});
} else {
deferred.reject();
sshKey.destroyRecord();
}
}
}
});
|
import Ember from 'ember';
export default Ember.Controller.extend({
form: function() {
return this.store.createRecord('ssh-key');
},
actions: {
deleteKey: function(key) {
this.store.find('ssh-key', key.id).then(function(key) {
key.destroyRecord();
});
},
save: function(deferred) {
var self = this;
// Create a new record based on the values in the form
var key = this.get('key');
var name = this.get('name');
var sshKey = this.store.createRecord('ssh-key', {
name: name,
key: key
});
// validate the record
sshKey.validate();
if (sshKey.get('isValid')) {
sshKey.save().then(function() {
// resolve the deferred promise
deferred.resolve();
// clear the form
self.set('key', '');
self.set('name', '');
});
} else {
deferred.reject();
sshKey.destroyRecord();
}
}
}
});
|
Add support for CA certificates
better SSL support
|
from logging.handlers import SocketHandler
import ssl
class LogstashHandler(SocketHandler):
"""
Sends output to an optionally encrypted streaming logstash TCP listener.
"""
def __init__(self, host, port, keyfile=None, certfile=None, ca_certs=None, ssl=True):
SocketHandler.__init__(self, host, port)
self.keyfile = keyfile
self.certfile = certfile
self.ca_certs = ca_certs
self.ssl = ssl
def makeSocket(self, timeout=1):
s = SocketHandler.makeSocket(self, timeout)
if self.ssl:
return ssl.wrap_socket(s, keyfile=self.keyfile, certfile=self.certfile, ca_certs=self.ca_certs)
return s
def makePickle(self, record):
"""
Just format the record according to the formatter. A new line is appended to
support streaming listeners.
"""
return self.format(record) + "\n"
|
from logging.handlers import SocketHandler
import ssl
class LogstashHandler(SocketHandler):
"""
Sends output to an optionally encrypted streaming logstash TCP listener.
"""
def __init__(self, host, port, keyfile=None, certfile=None, ssl=True):
SocketHandler.__init__(self, host, port)
self.keyfile = keyfile
self.certfile = certfile
self.ssl = ssl
def makeSocket(self, timeout=1):
s = SocketHandler.makeSocket(self, timeout)
if self.ssl:
return ssl.wrap_socket(s, keyfile=self.keyfile, certfile=self.certfile)
return s
def makePickle(self, record):
"""
Just format the record according to the formatter. A new line is appended to
support streaming listeners.
"""
return self.format(record) + "\n"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.