text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix for toggle all windows
import React, {Component} from 'react'; import Mousetrap from 'mousetrap'; class StatusBar extends Component { constructor(props) { super(props); this.toggleSearchAllWindows = this.toggleSearchAllWindows.bind(this); this.onChange = this.onChange.bind(this); } componentDidMount() { Mousetrap.bind(['alt+a'], this.toggleSearchAllWindows); } render() { return ( /* jshint ignore:start */ <label className='status'> <input type='checkbox' checked={this.props.searchAllWindows} onChange={this.onChange} /> <span>Show tabs from <u>a</u>ll windows</span> </label> /* jshint ignore:end */ ); } toggleSearchAllWindows() { this.props.changeSearchAllWindows(!this.props.searchAllWindows); } onChange(evt) { this.props.changeSearchAllWindows(evt.target.checked); } } export default StatusBar;
import React, {Component} from 'react'; import Mousetrap from 'mousetrap'; class StatusBar extends Component { componentDidMount() { Mousetrap.bind(['alt+a'], this.toggleSearchAllWindows); } render() { return ( /* jshint ignore:start */ <label className='status'> <input type='checkbox' checked={this.props.searchAllWindows} onChange={this.onChange} /> <span>Show tabs from <u>a</u>ll windows</span> </label> /* jshint ignore:end */ ); } toggleSearchAllWindows() { this.props.changeSearchAllWindows(!this.props.searchAllWindows); } onChange(evt) { this.props.changeSearchAllWindows(evt.target.checked); } } export default StatusBar;
Print both custom and original error messages
package scipipe import ( // "github.com/go-errors/errors" //"os" "os" "os/exec" re "regexp" ) func ExecCmd(cmd string) string { Info.Println("Executing command: ", cmd) combOutput, err := exec.Command("bash", "-lc", cmd).CombinedOutput() if err != nil { Error.Println("Could not execute command `" + cmd + "`: " + string(combOutput)) os.Exit(1) } return string(combOutput) } func Check(err error, errMsg string) { if err != nil { Error.Println("Custom Error Message: " + errMsg) Error.Println("Original Error Message: " + err.Error()) panic(err) } } // Return the regular expression used to parse the place-holder syntax for in-, out- and // parameter ports, that can be used to instantiate a SciProcess. func getShellCommandPlaceHolderRegex() *re.Regexp { regex := "{(o|os|i|is|p):([^{}:]+)}" r, err := re.Compile(regex) Check(err, "Could not compile regex: "+regex) return r }
package scipipe import ( // "github.com/go-errors/errors" //"os" "os" "os/exec" re "regexp" ) func ExecCmd(cmd string) string { Info.Println("Executing command: ", cmd) combOutput, err := exec.Command("bash", "-lc", cmd).CombinedOutput() if err != nil { Error.Println("Could not execute command `" + cmd + "`: " + string(combOutput)) os.Exit(1) } return string(combOutput) } func Check(err error, errMsg string) { if err != nil { Error.Println(errMsg) panic(err) } } // Return the regular expression used to parse the place-holder syntax for in-, out- and // parameter ports, that can be used to instantiate a SciProcess. func getShellCommandPlaceHolderRegex() *re.Regexp { regex := "{(o|os|i|is|p):([^{}:]+)}" r, err := re.Compile(regex) Check(err, "Could not compile regex: "+regex) return r }
Use DRF's built-in search filter
# -*- coding: utf-8 -*- from django.shortcuts import render # Create your views here. from rest_framework import viewsets from rest_framework import filters from porchlightapi.models import Repository, ValueDataPoint from porchlightapi.serializers import RepositorySerializer, ValueDataPointSerializer class RepositoryViewSet(viewsets.ReadOnlyModelViewSet): """ A REST view of repositories. Provides GET listing of Repositories, filtering on name and project, and individual repsositories on id. """ queryset = Repository.objects.all() serializer_class = RepositorySerializer filter_backends = (filters.SearchFilter,) search_fields = ('name', 'project', 'url') class ValueDataPointViewSet(viewsets.ReadOnlyModelViewSet): """ A REST view of data points. """ queryset = ValueDataPoint.objects.all() serializer_class = ValueDataPointSerializer
# -*- coding: utf-8 -*- from django.shortcuts import render # Create your views here. import django_filters from rest_framework import viewsets from rest_framework import filters from porchlightapi.models import Repository, ValueDataPoint from porchlightapi.serializers import RepositorySerializer, ValueDataPointSerializer class RepositoryFilter(django_filters.FilterSet): """ Provide filtering of repository objects based on name or project. This is 'icontains' filtering, so a repo with the name "Porchlight" will match 'por', 'Por', etc. """ name = django_filters.CharFilter(name="name", lookup_type='icontains') project = django_filters.CharFilter(name="project", lookup_type='icontains') class Meta: model = Repository fields = ['name', 'project',] class RepositoryViewSet(viewsets.ReadOnlyModelViewSet): """ A REST view of repositories. Provides GET listing of Repositories, filtering on name and project, and individual repsositories on id. """ queryset = Repository.objects.all() serializer_class = RepositorySerializer filter_backends = (filters.DjangoFilterBackend,) filter_class = RepositoryFilter # filter_fields = ('name', 'project') class ValueDataPointViewSet(viewsets.ReadOnlyModelViewSet): """ A REST view of data points. """ queryset = ValueDataPoint.objects.all() serializer_class = ValueDataPointSerializer
Make profiles list null by default
package com.example; import java.util.ArrayList; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Contact { public Integer id; public String email; public String firstName; public String lastName; public String middleName; public String dateOfBirth; public Integer sex; public ArrayList<Profile> profiles; public Contact() { this.id = null; this.email = null; this.firstName = null; this.lastName = null; this.middleName = null; this.dateOfBirth = null; this.sex = null; this.profiles = null; } public Contact( Integer id, String email, String firstName, String lastName, String middleName, String dateOfBirth, Integer sex ) { this.id = id; this.email = email; this.firstName = firstName; this.lastName = lastName; this.middleName = middleName; this.dateOfBirth = dateOfBirth; this.sex = sex; this.profiles = null; } }
package com.example; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Contact { public Integer id; public String email; public String firstName; public String lastName; public String middleName; public String dateOfBirth; public Integer sex; public Contact() { this.id = null; this.email = null; this.firstName = null; this.lastName = null; this.middleName = null; this.dateOfBirth = null; this.sex = null; } public Contact( Integer id, String email, String firstName, String lastName, String middleName, String dateOfBirth, Integer sex ) { this.id = id; this.email = email; this.firstName = firstName; this.lastName = lastName; this.middleName = middleName; this.dateOfBirth = dateOfBirth; this.sex = sex; } }
Add scipy as dependency for tomviz-pipeline
from setuptools import setup, find_packages setup( name='tomviz-external', version='0.0.1', description='Tomviz python external execution infrastructure.', author='Kitware, Inc.', author_email='kitware@kitware.com', url='https://www.tomviz.org/', license='BSD 3-Clause', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: BSD 3-Clause', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5' ], packages=find_packages(), install_requires=['tqdm', 'h5py', 'numpy', 'click', 'scipy'], entry_points={ 'console_scripts': [ 'tomviz-pipeline = tomviz.cli:main' ] } )
from setuptools import setup, find_packages setup( name='tomviz-external', version='0.0.1', description='Tomviz python external execution infrastructure.', author='Kitware, Inc.', author_email='kitware@kitware.com', url='https://www.tomviz.org/', license='BSD 3-Clause', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: BSD 3-Clause', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5' ], packages=find_packages(), install_requires=['tqdm', 'h5py', 'numpy', 'click'], entry_points={ 'console_scripts': [ 'tomviz-pipeline = tomviz.cli:main' ] } )
Fix for python 3 relative import statement
""" Import the main names to top level. """ from . import models as models from .compute_fp import compute_fixed_point from .discrete_rv import DiscreteRV from .ecdf import ECDF from .estspec import smooth, periodogram, ar_periodogram from .graph_tools import DiGraph from .gridtools import cartesian, mlinspace from .gth_solve import gth_solve from .kalman import Kalman from .lae import LAE from .arma import ARMA from .lqcontrol import LQ from .lqnash import nnash from .lss import LinearStateSpace from .matrix_eqn import solve_discrete_lyapunov, solve_discrete_riccati from .mc_tools import MarkovChain, mc_compute_stationary, mc_sample_path from .quadsums import var_quadratic_sum, m_quadratic_sum from .markov import random_markov_chain, random_stochastic_matrix from .rank_nullspace import rank_est, nullspace from .robustlq import RBLQ from .tauchen import approx_markov from . import quad as quad from .util import searchsorted, random_probvec, random_sample_without_replacement #-Module Imports-# from .util import random #Add Version Attribute from .version import version as __version__
""" Import the main names to top level. """ from . import models as models from .compute_fp import compute_fixed_point from .discrete_rv import DiscreteRV from .ecdf import ECDF from .estspec import smooth, periodogram, ar_periodogram from .graph_tools import DiGraph from .gridtools import cartesian, mlinspace from .gth_solve import gth_solve from .kalman import Kalman from .lae import LAE from .arma import ARMA from .lqcontrol import LQ from .lqnash import nnash from .lss import LinearStateSpace from .matrix_eqn import solve_discrete_lyapunov, solve_discrete_riccati from .mc_tools import MarkovChain, mc_compute_stationary, mc_sample_path from .quadsums import var_quadratic_sum, m_quadratic_sum from .markov import random_markov_chain, random_stochastic_matrix from .rank_nullspace import rank_est, nullspace from .robustlq import RBLQ from .tauchen import approx_markov from . import quad as quad from .util import searchsorted, random_probvec, random_sample_without_replacement #-Module Imports-# import util.random as random #Add Version Attribute from .version import version as __version__
Return rejected promise and don't set cache if key or value is null.
const redis = require("redis") const client = redis.createClient() class Cache { /** * Retrieve an unexpired cache entry by key. * @param {String} key of the cache entry * @returns {Promise} */ get(key) { return new Promise((resolve, reject) => { client.get(key, (error, reply) => { if (reply == null) { return reject() } resolve(JSON.parse(reply)) }) }) } /** * Insert cache entry with key and value. * @param {String} key of the cache entry * @param {String} value of the cache entry * @param {Number} timeToLive the number of seconds before entry expires * @returns {Object} */ set(key, value, timeToLive = 10800) { if (value == null || key == null) return null const json = JSON.stringify(value); client.set(key, json, (error, reply) => { if (reply == 'OK') { // successfully set value with key, now set TTL for key client.expire(key, timeToLive, (e) => { if (e) console.error('Unexpected error while setting expiration for key:', key, '. Error:', error) }) } }) return value } } module.exports = Cache;
const redis = require("redis") const client = redis.createClient() class Cache { /** * Retrieve an unexpired cache entry by key. * @param {String} key of the cache entry * @returns {Promise} */ get(key) { return new Promise((resolve, reject) => { client.get(key, (error, reply) => { if (reply == null) { reject() } resolve(JSON.parse(reply)) }) }) } /** * Insert cache entry with key and value. * @param {String} key of the cache entry * @param {String} value of the cache entry * @param {Number} timeToLive the number of seconds before entry expires * @returns {Object} */ set(key, value, timeToLive = 10800) { const json = JSON.stringify(value); client.set(key, json, (error, reply) => { if (reply == 'OK') { // successfully set value with key, now set TTL for key client.expire(key, timeToLive, (e) => { if (e) console.error('Unexpected error while setting expiration for key:', key, '. Error:', error) }) } }) return value } } module.exports = Cache;
Mark strings in AuthTokenSerializer as translatable
from django.contrib.auth import authenticate from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers class AuthTokenSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, attrs): username = attrs.get('username') password = attrs.get('password') if username and password: user = authenticate(username=username, password=password) if user: if not user.is_active: msg = _('User account is disabled.') raise serializers.ValidationError() attrs['user'] = user return attrs else: msg = _('Unable to login with provided credentials.') raise serializers.ValidationError(msg) else: msg = _('Must include "username" and "password"') raise serializers.ValidationError(msg)
from django.contrib.auth import authenticate from rest_framework import serializers class AuthTokenSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, attrs): username = attrs.get('username') password = attrs.get('password') if username and password: user = authenticate(username=username, password=password) if user: if not user.is_active: raise serializers.ValidationError('User account is disabled.') attrs['user'] = user return attrs else: raise serializers.ValidationError('Unable to login with provided credentials.') else: raise serializers.ValidationError('Must include "username" and "password"')
Fix bug in file redirection
const path = require('path'); const express = require('express'); const { name, version, directories } = require('../package.json'); const app = express(); const staticPath = path.join(__dirname, `${directories.build}/`); app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'X-Requested-With'); next(); }); app.use(express.static(staticPath)); app.get('/', (req, res) => { res.send(` <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> <h1> <a href="/${name.replace(' ', '_')}/">${name} v${version}</a> </h1> </body> </html> `); }); app.get(`/${name.replace(' ', '_')}/*`, (req, res) => { const file = req.params[0] ? req.params[0] : 'index.html'; console.log(`serve file: ${file}`); res.sendfile(file, { root: `./${directories.build}` }); }); const port = 5050; app.listen(port, () => { console.log(`listening on ${port}`); });
const path = require('path'); const express = require('express'); const { name, version, directories } = require('../package.json'); const app = express(); const staticPath = path.join(__dirname, `${directories.build}/`); app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'X-Requested-With'); next(); }); app.use(express.static(staticPath)); app.get('/', (req, res) => { res.send(` <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> <h1> <a href="/${name.replace(' ', '_')}/">${name} v${version}</a> </h1> </body> </html> `); }); app.get(`/${name.replace(' ', '_')}/*`, (req, res) => { const file = req.params[0] ? req.params[0] : 'index.html'; console.log(`serve file: ${file}`); res.sendfile(file, { root: `./docs/` }); }); const port = 5050; app.listen(port, () => { console.log(`listening on ${port}`); });
Add test that exercises block includes
import os import unittest from ansiblelint import Runner, RulesCollection class TestTaskIncludes(unittest.TestCase): def setUp(self): rulesdir = os.path.join('lib', 'ansiblelint', 'rules') self.rules = RulesCollection.create_from_directory(rulesdir) def test_block_included_tasks(self): filename = 'test/blockincludes.yml' runner = Runner(self.rules, filename, [], [], []) runner.run() self.assertEqual(len(runner.playbooks), 4) def test_block_included_tasks_with_rescue_and_always(self): filename = 'test/blockincludes2.yml' runner = Runner(self.rules, filename, [], [], []) runner.run() self.assertEqual(len(runner.playbooks), 4) def test_included_tasks(self): filename = 'test/taskincludes.yml' runner = Runner(self.rules, filename, [], [], []) runner.run() self.assertEqual(len(runner.playbooks), 4) def test_include_tasks_with_block_include(self): filename = 'test/include-in-block.yml' runner = Runner(self.rules, filename, [], [], []) runner.run() self.assertEqual(len(runner.playbooks), 3)
import os import unittest from ansiblelint import Runner, RulesCollection class TestTaskIncludes(unittest.TestCase): def setUp(self): rulesdir = os.path.join('lib', 'ansiblelint', 'rules') self.rules = RulesCollection.create_from_directory(rulesdir) def test_block_included_tasks(self): filename = 'test/blockincludes.yml' runner = Runner(self.rules, filename, [], [], []) runner.run() self.assertEqual(len(runner.playbooks), 4) def test_block_included_tasks_with_rescue_and_always(self): filename = 'test/blockincludes2.yml' runner = Runner(self.rules, filename, [], [], []) runner.run() self.assertEqual(len(runner.playbooks), 4) def test_included_tasks(self): filename = 'test/taskincludes.yml' runner = Runner(self.rules, filename, [], [], []) runner.run() self.assertEqual(len(runner.playbooks), 4)
Fix typo from previous commit
import requests from bs4 import BeautifulSoup from source.models.rt_rating import RTRating class RottenTomatoesService: __URL = 'http://www.rottentomatoes.com/m/' __SEPERATOR = '_' def __init__(self, title): self.title = title def get_rt_rating(self): search_url = self.__URL + self.format_title() movie_page = requests.get(search_url) contents = movie_page.text soup = BeautifulSoup(contents, 'lxml') ratings = self.get_ratings(soup) ratings.link = search_url return ratings def format_title(self): formatted_title = self.title if formatted_title.startswith('The '): formatted_title = formatted_title.replace('The ', '', 1) if "'s" in formatted_title: formatted_title = formatted_title.replace("'s", 's') formatted_title = formatted_title.replace(' ', self.__SEPERATOR) formatted_title = formatted_title.replace('-', '') return formatted_title def get_ratings(self, soup): items = [] for item in soup.findAll(attrs={'itemprop': 'ratingValue'}): items.append(item.get_text().strip('%')) return RTRating(items)
import requests from bs4 import BeautifulSoup from source.models.rt_rating import RTRating class RottenTomatoesService: __URL = 'http://www.rottentomatoes.com/m/' __SEPERATOR = '_' def __init__(self, title): self.title = title def get_rt_rating(self): search_url = self.__URL + self.format_title() movie_page = requests.get(search_url) contents = movie_page.text soup = BeautifulSoup(contents, 'lxml') ratings = self.get_ratings(soup) ratings.link = search_url return ratings def format_title(self): formatted_title = self.title if formatted_title.startswith('The '): formatted_title = formatted_title.replace('The ', '', 1) if "'s" in formatted_title: formatted_title = formatted_title.replace("'", 's') formatted_title = formatted_title.replace(' ', self.__SEPERATOR) formatted_title = formatted_title.replace('-', '') return formatted_title def get_ratings(self, soup): items = [] for item in soup.findAll(attrs={'itemprop': 'ratingValue'}): items.append(item.get_text().strip('%')) return RTRating(items)
Undo add AuditReader diff method
<?php /* * This file is part of the Sonata package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\AdminBundle\Model; interface AuditReaderInterface { /** * @param string $className * @param string $id * @param string $revision */ public function find($className, $id, $revision); /** * @param string $className * @param int $limit * @param int $offset */ public function findRevisionHistory($className, $limit = 20, $offset = 0); /** * @param string $classname * @param string $revision */ public function findRevision($classname, $revision); /** * @param string $className * @param string $id */ public function findRevisions($className, $id); }
<?php /* * This file is part of the Sonata package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\AdminBundle\Model; interface AuditReaderInterface { /** * @param string $className * @param string $id * @param string $revision */ public function find($className, $id, $revision); /** * @param string $className * @param int $limit * @param int $offset */ public function findRevisionHistory($className, $limit = 20, $offset = 0); /** * @param string $classname * @param string $revision */ public function findRevision($classname, $revision); /** * @param string $className * @param string $id */ public function findRevisions($className, $id); /** * @param string $className * @param int $id * @param int $oldRevision * @param int $newRevision */ public function diff($className, $id, $oldRevision, $newRevision); }
Fix issue with logger not having logQuery method
<?php namespace FOS\ElasticaBundle; use Elastica\Client as ElasticaClient; use Elastica\Request; use FOS\ElasticaBundle\Logger\ElasticaLogger; /** * @author Gordon Franke <info@nevalon.de> */ class Client extends ElasticaClient { public function request($path, $method = Request::GET, $data = array(), array $query = array()) { $start = microtime(true); $response = parent::request($path, $method, $data, $query); if (null !== $this->_logger and $this->_logger instanceof ElasticaLogger) { $time = microtime(true) - $start; $connection = $this->getLastRequest()->getConnection(); $connection_array = array( 'host' => $connection->getHost(), 'port' => $connection->getPort(), 'transport' => $connection->getTransport(), ); $this->_logger->logQuery($path, $method, $data, $time, $connection_array); } return $response; } }
<?php namespace FOS\ElasticaBundle; use Elastica\Client as ElasticaClient; use Elastica\Request; /** * @author Gordon Franke <info@nevalon.de> */ class Client extends ElasticaClient { public function request($path, $method = Request::GET, $data = array(), array $query = array()) { $start = microtime(true); $response = parent::request($path, $method, $data, $query); if (null !== $this->_logger) { $time = microtime(true) - $start; $connection = $this->getLastRequest()->getConnection(); $connection_array = array( 'host' => $connection->getHost(), 'port' => $connection->getPort(), 'transport' => $connection->getTransport(), ); $this->_logger->logQuery($path, $method, $data, $time, $connection_array); } return $response; } }
Remove redundant [browsertime] on each log line.
var winston = require('winston'), path = require('path'); var DEFAULT_LOG = 'browsertime'; module.exports = { getLog: function(name) { name = name || DEFAULT_LOG; return winston.loggers.get(name); }, addLog: function(name, options) { name = name || DEFAULT_LOG; options = options || {}; if (winston.loggers.has(name)) { return winston.loggers.get(name); } var logPath = path.join(options.logDir || '', name + '.log'); var logLevel = options.verbose ? 'verbose' : 'info'; var winstonOpts = { file: { level: logLevel, json: false, filename: logPath }, console: { level: logLevel, colorize: !options.noColor, silent: !!options.silent } }; return winston.loggers.add(name, winstonOpts); } };
var winston = require('winston'), path = require('path'); var DEFAULT_LOG = 'browsertime'; module.exports = { getLog: function(name) { name = name || DEFAULT_LOG; return winston.loggers.get(name); }, addLog: function(name, options) { name = name || DEFAULT_LOG; options = options || {}; if (winston.loggers.has(name)) { return winston.loggers.get(name); } var logPath = path.join(options.logDir || '', name + '.log'); var logLevel = options.verbose ? 'verbose' : 'info'; var winstonOpts = { file: { level: logLevel, json: false, label: name, filename: logPath }, console: { level: logLevel, colorize: !options.noColor, silent: !!options.silent } }; return winston.loggers.add(name, winstonOpts); } };
Use byte array for proxy response
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.controller.api.integration.configserver; import com.yahoo.container.jdisc.HttpResponse; import java.io.IOException; import java.io.OutputStream; import java.util.Optional; /** * @author valerijf */ public class ProxyResponse extends HttpResponse { private final byte[] content; private final String contentType; public ProxyResponse(byte[] content, String contentType, int status) { super(status); this.content = content; this.contentType = contentType; } @Override public void render(OutputStream outputStream) throws IOException { outputStream.write(content); } @Override public String getContentType() { return Optional.ofNullable(contentType).orElseGet(super::getContentType); } }
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.controller.api.integration.configserver; import com.yahoo.container.jdisc.HttpResponse; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.util.Optional; /** * @author valerijf */ public class ProxyResponse extends HttpResponse { private final String content; private final String contentType; public ProxyResponse(String content, String contentType, int status) { super(status); this.content = content; this.contentType = contentType; } @Override public void render(OutputStream outputStream) throws IOException { outputStream.write(content.getBytes(StandardCharsets.UTF_8)); } @Override public String getContentType() { return Optional.ofNullable(contentType).orElseGet(super::getContentType); } }
Make printview work with jupyter
// convert current notebook to html by calling "ipython nbconvert" and open static html file in new tab define([ 'base/js/namespace', 'jquery', ], function(IPython, $) { "use strict"; if (IPython.version[0] < 3) { console.log("This extension requires at least IPython 3.x") return } /** * Call nbconvert using the current notebook server profile * */ var nbconvertPrintView = function () { var name = IPython.notebook.notebook_name; var command = 'ip=get_ipython(); import os; os.system(\"jupyter nbconvert --profile=%s --to html ' + name + '\" % ip.profile)'; callbacks = { iopub : { output : function() { var url = name.split('.ipynb')[0] + '.html'; var win=window.open(url, '_blank'); win.focus(); } } }; IPython.notebook.kernel.execute(command, callbacks); //$('#doPrintView').blur(); }; var load_ipython_extension = function () { IPython.toolbar.add_buttons_group([ { id : 'doPrintView', label : 'Create static print view', icon : 'fa-print', callback : nbconvertPrintView } ]) } return { load_ipython_extension : load_ipython_extension } })
// convert current notebook to html by calling "ipython nbconvert" and open static html file in new tab define([ 'base/js/namespace', 'jquery', ], function(IPython, $) { "use strict"; if (IPython.version[0] < 3) { console.log("This extension requires IPython 3.x") return } /** * Call nbconvert using the current notebook server profile * */ var nbconvertPrintView = function () { var kernel = IPython.notebook.kernel; var name = IPython.notebook.notebook_name; var command = 'ip=get_ipython(); import os; os.system(\"ipython nbconvert --profile=%s --to html ' + name + '\" % ip.profile)'; function callback(out_type, out_data) { var url = name.split('.ipynb')[0] + '.html'; var win=window.open(url, '_blank'); win.focus(); } kernel.execute(command, { shell: { reply : callback } }); $('#doPrintView').blur() }; IPython.toolbar.add_buttons_group([ { id : 'doPrintView', label : 'Create static print view', icon : 'fa-print', callback : nbconvertPrintView } ]) })
Revert "Rename generic names to single letter" This reverts commit d7d5eff52385fbe224d36666223948ada966db35.
<%# Copyright 2013-2018 the original author or authors from the JHipster project. This file is part of the JHipster project, see http://www.jhipster.tech/ for more information. 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 <%=packageName%>.service.mapper; import java.util.List; /** * Contract for a generic dto to entity mapper. * * @param <DTO> - DTO type parameter. * @param <ENTITY> - Entity type parameter. */ public interface EntityMapper <DTO, ENTITY> { ENTITY toEntity(DTO dto); DTO toDto(ENTITY entity); List <ENTITY> toEntity(List<DTO> dtoList); List <DTO> toDto(List<ENTITY> entityList); }
<%# Copyright 2013-2018 the original author or authors from the JHipster project. This file is part of the JHipster project, see http://www.jhipster.tech/ for more information. 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 <%=packageName%>.service.mapper; import java.util.List; /** * Contract for a generic dto to entity mapper. * * @param <D> - DTO type parameter. * @param <E> - Entity type parameter. */ public interface EntityMapper <D, E> { E toEntity(D dto); D toDto(E entity); List <E> toEntity(List<D> dtoList); List <D> toDto(List<E> entityList); }
Remove deprecated --dev composer arg
#!/usr/bin/env php <?php chdir(__DIR__); $returnStatus = null; passthru('composer install', $returnStatus); if ($returnStatus !== 0) { exit(1); } passthru( './vendor/bin/phpcs --standard=PSR2 src tests *.php', $returnStatus ); if ($returnStatus !== 0) { exit(1); } passthru('./vendor/bin/phpunit', $returnStatus); if ($returnStatus !== 0) { exit(1); } $xml = new SimpleXMLElement(file_get_contents('clover.xml')); foreach ($xml->xpath('//file/metrics') as $metric) { if ((int)$metric['elements'] !== (int)$metric['coveredelements']) { fputs(STDERR, "Code coverage was NOT 100%\n"); exit(1); } } echo "Code coverage was 100%\n";
#!/usr/bin/env php <?php chdir(__DIR__); $returnStatus = null; passthru('composer install --dev', $returnStatus); if ($returnStatus !== 0) { exit(1); } passthru( './vendor/bin/phpcs --standard=PSR2 src tests *.php', $returnStatus ); if ($returnStatus !== 0) { exit(1); } passthru('./vendor/bin/phpunit', $returnStatus); if ($returnStatus !== 0) { exit(1); } $xml = new SimpleXMLElement(file_get_contents('clover.xml')); foreach ($xml->xpath('//file/metrics') as $metric) { if ((int)$metric['elements'] !== (int)$metric['coveredelements']) { fputs(STDERR, "Code coverage was NOT 100%\n"); exit(1); } } echo "Code coverage was 100%\n";
message: Add Error and Warning functions
// ------------------------------------------------- // ------------- MessageHandler -------------------- // ------------------------------------------------- "use strict"; function Send(command, data) { postMessage( { "command" : command, "data" : data } ); } function Debug(message) { Send("Debug", message); } function Abort() { Debug("Abort execution."); Send("Stop", {}); throw new Error('Kill worker'); } function Error(message) { Send("Debug", "Error: " + message); Abort(); } function Warn(message) { Send("Debug", "Warning: " + message); } var messagemap = new Object(); function Register(message, OnReceive) { messagemap[message] = OnReceive; } // this is a global object of the worker onmessage = function(e) { if (typeof messagemap[e.data.command] == 'function') { messagemap[e.data.command](e.data.data); return; } } module.exports.Register = Register; module.exports.Debug = Debug; module.exports.Error = Error; module.exports.Abort = Abort; module.exports.Send = Send;
// ------------------------------------------------- // ------------- MessageHandler -------------------- // ------------------------------------------------- "use strict"; function Send(command, data) { postMessage( { "command" : command, "data" : data } ); } function Debug(message) { Send("Debug", message); } function Abort() { Debug("Abort execution."); Send("Stop", {}); throw new Error('Kill worker'); } var messagemap = new Object(); function Register(message, OnReceive) { messagemap[message] = OnReceive; } // this is a global object of the worker onmessage = function(e) { if (typeof messagemap[e.data.command] == 'function') { messagemap[e.data.command](e.data.data); return; } } module.exports.Register = Register; module.exports.Debug = Debug; module.exports.Abort = Abort; module.exports.Send = Send;
Modify main loop code of FilterChain.parse()
const AstNode = require('./ast-node'); class FilterChain extends AstNode { type() { return 'filter_chain'; } /** * @param {ParseContext} context * @return {boolean} */ read(context) { return true; } /** * @param {ParseContext} context * @return {AstNodeParseResult} */ parse(context) { const config = context.config(); const tm = context.sourceTextManager(); const filters = []; tm.whitespace(); while (tm.charIs('|')) { tm.next('|'); tm.whitespace(); filters.push(context.parse('filter')); tm.whitespace(); if (tm.charIs(config.closeDelimiter())) { break; } } return { type: this.type(), filters: filters, }; } } module.exports = FilterChain;
const AstNode = require('./ast-node'); class FilterChain extends AstNode { type() { return 'filter_chain'; } /** * @param {ParseContext} context * @return {boolean} */ read(context) { return true; } /** * @param {ParseContext} context * @return {AstNodeParseResult} */ parse(context) { const config = context.config(); const tm = context.sourceTextManager(); const filters = []; while (!tm.eof()) { tm.whitespace(); if (!tm.charIs('|')) { break; } tm.next('|'); tm.whitespace(); filters.push(context.parse('filter')); if (tm.charIs(config.closeDelimiter())) { break; } } return { type: this.type(), filters: filters, }; } } module.exports = FilterChain;
Store original URL before logging in so that user is properly redirected on login.
package controllers; import java.util.ArrayList; import com.feth.play.module.pa.PlayAuthenticate; import com.feth.play.module.pa.user.AuthUser; import models.User; import play.Logger; import play.mvc.Http.Context; import play.mvc.Result; import play.mvc.Security; public class Secured extends Security.Authenticator { @Override public String getUsername(final Context ctx) { Logger.debug("Secured::getUsername " + ctx); final AuthUser u = PlayAuthenticate.getUser(ctx.session()); if (u != null) { User the_user = User.findByAuthUserIdentity(u); if (the_user == null) { return null; } return u.getId(); } PlayAuthenticate.storeOriginalUrl(ctx); return null; } @Override public Result onUnauthorized(final Context ctx) { return redirect(controllers.routes.Public.index()); } }
package controllers; import java.util.ArrayList; import com.feth.play.module.pa.PlayAuthenticate; import com.feth.play.module.pa.user.AuthUser; import models.User; import play.Logger; import play.mvc.Http.Context; import play.mvc.Result; import play.mvc.Security; public class Secured extends Security.Authenticator { @Override public String getUsername(final Context ctx) { Logger.debug("Secured::getUsername " + ctx); final AuthUser u = PlayAuthenticate.getUser(ctx.session()); if (u != null) { User the_user = User.findByAuthUserIdentity(u); if (the_user == null) { return null; } return u.getId(); } return null; } @Override public Result onUnauthorized(final Context ctx) { return redirect(com.feth.play.module.pa.controllers.routes.Authenticate.logout()); } }
Add metalsmith config to gulp config
module.exports = { // Autoprefixer autoprefixer: { // https://github.com/postcss/autoprefixer#browsers browsers: [ 'Explorer >= 10', 'ExplorerMobile >= 10', 'Firefox >= 30', 'Chrome >= 34', 'Safari >= 7', 'Opera >= 23', 'iOS >= 7', 'Android >= 4.4', 'BlackBerry >= 10' ] }, // BrowserSync browserSync: { browser: 'default', // or ["google chrome", "firefox"] https: false, // Enable https for localhost development. notify: false, // The small pop-over notifications in the browser. port: 9000 }, // GitHub Pages ghPages: { branch: 'gh-pages', domain: 'polymer-starter-kit.startpolymer.org', // change it! origin: 'origin' }, // Metalsmith metalsmith: { configFile: './psa-config.yaml' }, // PageSpeed Insights // Please feel free to use the `nokey` option to try out PageSpeed // Insights as part of your build process. For more frequent use, // we recommend registering for your own API key. For more info: // https://developers.google.com/speed/docs/insights/v1/getting_started pageSpeed: { key: '', // need uncomment in task nokey: true, site: 'http://polymer-starter-kit.startpolymer.org', // change it! strategy: 'mobile' // or desktop } };
module.exports = { // Autoprefixer autoprefixer: { // https://github.com/postcss/autoprefixer#browsers browsers: [ 'Explorer >= 10', 'ExplorerMobile >= 10', 'Firefox >= 30', 'Chrome >= 34', 'Safari >= 7', 'Opera >= 23', 'iOS >= 7', 'Android >= 4.4', 'BlackBerry >= 10' ] }, // BrowserSync browserSync: { browser: 'default', // or ["google chrome", "firefox"] https: false, // Enable https for localhost development. notify: false, // The small pop-over notifications in the browser. port: 9000 }, // GitHub Pages ghPages: { branch: 'gh-pages', domain: 'polymer-starter-kit.startpolymer.org', // change it! origin: 'origin' }, // PageSpeed Insights // Please feel free to use the `nokey` option to try out PageSpeed // Insights as part of your build process. For more frequent use, // we recommend registering for your own API key. For more info: // https://developers.google.com/speed/docs/insights/v1/getting_started pageSpeed: { key: '', // need uncomment in task nokey: true, site: 'http://polymer-starter-kit.startpolymer.org', // change it! strategy: 'mobile' // or desktop } };
Return metadata which are in {"class": string, "value": string} format only
class MetaData { constructor(data, extra_key) { this.data = data; this.extra_key = extra_key; } get(keys) { return this.slice(keys).filter((k, i) => typeof k.value === 'string'); } slice(keys) { if (!this.data) return []; if (this.extra_key) return this.slice_with_extra_key(keys); else return this.slice_without_extra_key(keys); } slice_with_extra_key(keys) { const data = []; keys.forEach((k) => { if (this.data[k] && this.data[k][this.extra_key]) data.push({class: k, value: this.data[k][this.extra_key]}); }); return data; } slice_without_extra_key(keys) { const data = []; keys.forEach((k) => { if (this.data[k]) data.push({class: k, value: this.data[k]}); }); return data; } } module.exports = MetaData;
class MetaData { constructor(data, extra_key) { this.data = data; this.extra_key = extra_key; } get(keys) { if (!this.data) return []; if (this.extra_key) return this.slice_with_extra_key(keys); else return this.slice_without_extra_key(keys); } slice_with_extra_key(keys) { const data = []; keys.forEach((k) => { if (this.data[k] && this.data[k][this.extra_key]) data.push({class: k, value: this.data[k][this.extra_key]}); }); return data; } slice_without_extra_key(keys) { const data = []; keys.forEach((k) => { if (this.data[k]) data.push({class: k, value: this.data[k]}); }); return data; } } module.exports = MetaData;
Move reportChange to after change occurs
import javax.annotation.Generated; import javax.annotation.Nonnull; import org.realityforge.arez.ArezContext; import org.realityforge.arez.Observable; @Generated( "org.realityforge.arez.processor.ArezProcessor" ) public final class Arez_TimeModel extends TimeModel { private final ArezContext $arez$_context; private final Observable $arez$_time; protected Arez_TimeModel( @Nonnull final ArezContext $arez$_context, final long time ) { super( time ); this.$arez$_context = $arez$_context; this.$arez$_time = $arez$_context.createObservable( "Time.time" ); } @Override public long getTime() { this.$arez$_time.reportObserved(); return super.getTime(); } @Override public void setTime( final long time ) { if ( super.getTime() != time ) { super.setTime( time ); this.$arez$_time.reportChanged(); } } @Override public void updateTime() { this.$arez$_context.safeProcedure( "Time.updateTime", true, () -> super.updateTime() ); } }
import javax.annotation.Generated; import javax.annotation.Nonnull; import org.realityforge.arez.ArezContext; import org.realityforge.arez.Observable; @Generated( "org.realityforge.arez.processor.ArezProcessor" ) public final class Arez_TimeModel extends TimeModel { private final ArezContext $arez$_context; private final Observable $arez$_time; protected Arez_TimeModel( @Nonnull final ArezContext $arez$_context, final long time ) { super( time ); this.$arez$_context = $arez$_context; this.$arez$_time = $arez$_context.createObservable( "Time.time" ); } @Override public long getTime() { this.$arez$_time.reportObserved(); return super.getTime(); } @Override public void setTime( final long time ) { if ( super.getTime() != time ) { this.$arez$_time.reportChanged(); super.setTime( time ); } } @Override public void updateTime() { this.$arez$_context.safeProcedure( "Time.updateTime", true, () -> super.updateTime() ); } }
Integrate secure middleware for handling https connections
package webhook import ( "os" "strings" "io/ioutil" "encoding/json" ) type Configuration struct { WebServerPort uint16 `json:"webserver-port"` EndpointName string `json:"endpoint-name"` ExchangeName string `json:"exchange-name"` QueueURI string `json:"queue-uri"` PoolConfig PoolConfiguration `json:"pool-config"` SecureConfig SecureConfiguration } type PoolConfiguration struct { MaxTotal int `json:"max-total"` MinIdle int `json:"min-idle"` MaxIdle int `json:"max-idle"` } type SecureConfiguration struct { IsDevelopment bool `json:"is-development"` } func LoadConfiguration(path string) Configuration { file := getFile(path) raw, err := ioutil.ReadFile(file) FailOnError(err, "Can not load configuration") var cfg Configuration err = json.Unmarshal(raw, &cfg) FailOnError(err, "Can not parse configuration") return cfg } func getFile(path string) string { env := os.Getenv("GO_ENV") if IsEmpty(env) { env = "development" } else { env = strings.ToLower(strings.TrimSpace(env)) } return path + env + ".json" }
package webhook import ( "os" "strings" "io/ioutil" "encoding/json" ) type Configuration struct { WebServerPort uint16 `json:"webserver-port"` EndpointName string `json:"endpoint-name"` ExchangeName string `json:"exchange-name"` QueueURI string `json:"queue-uri"` PoolConfig PoolConfiguration `json:"pool-config"` } type PoolConfiguration struct { MaxTotal int `json:"max-total"` MinIdle int `json:"min-idle"` MaxIdle int `json:"max-idle"` } func LoadConfiguration(path string) Configuration { file := getFile(path) raw, err := ioutil.ReadFile(file) FailOnError(err, "Can not load configuration") var cfg Configuration err = json.Unmarshal(raw, &cfg) FailOnError(err, "Can not parse configuration") return cfg } func getFile(path string) string { env := os.Getenv("GO_ENV") if IsEmpty(env) { env = "development" } else { env = strings.ToLower(strings.TrimSpace(env)) } return path + env + ".json" }
Add actual setting of new json
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ import moment from 'moment'; import french from 'moment/locale/fr'; import english from 'moment/locale/en-nz'; import { authStrings, buttonStrings, generalStrings, modalStrings, navStrings, pageInfoStrings, programStrings, syncStrings, tableStrings, LANGUAGE_CODES, formInputStrings, dispensingStrings, } from './index'; const DATE_CONFIGS = { DEFAULT: english, [LANGUAGE_CODES.FRENCH]: french, }; export const setDateLocale = languageCode => moment.updateLocale(languageCode, DATE_CONFIGS[languageCode] || DATE_CONFIGS.DEFAULT); export function setCurrentLanguage(language) { authStrings.setLanguage(language); buttonStrings.setLanguage(language); generalStrings.setLanguage(language); modalStrings.setLanguage(language); navStrings.setLanguage(language); pageInfoStrings.setLanguage(language); tableStrings.setLanguage(language); syncStrings.setLanguage(language); programStrings.setLanguage(language); formInputStrings.setLanguage(language); dispensingStrings.setLanguage(language); } export default setCurrentLanguage;
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ import moment from 'moment'; import french from 'moment/locale/fr'; import english from 'moment/locale/en-nz'; import { authStrings, buttonStrings, generalStrings, modalStrings, navStrings, pageInfoStrings, programStrings, syncStrings, tableStrings, LANGUAGE_CODES, } from './index'; const DATE_CONFIGS = { DEFAULT: english, [LANGUAGE_CODES.FRENCH]: french, }; export const setDateLocale = languageCode => moment.updateLocale(languageCode, DATE_CONFIGS[languageCode] || DATE_CONFIGS.DEFAULT); export function setCurrentLanguage(language) { authStrings.setLanguage(language); buttonStrings.setLanguage(language); generalStrings.setLanguage(language); modalStrings.setLanguage(language); navStrings.setLanguage(language); pageInfoStrings.setLanguage(language); tableStrings.setLanguage(language); syncStrings.setLanguage(language); programStrings.setLanguage(language); } export default setCurrentLanguage;
Add @Keep annotation to not over-optimize my enums!
package com.pr0gramm.app.services.config; import android.support.annotation.Keep; import org.immutables.gson.Gson; import org.immutables.value.Value; /** */ @Value.Immutable @Gson.TypeAdapters public abstract class Config { @Value.Default public boolean extraCategories() { return true; } @Value.Default public long maxUploadSizeNormal() { return 6 * 1024 * 1024; } @Value.Default public long maxUploadSizePremium() { return 12 * 1024 * 1024; } @Value.Default public boolean searchUsingTagService() { return false; } @Value.Default public boolean secretSanta() { return false; } @Value.Default public AdType adType() { return AdType.NONE; } @Keep public enum AdType { NONE, FEED, MAIN; } }
package com.pr0gramm.app.services.config; import org.immutables.gson.Gson; import org.immutables.value.Value; /** */ @Value.Immutable @Gson.TypeAdapters public abstract class Config { @Value.Default public boolean extraCategories() { return true; } @Value.Default public long maxUploadSizeNormal() { return 6 * 1024 * 1024; } @Value.Default public long maxUploadSizePremium() { return 12 * 1024 * 1024; } @Value.Default public boolean searchUsingTagService() { return false; } @Value.Default public boolean secretSanta() { return false; } @Value.Default public AdType adType() { return AdType.NONE; } public enum AdType { NONE, FEED, MAIN; } }
Set valid parents on carousel item
/* * Copyright (c) 2014 Darren Scott - All Rights Reserved * * This program is distributed under LGPL Version 2.1 in the hope that * it will be useful, but WITHOUT ANY WARRANTY. */ package org.bootstrapjsp.tags.core.carousel; import javax.servlet.jsp.tagext.JspTag; import org.bootstrapjsp.facet.ActiveFacet; import org.bootstrapjsp.tags.html.Div; import org.tldgen.annotations.Attribute; import org.tldgen.annotations.Tag; /** * A carousel item. * <p> * &lt;div class="item"&gt;...&lt;/div&gt; * </p> */ @Tag(name="carouselitem",dynamicAttributes=true) public class CarouselItem extends Div { @SuppressWarnings("unchecked") public CarouselItem() { super("item"); super.addFacet(new ActiveFacet(false)); super.setValidParents(Carousel.class); } /** * Sets a caption for this item. The caption is automatically * wrapped in a &lt;carouselcaption&gt;. */ @Attribute(rtexprvalue=true) public void setCaption(String caption) { super.appendChild(new CarouselCaption(caption), BEFORE_BODY); } @Override public void setParent(JspTag parent) { if (parent != null) { if (parent instanceof Carousel) { ((Carousel) parent).addItem(this); } } super.setParent(parent); } }
/* * Copyright (c) 2014 Darren Scott - All Rights Reserved * * This program is distributed under LGPL Version 2.1 in the hope that * it will be useful, but WITHOUT ANY WARRANTY. */ package org.bootstrapjsp.tags.core.carousel; import javax.servlet.jsp.tagext.JspTag; import org.bootstrapjsp.facet.ActiveFacet; import org.bootstrapjsp.tags.html.Div; import org.tldgen.annotations.Attribute; import org.tldgen.annotations.Tag; /** * A carousel item. * <p> * &lt;div class="item"&gt;...&lt;/div&gt; * </p> */ @Tag(name="carouselitem",dynamicAttributes=true) public class CarouselItem extends Div { public CarouselItem() { super("item"); super.addFacet(new ActiveFacet(false)); } /** * Sets a caption for this item. The caption is automatically * wrapped in a &lt;carouselcaption&gt;. */ @Attribute(rtexprvalue=true) public void setCaption(String caption) { super.appendChild(new CarouselCaption(caption), BEFORE_BODY); } @Override public void setParent(JspTag parent) { if (parent != null) { if (parent instanceof Carousel) { ((Carousel) parent).addItem(this); } else { throw new IllegalArgumentException("Illegal parent"); } } super.setParent(parent); } }
Add some missing return types to internal/final classes
<?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\Security\Core\Authorization\Voter; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Event\VoteEvent; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; /** * Decorates voter classes to send result events. * * @author Laurent VOULLEMIER <laurent.voullemier@gmail.com> * * @internal */ class TraceableVoter implements VoterInterface { private $voter; private $eventDispatcher; public function __construct(VoterInterface $voter, EventDispatcherInterface $eventDispatcher) { $this->voter = $voter; $this->eventDispatcher = $eventDispatcher; } public function vote(TokenInterface $token, $subject, array $attributes): int { $result = $this->voter->vote($token, $subject, $attributes); $this->eventDispatcher->dispatch(new VoteEvent($this->voter, $subject, $attributes, $result), 'debug.security.authorization.vote'); return $result; } public function getDecoratedVoter(): VoterInterface { return $this->voter; } }
<?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\Security\Core\Authorization\Voter; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Event\VoteEvent; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; /** * Decorates voter classes to send result events. * * @author Laurent VOULLEMIER <laurent.voullemier@gmail.com> * * @internal */ class TraceableVoter implements VoterInterface { private $voter; private $eventDispatcher; public function __construct(VoterInterface $voter, EventDispatcherInterface $eventDispatcher) { $this->voter = $voter; $this->eventDispatcher = $eventDispatcher; } public function vote(TokenInterface $token, $subject, array $attributes) { $result = $this->voter->vote($token, $subject, $attributes); $this->eventDispatcher->dispatch(new VoteEvent($this->voter, $subject, $attributes, $result), 'debug.security.authorization.vote'); return $result; } public function getDecoratedVoter(): VoterInterface { return $this->voter; } }
TASK: Change typo3.org reference to neos.io This change uses www.neos.io instead of typo3.org for testing the CurlEngine.
<?php namespace TYPO3\Flow\Tests\Functional\Http\Client; /* * This file is part of the TYPO3.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. */ /** * Functional tests for the HTTP client internal request engine * * @requires extension curl */ class CurlEngineTest extends \TYPO3\Flow\Tests\FunctionalTestCase { /** * @var boolean */ protected $testableSecurityEnabled = true; /** * @return void */ public function setUp() { parent::setUp(); $curlEngine = $this->objectManager->get(\TYPO3\Flow\Http\Client\CurlEngine::class); $this->browser->setRequestEngine($curlEngine); } /** * Check if the Curl Engine can send a GET request to neos.io * * @test */ public function getRequestReturnsResponse() { $response = $this->browser->request('https://www.neos.io'); $this->assertContains('This website is powered by Neos', $response->getContent()); } }
<?php namespace TYPO3\Flow\Tests\Functional\Http\Client; /* * This file is part of the TYPO3.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. */ /** * Functional tests for the HTTP client internal request engine * * @requires extension curl */ class CurlEngineTest extends \TYPO3\Flow\Tests\FunctionalTestCase { /** * @var boolean */ protected $testableSecurityEnabled = true; /** * @return void */ public function setUp() { parent::setUp(); $curlEngine = $this->objectManager->get(\TYPO3\Flow\Http\Client\CurlEngine::class); $this->browser->setRequestEngine($curlEngine); } /** * Check if the Curl Engine can send a GET request to typo3.org * * @test */ public function getRequestReturnsResponse() { $response = $this->browser->request('http://typo3.org'); $this->assertContains('This website is powered by TYPO3', $response->getContent()); } }
Remove a double call to requestLayout in applyTransformation
package com.desmond.squarecamera; import android.support.annotation.NonNull; import android.view.View; import android.view.animation.Animation; import android.view.animation.Transformation; /** * Created by desmond on 4/8/15. */ public class ResizeAnimation extends Animation { final int mStartLength; final int mFinalLength; final boolean mIsPortrait; final View mView; public ResizeAnimation(@NonNull View view, final ImageParameters imageParameters) { mStartLength = view.getContext().getResources().getDimensionPixelSize(R.dimen.cover_start_width); mFinalLength = imageParameters.getAnimationParameter(); mIsPortrait = imageParameters.isPortrait(); mView = view; } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { int newLength = (int) (mStartLength + (mFinalLength - mStartLength) * interpolatedTime); if (mIsPortrait) { mView.getLayoutParams().height = newLength; } else { mView.getLayoutParams().width = newLength; } } @Override public void initialize(int width, int height, int parentWidth, int parentHeight) { super.initialize(width, height, parentWidth, parentHeight); } @Override public boolean willChangeBounds() { return true; } }
package com.desmond.squarecamera; import android.support.annotation.NonNull; import android.view.View; import android.view.animation.Animation; import android.view.animation.Transformation; /** * Created by desmond on 4/8/15. */ public class ResizeAnimation extends Animation { final int mStartLength; final int mFinalLength; final boolean mIsPortrait; final View mView; public ResizeAnimation(@NonNull View view, final ImageParameters imageParameters) { mStartLength = view.getContext().getResources().getDimensionPixelSize(R.dimen.cover_start_width); mFinalLength = imageParameters.getAnimationParameter(); mIsPortrait = imageParameters.isPortrait(); mView = view; } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { int newLength = (int) (mStartLength + (mFinalLength - mStartLength) * interpolatedTime); if (mIsPortrait) { mView.getLayoutParams().height = newLength; } else { mView.getLayoutParams().width = newLength; } mView.requestLayout(); } @Override public void initialize(int width, int height, int parentWidth, int parentHeight) { super.initialize(width, height, parentWidth, parentHeight); } @Override public boolean willChangeBounds() { return true; } }
Switch to responsive bootstrap CSS and add needed nav items
<!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, initial-scale=1.0" /> <link rel="stylesheet" type="text/css" href="/assets/style/bootstrap-responsive.min.css" media="screen,projection" /> </head> <body> <div class="navbar"> <div class="navbar-inner"> <div class="container"> <nav> <ul class="nav"> <li> <a href="/">Home</a> </li> <li> <a href="/contact">Contact</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">
Fix parsing exception on unknown decorator
const { DataParser } = require('./DataParser'); const { DataEntry } = require('../entity/DataEntry'); const { Syntax } = require('../Enum'); class ClassComponentDataParser extends DataParser { parse (node) { switch (node.type) { case Syntax.ClassProperty: this.parseData(node, node.key, node.value || node); break; default: switch (node.expression.type) { case Syntax.AssignmentExpression: this.parseData(node, node.expression.left.property, node.expression.right); break; } break; } } parseData (node, key, value) { const ref = this.getValue(value); const entry = new DataEntry(key.name, { type: this.getTSType(node, ref.kind), value: ref.raw }); this.root.scope[entry.name] = ref.raw; this.parseEntryComment(entry, node); DataParser.mergeEntryKeywords(entry); if (node.accessibility) { entry.visibility = node.accessibility; } this.emit(entry); } } module.exports.ClassComponentDataParser = ClassComponentDataParser;
const { DataParser } = require('./DataParser'); const { DataEntry } = require('../entity/DataEntry'); const { Syntax } = require('../Enum'); class ClassComponentDataParser extends DataParser { parse (node) { switch (node.type) { case Syntax.ClassProperty: this.parseData(node, node.key, node.value); break; default: switch (node.expression.type) { case Syntax.AssignmentExpression: this.parseData(node, node.expression.left.property, node.expression.right); break; } break; } } parseData (node, key, value) { const ref = this.getValue(value); const entry = new DataEntry(key.name, { type: this.getTSType(node, ref.kind), value: ref.raw }); this.root.scope[entry.name] = ref.raw; this.parseEntryComment(entry, node); DataParser.mergeEntryKeywords(entry); if (node.accessibility) { entry.visibility = node.accessibility; } this.emit(entry); } } module.exports.ClassComponentDataParser = ClassComponentDataParser;
Update helptext for `service-level` command
<?php namespace Pantheon\Terminus\Commands\ServiceLevel; use Pantheon\Terminus\Commands\TerminusCommand; use Pantheon\Terminus\Site\SiteAwareInterface; use Pantheon\Terminus\Site\SiteAwareTrait; /** * Class SetCommand * @package Pantheon\Terminus\Commands\ServiceLevel */ class SetCommand extends TerminusCommand implements SiteAwareInterface { use SiteAwareTrait; /** * Upgrades or downgrades a site's service level. * * @authorize * * @command service-level:set * * @param string $site_id Site name * @param string $level [free|basic|pro|business] Service level * * @usage terminus service-level:set <site> <service_level> * Updates <site>'s service level to <service_level>. */ public function set($site_id, $level) { $site = $this->getSite($site_id); $workflow = $site->updateServiceLevel($level); $this->log()->notice('Setting plan of "{site_id}" to "{level}".', compact('site_id', 'level')); while (!$workflow->checkProgress()) { // @TODO: Add Symfony progress bar to indicate that something is happening. } $this->log()->notice($workflow->getMessage()); } }
<?php namespace Pantheon\Terminus\Commands\ServiceLevel; use Pantheon\Terminus\Commands\TerminusCommand; use Pantheon\Terminus\Site\SiteAwareInterface; use Pantheon\Terminus\Site\SiteAwareTrait; /** * Class SetCommand * @package Pantheon\Terminus\Commands\ServiceLevel */ class SetCommand extends TerminusCommand implements SiteAwareInterface { use SiteAwareTrait; /** * Set a site's service level * * @authorize * * @command service-level:set * * @param string $site_id The name of the site to set the service level of * @param string $level [free|basic|pro|business] The service level to set the site to */ public function set($site_id, $level) { $site = $this->getSite($site_id); $workflow = $site->updateServiceLevel($level); $this->log()->notice('Setting plan of "{site_id}" to "{level}".', compact('site_id', 'level')); while (!$workflow->checkProgress()) { // @TODO: Add Symfony progress bar to indicate that something is happening. } $this->log()->notice($workflow->getMessage()); } }
Test more stuff in python
import sys from PyQt5 import QtWidgets, QtGui from QHexEdit import QHexEdit, QHexEditData if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) # QHexEditData* hexeditdata = QHexEditData::fromFile("test.py"); hexeditdata = QHexEditData.fromFile('test.py') # QHexEdit* hexedit = new QHexEdit(); # hexedit->setData(hexeditdata); hexedit = QHexEdit() hexedit.setData(hexeditdata) hexedit.show() # hexedit->commentRange(0, 12, "I'm a comment!"); hexedit.commentRange(0, 12, "I'm a comment!") # hexedit->highlightBackground(0, 10, QColor(Qt::Red)); hexedit.highlightBackground(0, 10, QtGui.QColor(255, 0, 0)) sys.exit(app.exec_())
import sys from PyQt5 import QtWidgets from QHexEdit import QHexEdit, QHexEditData class HexEdit(QHexEdit): def __init__(self, fileName=None): super(HexEdit, self).__init__() file = open(fileName) data = file.read() self.setData(data) self.setReadOnly(False) if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) # QHexEditData* hexeditdata = QHexEditData::fromFile("data.bin"); data = QHexEditData.fromFile('test.py') # QHexEdit* hexedit = new QHexEdit(); # hexedit->setData(hexeditdata); mainWin = QHexEdit() mainWin.setData(data) mainWin.show() sys.exit(app.exec_())
Fix page's title in pdf header/footer
var juice = require('juice'); var WebsiteGenerator = require('../website'); var JSONUtils = require('../../json'); var Templating = require('../../templating'); var Promise = require('../../utils/promise'); /** Generate PDF header/footer templates @param {Output} output @param {String} type @return {String} */ function getPDFTemplate(output, type) { var filePath = 'pdf_' + type + '.html'; var outputRoot = output.getRoot(); var engine = WebsiteGenerator.createTemplateEngine(output, filePath); // Generate context var context = JSONUtils.encodeOutput(output); context.page = { num: '_PAGENUM_', title: '_SECTION_' }; // Render the theme return Templating.renderFile(engine, 'ebook/' + filePath, context) // Inline css and assets .then(function(tplOut) { return Promise.nfcall(juice.juiceResources, tplOut.getContent(), { webResources: { relativeTo: outputRoot } }); }); } module.exports = getPDFTemplate;
var juice = require('juice'); var WebsiteGenerator = require('../website'); var JSONUtils = require('../../json'); var Templating = require('../../templating'); var Promise = require('../../utils/promise'); /** Generate PDF header/footer templates @param {Output} output @param {String} type @return {String} */ function getPDFTemplate(output, type) { var filePath = 'pdf_' + type + '.html'; var outputRoot = output.getRoot(); var engine = WebsiteGenerator.createTemplateEngine(output, filePath); // Generate context var context = JSONUtils.encodeOutput(output); context.page = { num: '_PAGENUM_', title: '_TITLE_', section: '_SECTION_' }; // Render the theme return Templating.renderFile(engine, 'ebook/' + filePath, context) // Inline css and assets .then(function(tplOut) { return Promise.nfcall(juice.juiceResources, tplOut.getContent(), { webResources: { relativeTo: outputRoot } }); }); } module.exports = getPDFTemplate;
compdb: Replace re by os.path utils Instead of using regular expressions to drop file name ending use os.path.splitext().
import vim import re import json from os import path curr_file = vim.eval("expand('%:p')") curr_file_noext = path.splitext(curr_file)[0] ccd = vim.eval("l:ccd") opts = [] with open(ccd) as database: # Search for the right entry in the database matching file names for d in json.load(database): # This is an entry without a file attribute if 'file' not in d: continue # This entry is about a different file. We consider file names # without extension to handle header files which do not have # an entry in the database. d_file_noext = path.splitext(d['file'])[0] if d_file_noext != curr_file_noext: continue for result in re.finditer(r'-D\s*[^\s]+', d['command']): opts.append(result.group(0)) for result in re.finditer(r'-isystem\s*[^\s]+', d['command']): opts.append(result.group(0)) for result in re.finditer(r'-I\s*([^\s]+)', d['command']): opts.append('-I' + path.join(d['directory'], result.group(1))) break vim.command("let l:clang_options = '" + ' '.join(opts) + "'")
import vim import re import json from os import path current = vim.eval("expand('%:p')") ccd = vim.eval("l:ccd") opts = [] with open(ccd) as database: data = json.load(database) for d in data: # hax for headers fmatch = re.search(r'(.*)\.(\w+)$', current) dmatch = re.search(r'(.*)\.(\w+)$', d['file']) if fmatch.group(1) == dmatch.group(1): for result in re.finditer(r'-D\s*[^\s]+', d['command']): opts.append(result.group(0)) for result in re.finditer(r'-isystem\s*[^\s]+', d['command']): opts.append(result.group(0)) for result in re.finditer(r'-I\s*([^\s]+)', d['command']): opts.append('-I' + path.join(d['directory'], result.group(1))) break vim.command("let l:clang_options = '" + ' '.join(opts) + "'")
Enable service-interface and vf-binding extensions by default in contrail based provisioning. Change-Id: I5916f41cdf12ad54e74c0f76de244ed60f57aea5 Partial-Bug: 1556336
import string template = string.Template(""" [APISERVER] api_server_ip = $__contrail_api_server_ip__ api_server_port = $__contrail_api_server_port__ multi_tenancy = $__contrail_multi_tenancy__ #use_ssl = False #insecure = False #certfile=$__contrail_api_server_cert_file__ #keyfile=$__contrail_api_server_key_file__ #cafile=$__contrail_api_server_ca_file__ contrail_extensions = ipam:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_ipam.NeutronPluginContrailIpam,policy:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_policy.NeutronPluginContrailPolicy,route-table:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_vpc.NeutronPluginContrailVpc,contrail:None,service-interface:None,vf-binding:None [COLLECTOR] analytics_api_ip = $__contrail_analytics_server_ip__ analytics_api_port = $__contrail_analytics_server_port__ [KEYSTONE] auth_url = $__contrail_ks_auth_protocol__://$__contrail_keystone_ip__:$__contrail_ks_auth_port__/v2.0 admin_user=$__contrail_admin_user__ admin_password=$__contrail_admin_password__ admin_tenant_name=$__contrail_admin_tenant_name__ """)
import string template = string.Template(""" [APISERVER] api_server_ip = $__contrail_api_server_ip__ api_server_port = $__contrail_api_server_port__ multi_tenancy = $__contrail_multi_tenancy__ #use_ssl = False #insecure = False #certfile=$__contrail_api_server_cert_file__ #keyfile=$__contrail_api_server_key_file__ #cafile=$__contrail_api_server_ca_file__ contrail_extensions = ipam:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_ipam.NeutronPluginContrailIpam,policy:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_policy.NeutronPluginContrailPolicy,route-table:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_vpc.NeutronPluginContrailVpc,contrail:None [COLLECTOR] analytics_api_ip = $__contrail_analytics_server_ip__ analytics_api_port = $__contrail_analytics_server_port__ [KEYSTONE] auth_url = $__contrail_ks_auth_protocol__://$__contrail_keystone_ip__:$__contrail_ks_auth_port__/v2.0 admin_user=$__contrail_admin_user__ admin_password=$__contrail_admin_password__ admin_tenant_name=$__contrail_admin_tenant_name__ """)
Remove print method. No longer needed. git-svn-id: 169764d5f12c41a1cff66b81d896619f3ce5473d@126 5e0a886f-7f45-49c5-bc19-40643649e37f
package kawa.standard; import kawa.lang.*; /** * The Syntax transformer that re-writes the "define" Scheme primitive. * Currently, only handles top-level definitions. * @author Per Bothner */ public class define extends Syntax implements Printable { public Expression rewrite (Object obj, Interpreter interp) throws kawa.lang.WrongArguments { if (obj instanceof Pair) { Pair p1 = (Pair) obj; if (p1.car instanceof Symbol && p1.cdr instanceof Pair) { Pair p2 = (Pair) p1.cdr; if (p2.cdr == List.Empty) { SetExp result = new SetExp ((Symbol)p1.car, interp.rewrite (p2.car)); result.setDefining (true); return result; } } else if (p1.car instanceof Pair) { Pair p2 = (Pair) p1.car; if (p2.car instanceof Symbol) { Symbol name = (Symbol) p2.car; LambdaExp lexp = new LambdaExp (p2.cdr, p1.cdr, interp); lexp.setName (name.toString ()); SetExp result = new SetExp (name, lexp); result.setDefining (true); return result; } } } return interp.syntaxError ("invalid syntax for define"); } }
package kawa.standard; import kawa.lang.*; /** * The Syntax transformer that re-writes the "define" Scheme primitive. * Currently, only handles top-level definitions. * @author Per Bothner */ public class define extends Syntax implements Printable { public Expression rewrite (Object obj, Interpreter interp) throws kawa.lang.WrongArguments { if (obj instanceof Pair) { Pair p1 = (Pair) obj; if (p1.car instanceof Symbol && p1.cdr instanceof Pair) { Pair p2 = (Pair) p1.cdr; if (p2.cdr == List.Empty) { SetExp result = new SetExp ((Symbol)p1.car, interp.rewrite (p2.car)); result.setDefining (true); return result; } } else if (p1.car instanceof Pair) { Pair p2 = (Pair) p1.car; if (p2.car instanceof Symbol) { Symbol name = (Symbol) p2.car; LambdaExp lexp = new LambdaExp (p2.cdr, p1.cdr, interp); lexp.setName (name.toString ()); SetExp result = new SetExp (name, lexp); result.setDefining (true); return result; } } } return interp.syntaxError ("invalid syntax for define"); } public void print(java.io.PrintStream ps) { ps.print("#<builtin define>"); } }
Add -T option to list available targets
from .config import parse from .target import Target from .__version__ import __version__ from argparse import ArgumentParser import logging import os import sys def main(): setup_logging() parser = ArgumentParser(prog='construi', description='Run construi') parser.add_argument('target', metavar='TARGET', nargs='?') parser.add_argument('--basedir', metavar='DIR', default=os.getcwd()) parser.add_argument('--version', action='version', version=__version__) parser.add_argument('-T', '--list-targets', action='store_true') args = parser.parse_args() config = load_config(args) if args.list_targets: list_targets(config) target = args.target or config.default Target(config.for_target(target)).run() def load_config(args): return parse(args.basedir, 'construi.yml') def setup_logging(): root_logger = logging.getLogger() root_logger.addHandler(logging.StreamHandler(sys.stdout)) root_logger.setLevel(logging.INFO) logging.getLogger("requests").propagate = False def list_targets(config): targets = config.targets.keys() targets.sort() for target in targets: print(target) sys.exit(0)
from .config import parse from .target import Target from .__version__ import __version__ from argparse import ArgumentParser import logging import os import sys def main(): setup_logging() parser = ArgumentParser(prog='construi', description='Run construi') parser.add_argument('target', metavar='TARGET', nargs='?') parser.add_argument('--basedir', metavar='DIR', default=os.getcwd()) parser.add_argument('--version', action='version', version=__version__) args = parser.parse_args() config = parse(args.basedir, 'construi.yml') target = args.target or config.default Target(config.for_target(target)).run() def setup_logging(): root_logger = logging.getLogger() root_logger.addHandler(logging.StreamHandler(sys.stdout)) root_logger.setLevel(logging.INFO) logging.getLogger("requests").propagate = False
Use composed annotation for readability
package ee.tuleva.onboarding.auth.session; import java.io.Serial; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.Optional; import org.springframework.stereotype.Component; import org.springframework.web.context.annotation.SessionScope; @Component @SessionScope public class GenericSessionStore implements Serializable { @Serial private static final long serialVersionUID = -648103071415508424L; private final Map<String, Object> sessionAttributes = new HashMap<>(); public <T extends Serializable> void save(T sessionAttribute) { sessionAttributes.put(sessionAttribute.getClass().getName(), sessionAttribute); } public <T extends Serializable> Optional<T> get(Class clazz) { @SuppressWarnings("unchecked") T sessionAttribute = (T) sessionAttributes.get(clazz.getName()); if (sessionAttribute == null) { return Optional.empty(); } return Optional.of(sessionAttribute); } }
package ee.tuleva.onboarding.auth.session; import java.io.Serial; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.Optional; import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.ScopedProxyMode; import org.springframework.stereotype.Component; @Component @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) public class GenericSessionStore implements Serializable { @Serial private static final long serialVersionUID = -648103071415508424L; private final Map<String, Object> sessionAttributes = new HashMap<>(); public <T extends Serializable> void save(T sessionAttribute) { sessionAttributes.put(sessionAttribute.getClass().getName(), sessionAttribute); } public <T extends Serializable> Optional<T> get(Class clazz) { @SuppressWarnings("unchecked") T sessionAttribute = (T) sessionAttributes.get(clazz.getName()); if (sessionAttribute == null) { return Optional.empty(); } return Optional.of(sessionAttribute); } }
Update test to run on new code
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Run from Cryptchat # python3 -m unittest discover import unittest from ..network.networkhandler import NetworkHandler from ..crypto.diffiehellman import DiffieHellman class testNetworkHandler(unittest.TestCase): @classmethod def setUpClass(cls): alice = DiffieHellman() bob = DiffieHellman() a = alice.gensessionkey(bob.publickey) b = bob.gensessionkey(alice.publickey) cls.server = NetworkHandler("localhost", 8090, True, alice) cls.client = NetworkHandler("localhost", 8090, False, bob) cls.server.start() cls.client.start() while not cls.server.exchangedkeys: # Now this is some good code. It works though.... pass def test_sendmessage(self): m = "This is secret please do not read. And some chars to get unicode-testing out of the way åäö" self.client.send(m) m2 = self.server.receive() self.assertEqual(m, m2) def main(): unittest.main() if __name__ == '__main__': main()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Run from Cryptchat # python3 -m unittest discover import unittest from ..network.networkhandler import NetworkHandler from ..crypto.aes import AESCipher from ..crypto.diffiehellman import DiffieHellman class testNetworkHandler(unittest.TestCase): @classmethod def setUpClass(self): alice = DiffieHellman() bob = DiffieHellman() a = alice.gensessionkey(bob.publickey) b = bob.gensessionkey(alice.publickey) aes1 = AESCipher(a) aes2 = AESCipher(b) self.server = NetworkHandler("localhost", 8090, True, alice, aes1) self.client = NetworkHandler("localhost", 8090, False, bob, aes2) def test_sendmessage(self): self.server.start() self.client.start() m = "This is secret please do not read. And some chars to get unicode-testing out of the way åäö" self.client.send(m) m2 = self.server.getinmessage() self.assertEqual(m, m2) def main(): unittest.main() if __name__ == '__main__': main()
Move to sendMessage command for message sending. Also add 'notice' trigger, because why not
from CommandTemplate import CommandTemplate class Command(CommandTemplate): triggers = ['say', 'do', 'notice'] helptext = "Makes the bot say the provided text in the provided channel (format 'say [channel/user] text')" adminOnly = True showInCommandList = False def execute(self, bot, user, target, triggerInMsg, msg, msgWithoutFirstWord, msgParts, msgPartsLength): if msgPartsLength < 3: bot.say(target, "Please provide both a channel or user name to say something to, and the text to say") #Check if we're in the channel we have to say something to elif msgParts[1].startswith('#') and msgParts[1] not in bot.channelsUserList: bot.say(target, "I'm not in that channel, so I can't say anything in there, sorry.") #Nothing's stopping us now! Say it! else: messageToSay = " ".join(msgParts[2:]) messageType = 'say' if triggerInMsg == 'do': messageType = 'action' elif triggerInMsg == 'notice': messageType = 'notice' bot.sendMessage(msgParts[1], messageToSay, messageType)
from CommandTemplate import CommandTemplate class Command(CommandTemplate): triggers = ['say', 'do'] helptext = "Makes the bot say the provided text in the provided channel (format 'say [channel/user] text')" adminOnly = True showInCommandList = False def execute(self, bot, user, target, triggerInMsg, msg, msgWithoutFirstWord, msgParts, msgPartsLength): if msgPartsLength < 3: bot.say(target, "Please provide both a channel or user name to say something to, and the text to say") #Check if we're in the channel we have to say something to elif msgParts[1].startswith('#') and msgParts[1] not in bot.channelsUserList: bot.say(target, "I'm not in that channel, so I can't say anything in there, sorry.") #Nothing's stopping us now! Say it! else: messageToSay = " ".join(msgParts[2:]) if triggerInMsg == 'say': bot.say(msgParts[1], messageToSay) elif triggerInMsg == 'do': bot.doAction(msgParts[1], messageToSay)
Unify errors and failures in API
from sentinels import NOTHING class ErrorContainer(object): def add_error(self, message, exception_type=NOTHING, traceback=NOTHING, timestamp=NOTHING): return self.client.api.call_function('add_error', {self._get_id_key(): self.id, 'message': message, 'exception_type': exception_type, 'traceback': traceback, 'timestamp': timestamp }) def _get_id_key(self): if type(self).__name__ == 'Test': return 'test_id' return 'session_id'
from sentinels import NOTHING class ErrorContainer(object): def add_error(self, exception, exception_type, traceback, timestamp=NOTHING): return self.client.api.call_function('add_error', {self._get_id_key(): self.id, 'exception': exception, 'exception_type': exception_type, 'traceback': traceback, 'timestamp': timestamp }) def _get_id_key(self): if type(self).__name__ == 'Test': return 'test_id' return 'session_id'
Comment out custom de-/serializeUser code for now
'use strict'; // const p = require('path'); const _ = require('lodash'); const passport = require('passport'); // const User = require('../services/users/model'); // const config = require(p.join(process.cwd(), 'server/config/membership')); let serializeUser; let deserializeUser; // if (typeof config.serializeUser === 'function') { // if (config.serializeUser.length === 1) { // serializeUser = config.serializeUser(User); // } else { // serializeUser = config.serializeUser; // } // } // if (typeof config.deserializeUser === 'function') { // if (config.deserializeUser.length === 1) { // deserializeUser = config.deserializeUser(User); // } else { // deserializeUser = config.deserializeUser; // } // } // used to serialize the user for the session passport.serializeUser(serializeUser || ((user, done) => { done(null, _.pick(user, ['id', 'username', 'email', 'roles'])); })); // used to deserialize the user passport.deserializeUser(deserializeUser || ((user, done) => { done(null, user); // User.findById(user, (err, user) => { // done(err, user); // }); })); require('./req'); require('./strategies');
'use strict'; const p = require('path'); const _ = require('lodash'); const passport = require('passport'); // const User = require('../services/users/model'); const config = require(p.join(process.cwd(), 'server/config/membership')); let serializeUser; let deserializeUser; if (typeof config.serializeUser === 'function') { if (config.serializeUser.length === 1) { serializeUser = config.serializeUser(User); } else { serializeUser = config.serializeUser; } } if (typeof config.deserializeUser === 'function') { if (config.deserializeUser.length === 1) { deserializeUser = config.deserializeUser(User); } else { deserializeUser = config.deserializeUser; } } // used to serialize the user for the session passport.serializeUser(serializeUser || ((user, done) => { done(null, _.pick(user, ['id', 'username', 'email', 'roles'])); })); // used to deserialize the user passport.deserializeUser(deserializeUser || ((user, done) => { done(null, user); // User.findById(user, (err, user) => { // done(err, user); // }); })); require('./req'); require('./strategies');
Add TextView text, SpeechView text and SpeechView seconds elapsed fields to user schema
/* eslint new-cap: 0 */ const mongoose = require('mongoose'); const bcrypt = require('bcrypt-nodejs'); const Q = require('q'); const SALT_WORK_FACTOR = 10; const UserSchema = new mongoose.Schema({ username: { type: String, required: true, unique: true, }, password: { type: String, required: true, }, salt: String, textViewText: String, speechViewText: String, speechViewSecondsElapsed: Number, }); UserSchema.methods.comparePasswords = function (candidatePassword) { const savedPassword = this.password; return Q.Promise((resolve, reject) => { bcrypt.compare(candidatePassword, savedPassword, (err, matched) => { if (err) { reject(err); } else { resolve(matched); } }); }); }; UserSchema.pre('save', function presaveCallback(next) { const user = this; return bcrypt.genSalt(SALT_WORK_FACTOR, (err, salt) => { if (err) { return next(err); } return bcrypt.hash(user.password, salt, null, (err2, hash) => { if (err2) { return next(err2); } user.password = hash; user.salt = salt; return next(); }); }); }); module.exports = mongoose.model('User', UserSchema);
/* eslint new-cap: 0 */ const mongoose = require('mongoose'); const bcrypt = require('bcrypt-nodejs'); const Q = require('q'); const SALT_WORK_FACTOR = 10; const UserSchema = new mongoose.Schema({ username: { type: String, required: true, unique: true, }, password: { type: String, required: true, }, salt: String, }); UserSchema.methods.comparePasswords = function (candidatePassword) { const savedPassword = this.password; return Q.Promise((resolve, reject) => { bcrypt.compare(candidatePassword, savedPassword, (err, matched) => { if (err) { reject(err); } else { resolve(matched); } }); }); }; UserSchema.pre('save', function presaveCallback(next) { const user = this; return bcrypt.genSalt(SALT_WORK_FACTOR, (err, salt) => { if (err) { return next(err); } return bcrypt.hash(user.password, salt, null, (err2, hash) => { if (err2) { return next(err2); } user.password = hash; user.salt = salt; return next(); }); }); }); module.exports = mongoose.model('User', UserSchema);
Deploy to Kovan test network.
module.exports = { migrations_directory: "./migrations", networks: { development: { host: "localhost", port: 8545, network_id: "*" }, live: { host: "localhost", port: 8546, network_id: 1, }, Ropsten: { host: "localhost", port: 8547, network_id: 3, gasprice: 23000000000, // 23 gwei }, Kovan: { host: "localhost", port: 8548, network_id: 42, gasprice: 23000000000, // 23 gwei }, Rinkeby: { host: "localhost", port: 8549, network_id: 4, } } }
module.exports = { migrations_directory: "./migrations", networks: { development: { host: "localhost", port: 8545, network_id: "*" }, live: { host: "localhost", port: 8546, network_id: 1, }, Ropsten: { host: "localhost", port: 8547, network_id: 3, gasprice: 23000000000, // 23 gwei }, Rinkeby: { host: "localhost", port: 8548, network_id: 4, } } }
Change focus on select example component name
import React, { Component } from 'react' import Slider from '../src/slider' export default class FocusOnSelect extends Component { render() { const settings = { focusOnSelect: true, infinite: true, slidesToShow: 3, slidesToScroll: 1, speed: 500 }; return ( <div> <h2>FocusOnSelect</h2> <div>Click on any slide to select and make it current slide</div> <Slider {...settings}> <div><h3>1</h3></div> <div><h3>2</h3></div> <div><h3>3</h3></div> <div><h3>4</h3></div> <div><h3>5</h3></div> <div><h3>6</h3></div> </Slider> </div> ); } }
import React, { Component } from 'react' import Slider from '../src/slider' export default class CenterModeWithFocusOnSelect extends Component { render() { const settings = { focusOnSelect: true, infinite: true, slidesToShow: 3, slidesToScroll: 1, speed: 500 }; return ( <div> <h2>FocusOnSelect</h2> <div>Click on any slide to select and make it current slide</div> <Slider {...settings}> <div><h3>1</h3></div> <div><h3>2</h3></div> <div><h3>3</h3></div> <div><h3>4</h3></div> <div><h3>5</h3></div> <div><h3>6</h3></div> </Slider> </div> ); } }
Add leaflet extensions to build script.
var deps = { LeafletExtensions: { src: [ 'ext/LineUtil.js', 'ext/Polyline.js', 'ext/Polygon.js' ], desc: 'Extensions to Leaflet to add intersection detection.' }, DrawHandler: { src: ['draw/Handler.Draw.js'], desc: 'The base class for drawing.', deps: ['LeafletExtensions'] }, Polys: { src: [ 'draw/shapes/Polyline.Draw.js', 'draw/shapes/Polygon.Draw.js' ], desc: 'Polyline and Polygon drawing handlers.', deps: ['DrawHandler'] }, SimpleShapes: { src: [ 'draw/shapes/SimpleShape.Draw.js', 'draw/shapes/Circle.Draw.js', 'draw/shapes/Rectangle.Draw.js' ], desc: 'Simple Shape drawing handlers.', deps: ['DrawHandler'] }, Markers: { src: ['draw/shapes/Marker.Draw.js'], desc: 'Marker drawing handlers.', deps: ['DrawHandler'] }, DrawingControl: { src: ['draw/Control.Draw.js'], desc: 'Drawing control.', deps: [ 'Polys', 'SimpleShapes', 'Markers' ] } }; if (typeof exports !== 'undefined') { exports.deps = deps; }
var deps = { DrawHandler: { src: ['Handler.Draw.js'], desc: 'The base class for drawing.', }, Polys: { src: ['Polyline.Draw.js', 'Polygon.Draw.js'], desc: 'Polyline and Polygon drawing handlers.', deps: ['DrawHandler'] }, SimpleShapes: { src: ['SimpleShape.Draw.js', 'Circle.Draw.js', 'Rectangle.Draw.js'], desc: 'Simple Shape drawing handlers.', deps: ['DrawHandler'] }, Markers: { src: ['Marker.Draw.js'], desc: 'Marker drawing handlers.', deps: ['DrawHandler'] }, DrawingControl: { src: ['Control.Draw.js'], desc: 'Drawing control.', deps: ['Polys', 'SimpleShapes', 'Markers'] } }; if (typeof exports !== 'undefined') { exports.deps = deps; }
Fix pyflakes complaining of imported but unused module.
# Copyright 2014-2015 Open Source Robotics Foundation, 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. import logging import traceback from .import_type_support_impl import import_type_support __all__ = ['import_type_support'] try: from .generate_py_impl import generate_py assert generate_py __all__.append('generate_py') except ImportError: logger = logging.getLogger('rosidl_generator_py') logger.debug( 'Failed to import modules for generating Python structures:\n' + traceback.format_exc())
# Copyright 2014-2015 Open Source Robotics Foundation, 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. import logging import traceback from .import_type_support_impl import import_type_support __all__ = ['import_type_support'] try: from .generate_py_impl import generate_py __all__.append('generate_py') except ImportError: logger = logging.getLogger('rosidl_generator_py') logger.debug( 'Failed to import modules for generating Python structures:\n' + traceback.format_exc())
FIX : Header et Footer non déclaré
/** * * App * * This component is the skeleton around the actual pages, and should only * contain code that should be seen on all pages. (e.g. navigation bar) */ import React from 'react'; import Helmet from 'react-helmet'; import styled from 'styled-components'; import Header from 'components/Header'; import Footer from 'components/Footer'; import FooterBaseBoilerPlate from 'components/FooterBaseBoilerPlate'; import withProgressBar from 'components/ProgressBar'; const AppWrapper = styled.div` max-width: calc(768px + 16px * 2); margin: 0 auto; display: flex; min-height: 100%; padding: 0 16px; flex-direction: column; `; export function App(props) { return ( <AppWrapper> <Helmet titleTemplate="%s - React.js Boilerplate" defaultTitle="React.js Boilerplate" meta={[ { name: 'description', content: 'A React.js Boilerplate application' }, ]} /> <Header /> {React.Children.toArray(props.children)} <Footer /> </AppWrapper> ); } App.propTypes = { children: React.PropTypes.node, }; export default withProgressBar(App);
/** * * App * * This component is the skeleton around the actual pages, and should only * contain code that should be seen on all pages. (e.g. navigation bar) */ import React from 'react'; import Helmet from 'react-helmet'; import styled from 'styled-components'; import HeaderBaseBoilerPlate from 'components/HeaderBaseBoilerPlate'; import FooterBaseBoilerPlate from 'components/FooterBaseBoilerPlate'; import withProgressBar from 'components/ProgressBar'; const AppWrapper = styled.div` max-width: calc(768px + 16px * 2); margin: 0 auto; display: flex; min-height: 100%; padding: 0 16px; flex-direction: column; `; export function App(props) { return ( <AppWrapper> <Helmet titleTemplate="%s - React.js Boilerplate" defaultTitle="React.js Boilerplate" meta={[ { name: 'description', content: 'A React.js Boilerplate application' }, ]} /> <HeaderBaseBoilerPlate /> {React.Children.toArray(props.children)} <FooterBaseBoilerPlate /> </AppWrapper> ); } App.propTypes = { children: React.PropTypes.node, }; export default withProgressBar(App);
Add handlebars helper in order to show recipe image
(function () { RecipeListView.prototype.template = Handlebars.compile($("#recipe-list-tpl").html()); RecipeView.prototype.template = Handlebars.compile($("#recipe-tpl").html()); Handlebars.registerHelper('recipe_image', function(image_id) { return _.find(recipe_images, function(recipe){ return recipe.id == image_id; }).source_url; }); var service = new RecipeService(); service.initialize().done(function () { router.addRoute('', function() { service.printRecipes(); }); router.addRoute('recipes/:id', function(id) { service.findById(parseInt(id)).done(function(recipe) { $('#content').html(new RecipeView(recipe).render().$el); }); }); router.addRoute('about', function() { $('#content').load("about.html"); }); router.start(); }); }());
(function () { RecipeListView.prototype.template = Handlebars.compile($("#recipe-list-tpl").html()); RecipeView.prototype.template = Handlebars.compile($("#recipe-tpl").html()); var service = new RecipeService(); service.initialize().done(function () { router.addRoute('', function() { service.printRecipes(); }); router.addRoute('recipes/:id', function(id) { service.findById(parseInt(id)).done(function(recipe) { $('#content').html(new RecipeView(recipe).render().$el); }); }); router.addRoute('about', function() { $('#content').load("about.html"); }); router.start(); }); }());
Change order of API call
from flask import Blueprint, jsonify from .security import validate_request_authentication from qiime.sdk import PluginManager PLUGIN_MANAGER = PluginManager() v1 = Blueprint('v1', __name__) v1.before_request(validate_request_authentication) @v1.route('/', methods=['GET', 'POST']) def root(): return jsonify(content="!") @v1.route('/plugins', methods=['GET']) def api_plugins(): plugin_list = list(PLUGIN_MANAGER.plugins.keys()) return jsonify({"names": plugin_list}) @v1.route('/<plugin_name>/workflows', methods=['GET']) def api_workflows(plugin_name): plugin = PLUGIN_MANAGER.plugins[plugin_name] workflows_dict = {} for key, value in plugin.workflows.items(): workflows_dict[key] = {} workflows_dict[key]['info'] = "Produces: {}".format(list(value.signature.output_artifacts.values())) return jsonify({"workflows": workflows_dict})
from flask import Blueprint, jsonify from .security import validate_request_authentication from qiime.sdk import PluginManager PLUGIN_MANAGER = PluginManager() v1 = Blueprint('v1', __name__) v1.before_request(validate_request_authentication) @v1.route('/', methods=['GET', 'POST']) def root(): return jsonify(content="!") @v1.route('/plugins', methods=['GET']) def api_plugins(): plugin_list = list(PLUGIN_MANAGER.plugins.keys()) return jsonify({"names": plugin_list}) @v1.route('/workflows/<plugin_name>', methods=['GET']) def api_workflows(plugin_name): plugin = PLUGIN_MANAGER.plugins[plugin_name] workflows_dict = {} for key, value in plugin.workflows.items(): workflows_dict[key] = {} workflows_dict[key]['info'] = "Produces: {}".format(list(value.signature.output_artifacts.values())) return jsonify({"workflows": workflows_dict})
Fix image width and height switching
# Copyright 2018 The Lucid Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """High-level wrapper for paramaterizing images.""" import tensorflow as tf from lucid.optvis.param.color import to_valid_rgb from lucid.optvis.param.spatial import pixel_image, fft_image def image(w, h=None, batch=None, sd=None, decorrelate=True, fft=True, alpha=False): h = h or w batch = batch or 1 channels = 4 if alpha else 3 shape = [batch, h, w, channels] param_f = fft_image if fft else pixel_image t = param_f(shape, sd=sd) rgb = to_valid_rgb(t[..., :3], decorrelate=decorrelate, sigmoid=True) if alpha: a = tf.nn.sigmoid(t[..., 3:]) return tf.concat([rgb, a], -1) return rgb
# Copyright 2018 The Lucid Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """High-level wrapper for paramaterizing images.""" import tensorflow as tf from lucid.optvis.param.color import to_valid_rgb from lucid.optvis.param.spatial import pixel_image, fft_image def image(w, h=None, batch=None, sd=None, decorrelate=True, fft=True, alpha=False): h = h or w batch = batch or 1 channels = 4 if alpha else 3 shape = [batch, w, h, channels] param_f = fft_image if fft else pixel_image t = param_f(shape, sd=sd) rgb = to_valid_rgb(t[..., :3], decorrelate=decorrelate, sigmoid=True) if alpha: a = tf.nn.sigmoid(t[..., 3:]) return tf.concat([rgb, a], -1) return rgb
Fix passing json unmarshal non-pointer values
package ambition import ( "encoding/json" ) func PostOccurrenceByActionIdJson(ActionId int, occurrenceJson []byte) error { var occurrence Occurrence err := json.Unmarshal(occurrenceJson, &occurrence) occurrence.ActionId = ActionId database.InsertOccurrence(&occurrence) return err } func PostActionBySetIdJson(SetId int, actionJson []byte) error { var action Action err := json.Unmarshal(actionJson, &action) action.SetId = SetId database.InsertAction(&action) return err } func PostArrayOfSetsJson(setJson []byte) error { var sets []Set json.Unmarshal(setJson, &sets) var err error for _, set := range sets { err = database.InsertSet(&set) } return err } func PostArrayOfActionsJson(actionJson []byte) error { var actions []Action json.Unmarshal(actionJson, &actions) var err error for _, action := range actions { err = database.InsertAction(&action) } return err } func PostArrayOfOccurrencesJson(occurrenceJson []byte) error { var occurrences []Occurrence json.Unmarshal(occurrenceJson, &occurrences) var err error for _, occurrence := range occurrences { err = database.InsertOccurrence(&occurrence) } return err }
package ambition import ( "encoding/json" ) func PostOccurrenceByActionIdJson(ActionId int, occurrenceJson []byte) error { var occurrence Occurrence err := json.Unmarshal(occurrenceJson, occurrence) occurrence.ActionId = ActionId database.InsertOccurrence(&occurrence) return err } func PostActionBySetIdJson(SetId int, actionJson []byte) error { var action Action err := json.Unmarshal(actionJson, action) action.SetId = SetId database.InsertAction(&action) return err } func PostArrayOfSetsJson(setJson []byte) error { var sets []Set json.Unmarshal(setJson, &sets) var err error for _, set := range sets { err = database.InsertSet(&set) } return err } func PostArrayOfActionsJson(actionJson []byte) error { var actions []Action json.Unmarshal(actionJson, &actions) var err error for _, action := range actions { err = database.InsertAction(&action) } return err } func PostArrayOfOccurrencesJson(occurrenceJson []byte) error { var occurrences []Occurrence json.Unmarshal(occurrenceJson, &occurrences) var err error for _, occurrence := range occurrences { err = database.InsertOccurrence(&occurrence) } return err }
Add link to edit test date information to Pending page Fixes #177
<h2><span class="label label-default">Pending surveys</span></h2> <table class="table table-striped table-hover"> <thead> <tr> <th>Survey ID</th><th>Description</th><th>Date Scheduled</th><th>Accession</th><th>Survey Note</th><th></th> </tr> </thead> <tbody> @foreach ($pendingSurveys as $pending) <tr> <td><a href="{{ route('surveys.edit', $pending->surveyId)}}">{{ $pending->surveyId }}</a></td> <td><a href="{{ route('machines.show', $pending->machineId) }}">{{ $pending->description }}</a></td> <td>{{ $pending->test_date}}</td> <td>{{ $pending->accession }}</td> <td>{{ $pending->notes }}</td> <td><a href="{{ route('surveys.edit', $pending->surveyId) }}" class="btn btn-default btn-xs" role="button" data-toggle="tooltip" title="Modify this machine"> <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span></a> </td> </tr> @endforeach </tbody> </table>
<h2><span class="label label-default">Pending surveys</span></h2> <table class="table table-striped table-hover"> <thead> <tr> <th>Survey ID</th><th>Description</th><th>Date Scheduled</th><th>Accession</th><th>Survey Note</th> </tr> </thead> <tbody> @foreach ($pendingSurveys as $pending) <tr> <td><a href="{{ route('surveys.edit', $pending->surveyId)}}">{{ $pending->surveyId }}</a></td> <td><a href="{{ route('machines.show', $pending->machineId) }}">{{ $pending->description }}</a></td> <td>{{ $pending->test_date}}</td> <td>{{ $pending->accession }}</td> <td>{{ $pending->notes }}</td> </tr> @endforeach </tbody> </table>
Fix issue in overview parser
'use strict'; const D3 = require('D3'); exports.parser = function(rows) { var overviewResponse = D3.values(rows[0]); var overview = D3.nest() .key(function(d) { return d.region_code; }) .rollup(function(v) { return { 'region_code': v[0], 'region_name': v[1], 'current_total': v[2], 'delayed_total': v[3], 'days_to_payment': v[4] } }) .entries(overviewResponse) .map(function(d) { return d.value; }); var data = { 'overview': overview }; return data; };
'use strict'; const D3 = require('D3'); exports.parser = function(rows) { var overviewResponse = D3.values(rows[0]); var overview = D3.nest() .key(function(d) { return d.region_code; }) .rollup(function(v) { return { 'region_code': v[0].region_code, 'region_name': v[0].region_name, 'current_total': v[0].current_total, 'delayed_total': v[0].delayed_total, 'days_to_payment': v[0].days_to_payment } }) .entries(overviewResponse) .map(function(d) { return d.values; }); var data = { 'overview': overview }; return data; };
[PAXJDBC-124] Fix missing itest dependency for aries-pool
package org.ops4j.pax.jdbc.test.pool; import javax.inject.Inject; import org.junit.Test; import org.ops4j.pax.exam.Configuration; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.util.Filter; import org.ops4j.pax.jdbc.pool.common.PooledDataSourceFactory; import org.ops4j.pax.jdbc.test.AbstractJdbcTest; public class PoolAriesTest extends AbstractJdbcTest { @Inject @Filter("(pool=aries)(xa=false)") PooledDataSourceFactory pool; @Configuration public Option[] config() { return new Option[] { // regressionDefaults(), // poolDefaults(), // mvnBundle("commons-logging", "commons-logging"), mvnBundle("org.apache.geronimo.components", "geronimo-connector"), mvnBundle("org.apache.geronimo.specs", "geronimo-j2ee-connector_1.6_spec"), mvnBundle("org.ops4j.pax.jdbc", "pax-jdbc-pool-aries"), }; } @Test public void testPooledDataSourceFactoryServicesPresent() { } }
package org.ops4j.pax.jdbc.test.pool; import javax.inject.Inject; import org.junit.Test; import org.ops4j.pax.exam.Configuration; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.util.Filter; import org.ops4j.pax.jdbc.pool.common.PooledDataSourceFactory; import org.ops4j.pax.jdbc.test.AbstractJdbcTest; public class PoolAriesTest extends AbstractJdbcTest { @Inject @Filter("(pool=aries)(xa=false)") PooledDataSourceFactory pool; @Configuration public Option[] config() { return new Option[] { // regressionDefaults(), // poolDefaults(), // mvnBundle("org.apache.geronimo.components", "geronimo-connector"), mvnBundle("org.apache.geronimo.specs", "geronimo-j2ee-connector_1.6_spec"), mvnBundle("org.ops4j.pax.jdbc", "pax-jdbc-pool-aries"), }; } @Test public void testPooledDataSourceFactoryServicesPresent() { } }
Replace non-word charactor into space
<?php namespace CodeGen\Frameworks\PHPUnit; use CodeGen\UserClass; use Doctrine\Common\Inflector\Inflector; use CodeGen\ClassMethod; class PHPUnitFrameworkTestCase extends UserClass { public function __construct($title) { $class = Inflector::classify(preg_replace('/\W+/',' ',$title)); parent::__construct($class); $this->extendClass('PHPUnit_Framework_TestCase', true); } public function addTest($testName) { $methodName = 'test' . Inflector::classify($testName); $testMethod = new ClassMethod($methodName, [], []); $testMethod->setScope('public'); $this->methods[] = $testMethod; return $testMethod; } }
<?php namespace CodeGen\Frameworks\PHPUnit; use CodeGen\UserClass; use Doctrine\Common\Inflector\Inflector; use CodeGen\ClassMethod; class PHPUnitFrameworkTestCase extends UserClass { public function __construct($title) { $class = Inflector::classify($title); parent::__construct($class); $this->extendClass('PHPUnit_Framework_TestCase', true); } public function addTest($testName) { $methodName = 'test' . Inflector::classify($testName); $testMethod = new ClassMethod($methodName, [], []); $testMethod->setScope('public'); $this->methods[] = $testMethod; return $testMethod; } }
Allow certificites to be conditional
'use strict'; var memoize = require('memoizee/plain') , validDb = require('dbjs/valid-dbjs') , defineStringLine = require('dbjs-ext/string/string-line'); module.exports = memoize(function (db) { var StringLine; validDb(db); StringLine = defineStringLine(db); db.Object.extend('Registration', { certificates: { type: StringLine, multiple: true, value: function () { return [this.key]; } }, requirements: { type: StringLine, multiple: true }, costs: { type: StringLine, multiple: true }, isMandatory: { type: db.Boolean, value: true }, isApplicable: { type: db.Boolean, value: true }, isRequested: { type: db.Boolean, value: true } }, { label: { type: StringLine }, abbr: { type: StringLine } }); return db.Registration; }, { normalizer: require('memoizee/normalizers/get-1')() });
'use strict'; var memoize = require('memoizee/plain') , validDb = require('dbjs/valid-dbjs') , defineStringLine = require('dbjs-ext/string/string-line') , defineDocument = require('./document'); module.exports = memoize(function (db) { var StringLine, Document; validDb(db); StringLine = defineStringLine(db); Document = defineDocument(db); db.Object.extend('Registration', { requirements: { type: StringLine, multiple: true }, costs: { type: StringLine, multiple: true }, isMandatory: { type: db.Boolean, value: true }, isApplicable: { type: db.Boolean, value: true }, isRequested: { type: db.Boolean, value: true } }, { label: { type: StringLine }, abbr: { type: StringLine }, certificates: { type: Document, multiple: true } }); return db.Registration; }, { normalizer: require('memoizee/normalizers/get-1')() });
Change code to make Sonar happy See #5489
package <%=packageName%>.web.rest.errors; import java.util.HashMap; import java.util.Map; /** * Custom, parameterized exception, which can be translated on the client side. * For example: * * <pre> * throw new CustomParameterizedException(&quot;myCustomError&quot;, &quot;hello&quot;, &quot;world&quot;); * </pre> * * Can be translated with: * * <pre> * "error.myCustomError" : "The server says {{param0}} to {{param1}}" * </pre> */ public class CustomParameterizedException extends RuntimeException { private static final long serialVersionUID = 1L; private static final String PARAM = "param"; private final String message; private final Map<String, String> paramMap = new HashMap<>(); public CustomParameterizedException(String message, String... params) { super(message); this.message = message; if (params != null && params.length > 0) { for (int i = 0; i < params.length; i++) { paramMap.put(PARAM + i, params[i]); } } } public CustomParameterizedException(String message, Map<String, String> paramMap) { super(message); this.message = message; this.paramMap.putAll(paramMap); } public ParameterizedErrorVM getErrorVM() { return new ParameterizedErrorVM(message, paramMap); } }
package <%=packageName%>.web.rest.errors; import java.util.HashMap; import java.util.Map; /** * Custom, parameterized exception, which can be translated on the client side. * For example: * * <pre> * throw new CustomParameterizedException(&quot;myCustomError&quot;, &quot;hello&quot;, &quot;world&quot;); * </pre> * * Can be translated with: * * <pre> * "error.myCustomError" : "The server says {{param0}} to {{param1}}" * </pre> */ public class CustomParameterizedException extends RuntimeException { private static final long serialVersionUID = 1L; private static final String PARAM = "param"; private final String message; private Map<String, String> paramMap; public CustomParameterizedException(String message, String... params) { super(message); this.message = message; if (params != null && params.length > 0) { this.paramMap = new HashMap<>(); for (int i = 0; i < params.length; i++) { paramMap.put(PARAM + i, params[i]); } } } public CustomParameterizedException(String message, Map<String, String> paramMap) { super(message); this.message = message; this.paramMap = paramMap; } public ParameterizedErrorVM getErrorVM() { return new ParameterizedErrorVM(message, paramMap); } }
Add a name for the recipe section
""" Copyright 2010 Jason Chu, Dusty Phillips, and Phil Schalm 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 django import forms from project.models import Project class ProjectForm(forms.ModelForm): class Meta: model = Project class DjangoRecipeForm(forms.Form): name = forms.CharField(initial="django") settings = forms.CharField() version = forms.ChoiceField(choices=[ ("trunk", "trunk"), ("1.2", "1.2"), ("1.1.2", "1.1.2"), ("1.1", "1.1"), ("1.0.4", "1.04"), ("0.96", "0.96"), ]) eggs = forms.CharField() project = forms.CharField() extra_paths = forms.CharField() fcgi = forms.BooleanField() wsgi = forms.BooleanField() recipe_form_map = { 'djangorecipe': DjangoRecipeForm }
""" Copyright 2010 Jason Chu, Dusty Phillips, and Phil Schalm 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 django import forms from project.models import Project class ProjectForm(forms.ModelForm): class Meta: model = Project class DjangoRecipeForm(forms.Form): settings = forms.CharField() version = forms.ChoiceField(choices=[ ("trunk", "trunk"), ("1.2", "1.2"), ("1.1.2", "1.1.2"), ("1.1", "1.1"), ("1.0.4", "1.04"), ("0.96", "0.96"), ]) eggs = forms.CharField() project = forms.CharField() extra_paths = forms.CharField() fcgi = forms.BooleanField() wsgi = forms.BooleanField() recipe_form_map = { 'djangorecipe': DjangoRecipeForm }
:new: Add a placeholder updateMeta method
'use babel' import {CompositeDisposable, Emitter} from 'atom' import {aggressiveDebounce} from './helpers' export default class Editor { constructor(textEditor, connection) { this.subscriptions = new CompositeDisposable() this.connection = connection this.emitter = new Emitter() this.subscriptions.add(this.emitter) this.subscriptions.add(atom.config.observe('steel-flint.liveReload', liveReload => { this.liveReload = liveReload })) this.subscriptions.add(textEditor.onDidDestroy(() => { this.dispose() })) let oldText = null this.subscriptions.add(textEditor.onDidChange(aggressiveDebounce(() => { const filePath = textEditor.getPath() const fileContents = textEditor.getText() if (this.liveReload && oldText !== fileContents) { oldText = fileContents connection.send('live:save', {path: filePath, contents: fileContents}) } }, 16))) this._updateMeta = aggressiveDebounce(this.updateMeta, 16) } updateMeta(meta) { console.log(meta) } getConnection() { return this.connection } onDidDestroy(callback) { return this.emitter.on('did-destroy', callback) } dispose() { this.emitter.emit('did-destroy') this.subscriptions.dispose() this.connection = null } }
'use babel' import {CompositeDisposable, Emitter} from 'atom' import {aggressiveDebounce} from './helpers' export default class Editor { constructor(textEditor, connection) { this.subscriptions = new CompositeDisposable() this.connection = connection this.emitter = new Emitter() this.subscriptions.add(this.emitter) this.subscriptions.add(atom.config.observe('steel-flint.liveReload', liveReload => { this.liveReload = liveReload })) this.subscriptions.add(textEditor.onDidDestroy(() => { this.dispose() })) let oldText = null this.subscriptions.add(textEditor.onDidChange(aggressiveDebounce(() => { const filePath = textEditor.getPath() const fileContents = textEditor.getText() if (this.liveReload && oldText !== fileContents) { oldText = fileContents connection.send('live:save', {path: filePath, contents: fileContents}) } }, 16))) } getConnection() { return this.connection } onDidDestroy(callback) { return this.emitter.on('did-destroy', callback) } dispose() { this.emitter.emit('did-destroy') this.subscriptions.dispose() this.connection = null } }
fix: Fix error when msg is undefined.
import Vue from 'vue' import Message from './Message.vue' import Modal from './Modal.vue' const MessageConstructor = Vue.extend(Message) const Msg = function (option) { let instance option = option || {} if (typeof option === 'string') { option = { message: option } } instance = new MessageConstructor({ data: option }) instance.vm = instance.$mount() document.body.appendChild(instance.vm.$el) instance.vm.visible = true } const success = msg => Msg(msg) const info = msg => { Msg({ type: 'info', message: msg }) } const warn = msg => { Msg({ type: 'warn', message: msg }) } const error = (msg = '', close) => { if (close === undefined) close = true Msg({ type: 'error', message: msg.msg || msg, showClose: close }) } const modal = function (option = {}) { let instance if (typeof option === 'string') { option = { content: option } } const Constructor = Vue.extend(Modal) instance = new Constructor({ data: option }) instance.vm = instance.$mount() document.body.appendChild(instance.vm.$el) instance.vm.visible = true } export { Msg, success, info, warn, error, modal }
import Vue from 'vue' import Message from './Message.vue' import Modal from './Modal.vue' const MessageConstructor = Vue.extend(Message) const Msg = function (option) { let instance option = option || {} if (typeof option === 'string') { option = { message: option } } instance = new MessageConstructor({ data: option }) instance.vm = instance.$mount() document.body.appendChild(instance.vm.$el) instance.vm.visible = true } const success = msg => Msg(msg) const info = msg => { Msg({ type: 'info', message: msg }) } const warn = msg => { Msg({ type: 'warn', message: msg }) } const error = (msg, close) => { if (close === undefined) close = true Msg({ type: 'error', message: msg.msg || msg, showClose: close }) } const modal = function (option = {}) { let instance if (typeof option === 'string') { option = { content: option } } const Constructor = Vue.extend(Modal) instance = new Constructor({ data: option }) instance.vm = instance.$mount() document.body.appendChild(instance.vm.$el) instance.vm.visible = true } export { Msg, success, info, warn, error, modal }
Return status code 200 when Device instance already exists
from django.db import IntegrityError from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .serializers import DeviceSerializer class DeviceTokenSetter(APIView): """ Set a push token related to device for logged in User """ permission_classes = (IsAuthenticated, ) def post(self, request, format=None): serializer = DeviceSerializer(data=request.data) if serializer.is_valid(raise_exception=True): try: serializer.save(user=request.user) return Response(status=status.HTTP_201_CREATED) except IntegrityError: return Response('Device instance already exists.', status=status.HTTP_200_OK)
from django.db import IntegrityError from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .serializers import DeviceSerializer class DeviceTokenSetter(APIView): """ Set a push token related to device for logged in User """ permission_classes = (IsAuthenticated, ) def post(self, request, format=None): serializer = DeviceSerializer(data=request.data) if serializer.is_valid(raise_exception=True): try: serializer.save(user=request.user) return Response(status=status.HTTP_201_CREATED) except IntegrityError: return Response('Device instance already exists.', status=status.HTTP_409_CONFLICT)
Disable testing equals on samples
package org.pdxfinder.graph.dao; import org.junit.Test; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.*; public class SampleTest { /* @Test public void equals_givenIdenticalObjects_symmetricallyEqual() { Sample x = new Sample("id"); Sample y = new Sample("id"); assertTrue(x.equals(y) && y.equals(x)); } @Test public void equals_givenIdenticalObjects_hashCodeIsEqual() { Sample x = new Sample("id"); Sample y = new Sample("id"); assertEquals(x.hashCode(), y.hashCode()); } @Test public void hashCode_givenObjectPutInMap_identicalKeyRetrievesTheValue() { Sample x = new Sample("id"); Sample y = new Sample("id"); Map<Sample, String> map = new HashMap<>(); map.put(x, "this"); assertEquals("this", map.get(y)); } */ }
package org.pdxfinder.graph.dao; import org.junit.Test; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.*; public class SampleTest { @Test public void equals_givenIdenticalObjects_symmetricallyEqual() { Sample x = new Sample("id"); Sample y = new Sample("id"); assertTrue(x.equals(y) && y.equals(x)); } @Test public void equals_givenIdenticalObjects_hashCodeIsEqual() { Sample x = new Sample("id"); Sample y = new Sample("id"); assertEquals(x.hashCode(), y.hashCode()); } @Test public void hashCode_givenObjectPutInMap_identicalKeyRetrievesTheValue() { Sample x = new Sample("id"); Sample y = new Sample("id"); Map<Sample, String> map = new HashMap<>(); map.put(x, "this"); assertEquals("this", map.get(y)); } }
Add override annotations to make error prone happy
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to you under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jmeter.functions; import org.apache.jmeter.util.JMeterUtils; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; /** Test JavaScript function with Rhino engine */ public class TestJavascriptFunctionWithRhino extends TestJavascriptFunction { @BeforeEach @Override public void setUp() { JMeterUtils.getJMeterProperties().put("javascript.use_rhino", "true"); super.setUp(); } @AfterEach @Override public void tearDown() { JMeterUtils.getJMeterProperties().remove("javascript.use_rhino"); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to you under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jmeter.functions; import org.apache.jmeter.util.JMeterUtils; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; /** Test JavaScript function with Rhino engine */ public class TestJavascriptFunctionWithRhino extends TestJavascriptFunction { @BeforeEach public void setUp() { JMeterUtils.getJMeterProperties().put("javascript.use_rhino", "true"); super.setUp(); } @AfterEach public void tearDown() { JMeterUtils.getJMeterProperties().remove("javascript.use_rhino"); } }
Use null as indicator for unconditional action. Signed-off-by: Etienne M. Gagnon <bf06ec0eb40152cd863534753d026b021022c851@j-meg.com>
/* This file is part of SableCC ( http://sablecc.org ). * * See the NOTICE file distributed with this work for copyright information. * * 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.sablecc.sablecc.lrautomaton; import java.util.*; public abstract class Action { private final Map<Integer, Set<Item>> distanceToItemSetMap; Action( Map<Integer, Set<Item>> distanceToItemSetMap) { this.distanceToItemSetMap = distanceToItemSetMap; } }
/* This file is part of SableCC ( http://sablecc.org ). * * See the NOTICE file distributed with this work for copyright information. * * 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.sablecc.sablecc.lrautomaton; import java.util.*; public abstract class Action { private final Map<Integer, Set<Item>> distanceToItemSetMap; Action( Map<Integer, Set<Item>> distanceToItemSetMap) { if (distanceToItemSetMap != null) { this.distanceToItemSetMap = distanceToItemSetMap; } else { this.distanceToItemSetMap = new LinkedHashMap<Integer, Set<Item>>(); } } }
Make py starterpackage more like java/c++ one
import math import sys # A helper class for working with points. class Point: def __init__(self, x, y): self.x = x self.y = y class Edge: def __init__(self, p1, p2): self.p1 = p1 self.p2 = p2 # Gets a problem from a file as an list of points. def getProblem(filename): pts = [] with open(filename, 'r') as input: for line in input: l = line.split(' ') pts.append(Point(float(l[0]), float(l[1]))) return pts # Outputs a list of edges to file "out.txt" for submission. def outputSolutionsToFile(edges): f = open("out.txt", 'w') for a in edges: f.write(str(a.p1.x) + ' ' + str(a.p1.y) + ' ' + str(a.p2.x) + ' ' + str(a.p2.y) + '\n') pts = getProblem("st.txt") # Where you will find the input points. edges = [] # Edges should be added to this. # Your code here. This sample code just connects the points in the order that they are given: for a in range(1, len(pts)): edges.append(Edge(pts[a-1], pts[a])) outputSolutionsToFile(edges)
import math import sys # A helper class for working with points. class Point: def __init__(self, x, y): self.x = x self.y = y class Edge: def __init__(self, p1, p2): self.p1 = p1 self.p2 = p2 def getProblem(filename): pts = [] with open(filename, 'r') as input: for line in input: l = line.split(' ') pts.append(Point(float(l[0]), float(l[1]))) return pts def outputSolutionsToFile(edges): f = open("out.txt", 'w') for a in edges: f.write(str(a.p1.x) + ' ' + str(a.p1.y) + ' ' + str(a.p2.x) + ' ' + str(a.p2.y) + '\n') pts = [] # Where you will find the input points. edges = [] # Edges should be added to this. # Your code here. This sample code just connects the points in the order that they are given: for a in range(1, len(pts)): edges.append(Edge(pts[a-1], pts[a]))
Allow everyone to bam and warm, hide commands
import discord import random from discord.ext import commands class Meme: """ Meme commands. """ def __init__(self, bot): self.bot = bot print('Addon "{}" loaded'.format(self.__class__.__name__)) @commands.command(pass_context=True, hidden=True, name="bam") async def bam_member(self, ctx, user: discord.Member, *, reason=""): """Bams a user owo""" await self.bot.say("{} is ̶n͢ow b̕&̡.̷ 👍̡".format(self.bot.escape_name(user))) @commands.command(pass_context=True, hidden=True, name="warm") async def warm_member(self, ctx, user: discord.Member, *, reason=""): """Warms a user :3""" await self.bot.say("{} warmed. User is now {}°C.".format(user.mention, str(random.randint(0, 100)))) def setup(bot): bot.add_cog(Meme(bot))
import discord import random from discord.ext import commands class Meme: """ Meme commands. """ def __init__(self, bot): self.bot = bot print('Addon "{}" loaded'.format(self.__class__.__name__)) @commands.has_permissions(kick_members=True) @commands.command(pass_context=True, name="bam") async def bam_member(self, ctx, user: discord.Member, *, reason=""): """Bams a user. Staff only.""" await self.bot.say("{} is ̶n͢ow b̕&̡.̷ 👍̡".format(self.bot.escape_name(user))) @commands.has_permissions(kick_members=True) @commands.command(pass_context=True, name="warm") async def warm_member(self, ctx, user: discord.Member, *, reason=""): """Warms a user :3. Staff only.""" await self.bot.say("{} warmed. User is now {}°C.".format(user.mention, str(random.randint(0, 100)))) def setup(bot): bot.add_cog(Meme(bot))
Create a test specifically for naming inconsistencies beween DOM and HTML.
/*global QUnit:false, module:false, test:false, asyncTest:false, expect:false*/ /*global start:false, stop:false ok:false, equal:false, notEqual:false, deepEqual:false*/ /*global notDeepEqual:false, strictEqual:false, notStrictEqual:false, raises:false*/ (function(el) { test("creating an element with attributes", function() { var e = el('p', {id: 'my-id', 'class': 'my-class', 'data-alice': 'bob'}); var dataAttribute = e.attributes.getNamedItem('data-alice'); ok(dataAttribute); equal(dataAttribute.value, 'bob'); equal(e.id, 'my-id'); equal(e.className, 'my-class'); }); test("attributes named differently by the DOM are not an issue as long as you use the HTML naming", function() { var e; e = el('p', {'class': 'my-class1 my-class2'}); equal(e.className, 'my-class1 my-class2'); e = el('label', {'for': 'my-input'}); equal(e.htmlFor, 'my-input'); }); test("setting an attribute to null removes it from the element", function() { var e = el('a', {href: null}); ok( !e.href ); }); }(el));
/*global QUnit:false, module:false, test:false, asyncTest:false, expect:false*/ /*global start:false, stop:false ok:false, equal:false, notEqual:false, deepEqual:false*/ /*global notDeepEqual:false, strictEqual:false, notStrictEqual:false, raises:false*/ (function(el) { test("creating an element with attributes", function() { var e = el('p', {id: 'my-id', 'class': 'my-class', 'data-alice': 'bob'}); var dataAttribute = e.attributes.getNamedItem('data-alice'); ok(dataAttribute); equal(dataAttribute.value, 'bob'); equal(e.id, 'my-id'); equal(e.className, 'my-class'); }); test("setting an attribute to null removes it from the element", function() { var e = el('a', {href: null}); ok( !e.href ); }); }(el));
Add the generated Client interfaces to the telepathy.server namespace
""" telepathy-python - Base classes defining the interfaces of the Telepathy framework Copyright (C) 2005, 2006 Collabora Limited Copyright (C) 2005, 2006 Nokia Corporation Copyright (C) 2006 INdT This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ from telepathy.server.connmgr import * from telepathy.server.conn import * from telepathy.server.channel import * from telepathy.server.channelmanager import * from telepathy.server.debug import * from telepathy.server.handle import * from telepathy.server.media import * from telepathy.server.properties import * from telepathy._generated.Client_Observer import ClientObserver from telepathy._generated.Client_Approver import ClientApprover from telepathy._generated.Client_Handler import ClientHandler from telepathy._generated.Client_Interface_Requests import ClientInterfaceRequests from telepathy import version, __version__
""" telepathy-python - Base classes defining the interfaces of the Telepathy framework Copyright (C) 2005, 2006 Collabora Limited Copyright (C) 2005, 2006 Nokia Corporation Copyright (C) 2006 INdT This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ from telepathy.server.connmgr import * from telepathy.server.conn import * from telepathy.server.channel import * from telepathy.server.channelmanager import * from telepathy.server.debug import * from telepathy.server.handle import * from telepathy.server.media import * from telepathy.server.properties import * from telepathy import version, __version__
Add update and delete methods.
/* * Copyright 2016, Frederik Boster * * 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 de.syquel.bushytail.controller; import org.apache.olingo.server.api.uri.UriParameter; import java.util.List; /** * Interface for all ODataControllers. Provides CRUD Operations. * * @author Clemens Bartz * @author Frederik Boster * @since 1.0 * * @param <T> Entity which is handled by the controller. */ public interface IBushyTailController<T> { /** * Read an entity. * @param keyPredicates the search criterias * @return the entity */ T read(List<UriParameter> keyPredicates); /** * Create the entity. * @param entity the entity */ void create(T entity); void update(T entity); void delete(T entity); }
/* * Copyright 2016, Frederik Boster * * 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 de.syquel.bushytail.controller; import org.apache.olingo.server.api.uri.UriParameter; import java.util.List; /** * Interface for all ODataControllers. Provides CRUD Operations. * * @author Clemens Bartz * @author Frederik Boster * @since 1.0 * * @param <T> Entity which is handled by the controller. */ public interface IBushyTailController<T> { /** * Read an entity. * @param keyPredicates the search criterias * @return the entity */ T read(List<UriParameter> keyPredicates); /** * Create the entity. * @param entity the entity */ void create(T entity); }
Add linkPrefix to links when activated
import React from 'react' import Link from 'react-router/lib/Link' let linkPrefix = `` if (__PREFIX_LINKS__) { linkPrefix = __LINK_PREFIX__ } // Use createClass instead of ES6 class as Babel spews out a ton of code // for polyfilling classes which there's no reason to pay for this. // A function component would be ideal but we need componentDidMount. const GatsbyLink = React.createClass({ propTypes: { to: React.PropTypes.string.isRequired, }, componentDidMount () { // Only enable prefetching of Link resources in production and for browsers that // don't support service workers *cough* Safari/IE *cough*. if (process.env.NODE_ENV === `production` && !(`serviceWorker` in navigator)) { const routes = window.gatsbyRootRoute const { createMemoryHistory } = require(`history`) const matchRoutes = require(`react-router/lib/matchRoutes`) const getComponents = require(`react-router/lib/getComponents`) const createLocation = createMemoryHistory().createLocation if (typeof routes !== 'undefined') { matchRoutes([routes], createLocation(this.props.to), (error, nextState) => { getComponents(nextState, () => console.log(`loaded assets for ${this.props.to}`)) }) } } }, render () { const to = linkPrefix + this.props.to return <Link {...this.props} to={to} /> }, }) module.exports = GatsbyLink
import React from 'react' import Link from 'react-router/lib/Link' // Use createClass instead of ES6 class as Babel spews out a ton of code // for polyfilling classes which there's no reason to pay for this. // A function component would be ideal but we need componentDidMount. const GatsbyLink = React.createClass({ propTypes: { to: React.PropTypes.string.isRequired, }, componentDidMount () { // Only enable prefetching of Link resources in production and for browsers that // don't support service workers *cough* Safari/IE *cough*. if (process.env.NODE_ENV === `production` && !(`serviceWorker` in navigator)) { const routes = window.gatsbyRootRoute const { createMemoryHistory } = require(`history`) const matchRoutes = require(`react-router/lib/matchRoutes`) const getComponents = require(`react-router/lib/getComponents`) const createLocation = createMemoryHistory().createLocation if (typeof routes !== 'undefined') { matchRoutes([routes], createLocation(this.props.to), (error, nextState) => { getComponents(nextState, () => console.log(`loaded assets for ${this.props.to}`)) }) } } }, render () { return <Link {...this.props} /> }, }) module.exports = GatsbyLink
Make sure scatter chart's circle are animating when hovered
'use strict'; var expect = require('chai').expect; describe('ScatterChart', function() { it('renders scatterchart', function() { var React = require('react/addons'); var ScatterChart = require('../src/scatterchart').ScatterChart; var generate = require('../utils/datagen').generateArrayOfPoints; var TestUtils = React.addons.TestUtils; var points = 5; var pointRadius = 5; // Render a scatterchart using array data var data = { series1: generate(points), series2: generate(points) }; var scatterchart = TestUtils.renderIntoDocument( <ScatterChart data={data} width={400} height={200} pointRadius={pointRadius} /> ); var circles = TestUtils.scryRenderedDOMComponentsWithTag( scatterchart, 'circle'); expect(circles).to.have.length(2 * points); var circleOne = circles[0]; var circleOneColor = circleOne.props.fill; expect(circleOne.props.r).to.equal(pointRadius); TestUtils.Simulate.mouseOver(circleOne); expect(circleOne.props.r).to.be.above(pointRadius); expect(circleOne.props.fill).to.not.equal(circleOneColor); TestUtils.Simulate.mouseOut(circleOne); expect(circleOne.props.r).to.equal(pointRadius); expect(circleOne.props.fill).to.equal(circleOneColor); }); });
'use strict'; var expect = require('chai').expect; describe('ScatterChart', function() { it('renders scatterchart', function() { var React = require('react/addons'); var ScatterChart = require('../src/scatterchart').ScatterChart; var generate = require('../utils/datagen').generateArrayOfPoints; var TestUtils = React.addons.TestUtils; var points = 5; var pointRadius = 5; // Render a scatterchart using array data var data = { series1: generate(points), series2: generate(points) }; var scatterchart = TestUtils.renderIntoDocument( <ScatterChart data={data} width={400} height={200} pointRadius={pointRadius} /> ); var circles = TestUtils.scryRenderedDOMComponentsWithTag( scatterchart, 'circle'); expect(circles).to.have.length(2 * points); var circleOne = circles[0]; expect(circleOne.getDOMNode().r.baseVal.value).to.equal(pointRadius); TestUtils.Simulate.mouseOver(circleOne); expect(circleOne.getDOMNode().r.baseVal.value).to.be.above(pointRadius); TestUtils.Simulate.mouseOut(circleOne); expect(circleOne.getDOMNode().r.baseVal.value).to.equal(pointRadius); }); });
Define listItems() with new MVC model OPEN - task 41: Design "ListItemPane" as per new MVC model http://github.com/DevOpsDistilled/OpERP/issues/issue/41
package devopsdistilled.operp.client.items; import javax.inject.Inject; import org.springframework.context.ApplicationContext; import devopsdistilled.operp.client.items.controllers.CreateItemPaneController; import devopsdistilled.operp.client.items.controllers.ListItemPaneController; import devopsdistilled.operp.server.data.entity.items.Item; import devopsdistilled.operp.server.data.service.items.ItemService; public class ItemControllerImpl implements ItemController { @Inject private ApplicationContext context; @Inject private ItemService itemService; @Override public void createItem() { CreateItemPaneController createItemPaneController = context .getBean(CreateItemPaneController.class); createItemPaneController.init(); } @Override public void listItems() { ListItemPaneController listItemPaneController = context .getBean(ListItemPaneController.class); listItemPaneController.init(); } @Override public void editItem(Item item) { } @Override public void deleteItem(Item item) { itemService.delete(item); } }
package devopsdistilled.operp.client.items; import javax.inject.Inject; import org.springframework.context.ApplicationContext; import devopsdistilled.operp.client.items.controllers.CreateItemPaneController; import devopsdistilled.operp.server.data.entity.items.Item; import devopsdistilled.operp.server.data.service.items.ItemService; public class ItemControllerImpl implements ItemController { @Inject private ApplicationContext context; @Inject private ItemService itemService; @Override public void createItem() { CreateItemPaneController createItemPaneController = context .getBean(CreateItemPaneController.class); createItemPaneController.init(); } @Override public void editItem(Item item) { } @Override public void listItems() { ListItemPane listItemPane = context.getBean(ListItemPane.class); listItemPane.init(); listItemPane.getDialog(); } @Override public void deleteItem(Item item) { itemService.delete(item); } }
PUBDEV-455: Fix DRFParametersV2, remove unused do_grpsplit argument.
package hex.schemas; import hex.tree.drf.DRF; import hex.tree.drf.DRFModel.DRFParameters; import water.api.API; import water.api.SupervisedModelParametersSchema; import hex.schemas.SharedTreeV2; // Yes, this is needed. Compiler bug. import hex.schemas.SharedTreeV2.SharedTreeParametersV2; // Yes, this is needed. Compiler bug. public class DRFV2 extends SharedTreeV2<DRF,DRFV2,DRFV2.DRFParametersV2> { public static final class DRFParametersV2 extends SharedTreeParametersV2<DRFParameters, DRFParametersV2> { static public String[] own_fields = new String[] { "mtries", "sample_rate", "build_tree_one_node" }; // Input fields @API(help = "Number of columns to randomly select at each level, or -1 for sqrt(#cols)") public int mtries; @API(help = "Sample rate, from 0. to 1.0") public float sample_rate; @API(help="Run on one node only; no network overhead but fewer cpus used. Suitable for small datasets.") public boolean build_tree_one_node; } }
package hex.schemas; import hex.tree.drf.DRF; import hex.tree.drf.DRFModel.DRFParameters; import water.api.API; import water.api.SupervisedModelParametersSchema; import hex.schemas.SharedTreeV2; // Yes, this is needed. Compiler bug. import hex.schemas.SharedTreeV2.SharedTreeParametersV2; // Yes, this is needed. Compiler bug. public class DRFV2 extends SharedTreeV2<DRF,DRFV2,DRFV2.DRFParametersV2> { public static final class DRFParametersV2 extends SharedTreeParametersV2<DRFParameters, DRFParametersV2> { static public String[] own_fields = new String[] { "mtries", "sample_rate", "do_grpsplit", "build_tree_one_node" }; // Input fields @API(help = "Columns to randomly select at each level, or -1 for sqrt(#cols)") public int mtries; @API(help = "Sample rate, from 0. to 1.0") public float sample_rate; @API(help = "Check non-contiguous group splits for categorical predictors") public boolean do_grpsplit; @API(help="Run on one node only; no network overhead but fewer cpus used. Suitable for small datasets.") public boolean build_tree_one_node; } }
Increase payload limit to 1.5MB When editing a model, this allow the user to upload a 1MB file, rather than something like a 925.3kB file, along with about 500kB of description text.
import express from 'express'; import path from 'path'; import bodyParser from 'body-parser'; import api from './api'; let server = null; function start(port) { return new Promise((resolve, reject) => { if (server !== null) { reject(new Error('The server is already running.')); } let app = express(); app.use(express.static(path.join(__dirname, '../public'))); app.use(bodyParser.json({ limit: '1.5MB' })); app.use('/api', api); server = app.listen(port, () => { resolve(); }); }); } function stop() { return new Promise((resolve, reject) => { if (server === null) { reject(new Error('The server is not running.')); } server.close(() => { server = null; resolve(); }); }); } export default { start, stop };
import express from 'express'; import path from 'path'; import bodyParser from 'body-parser'; import api from './api'; let server = null; function start(port) { return new Promise((resolve, reject) => { if (server !== null) { reject(new Error('The server is already running.')); } let app = express(); app.use(express.static(path.join(__dirname, '../public'))); app.use(bodyParser.json({ limit: '1MB' })); app.use('/api', api); server = app.listen(port, () => { resolve(); }); }); } function stop() { return new Promise((resolve, reject) => { if (server === null) { reject(new Error('The server is not running.')); } server.close(() => { server = null; resolve(); }); }); } export default { start, stop };
Improve existing methods, add new ones for packing longs
package org.bouncycastle.crypto.util; public abstract class Pack { public static int bigEndianToInt(byte[] bs, int off) { int n = bs[ off] << 24; n |= (bs[++off] & 0xff) << 16; n |= (bs[++off] & 0xff) << 8; n |= (bs[++off] & 0xff); return n; } public static void intToBigEndian(int n, byte[] bs, int off) { bs[ off] = (byte)(n >>> 24); bs[++off] = (byte)(n >>> 16); bs[++off] = (byte)(n >>> 8); bs[++off] = (byte)(n ); } public static long bigEndianToLong(byte[] bs, int off) { int hi = bigEndianToInt(bs, off); int lo = bigEndianToInt(bs, off + 4); return ((long)(hi & 0xffffffffL) << 32) | (long)(lo & 0xffffffffL); } public static void longToBigEndian(long n, byte[] bs, int off) { intToBigEndian((int)(n >>> 32), bs, off); intToBigEndian((int)(n & 0xffffffffL), bs, off + 4); } }
package org.bouncycastle.crypto.util; public abstract class Pack { public static int bigEndianToInt(byte[] bs, int off) { int n = bs[off++] << 24; n |= (bs[off++] & 0xff) << 16; n |= (bs[off++] & 0xff) << 8; n |= (bs[off++] & 0xff); return n; } public static void intToBigEndian(int n, byte[] bs, int off) { bs[off++] = (byte)(n >>> 24); bs[off++] = (byte)(n >>> 16); bs[off++] = (byte)(n >>> 8); bs[off ] = (byte)(n ); } }
Increment version to 0.0.5 for release
<?php define("BEYONIC_CLIENT_VERSION", "0.0.5"); if (!function_exists('curl_init')) { throw new Exception('Beyonic requires the CURL PHP extension.'); } if (!function_exists('json_decode')) { throw new Exception('Beyonic requires the JSON PHP extension.'); } // Beyonic Primary Interface require_once(dirname(__FILE__) . '/Beyonic/Beyonic.php'); // Beyonic API endpoints require_once(dirname(__FILE__) . '/Beyonic/Endpoint_Wrapper.php'); require_once(dirname(__FILE__) . '/Beyonic/Webhook.php'); require_once(dirname(__FILE__) . '/Beyonic/Payment.php'); require_once(dirname(__FILE__) . '/Beyonic/Collection.php'); require_once(dirname(__FILE__) . '/Beyonic/Collection_Request.php'); require_once(dirname(__FILE__) . '/Beyonic/Contact.php'); require_once(dirname(__FILE__) . '/Beyonic/Account.php'); require_once(dirname(__FILE__) . '/Beyonic/Transaction.php'); require_once(dirname(__FILE__) . '/Beyonic/Beyonic_Exception.php');
<?php define("BEYONIC_CLIENT_VERSION", "0.0.4"); if (!function_exists('curl_init')) { throw new Exception('Beyonic requires the CURL PHP extension.'); } if (!function_exists('json_decode')) { throw new Exception('Beyonic requires the JSON PHP extension.'); } // Beyonic Primary Interface require_once(dirname(__FILE__) . '/Beyonic/Beyonic.php'); // Beyonic API endpoints require_once(dirname(__FILE__) . '/Beyonic/Endpoint_Wrapper.php'); require_once(dirname(__FILE__) . '/Beyonic/Webhook.php'); require_once(dirname(__FILE__) . '/Beyonic/Payment.php'); require_once(dirname(__FILE__) . '/Beyonic/Collection.php'); require_once(dirname(__FILE__) . '/Beyonic/Collection_Request.php'); require_once(dirname(__FILE__) . '/Beyonic/Contact.php'); require_once(dirname(__FILE__) . '/Beyonic/Account.php'); require_once(dirname(__FILE__) . '/Beyonic/Transaction.php'); require_once(dirname(__FILE__) . '/Beyonic/Beyonic_Exception.php');
Fix order in v2 dragon endpoint
const limit = require('../../lib/query-builder/v2/limit'); const project = require('../../lib/query-builder/v2/project'); module.exports = { /** * Returns all Dragon data */ all: async (ctx) => { const data = await global.db .collection('dragon') .find({}) .project(project(ctx.request.query)) .sort({ id: 1 }) .limit(limit(ctx.request.query)) .toArray(); ctx.body = data; }, /** * Returns specific Dragon data */ specific: async (ctx) => { const data = await global.db .collection('dragon') .find({ id: ctx.params.capsule }) .project(project(ctx.request.query)) .toArray(); [ctx.body] = data; }, };
const limit = require('../../lib/query-builder/v2/limit'); const project = require('../../lib/query-builder/v2/project'); module.exports = { /** * Returns all Dragon data */ all: async (ctx) => { const data = await global.db .collection('dragon') .find({}) .project(project(ctx.request.query)) .limit(limit(ctx.request.query)) .toArray(); ctx.body = data; }, /** * Returns specific Dragon data */ specific: async (ctx) => { const data = await global.db .collection('dragon') .find({ id: ctx.params.capsule }) .project(project(ctx.request.query)) .toArray(); [ctx.body] = data; }, };
Fix assertion error documentation URL Prefix version number with 'v' to obtain correct URL. This fixes #8556.
/** * @module ol/AssertionError */ import {VERSION} from './util.js'; /** * Error object thrown when an assertion failed. This is an ECMA-262 Error, * extended with a `code` property. * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error. */ class AssertionError extends Error { /** * @param {number} code Error code. */ constructor(code) { const path = VERSION === 'latest' ? VERSION : 'v' + VERSION.split('-')[0]; const message = 'Assertion failed. See https://openlayers.org/en/' + path + '/doc/errors/#' + code + ' for details.'; super(message); /** * Error code. The meaning of the code can be found on * https://openlayers.org/en/latest/doc/errors/ (replace `latest` with * the version found in the OpenLayers script's header comment if a version * other than the latest is used). * @type {number} * @api */ this.code = code; /** * @type {string} */ this.name = 'AssertionError'; // Re-assign message, see https://github.com/Rich-Harris/buble/issues/40 this.message = message; } } export default AssertionError;
/** * @module ol/AssertionError */ import {VERSION} from './util.js'; /** * Error object thrown when an assertion failed. This is an ECMA-262 Error, * extended with a `code` property. * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error. */ class AssertionError extends Error { /** * @param {number} code Error code. */ constructor(code) { const path = VERSION.split('-')[0]; const message = 'Assertion failed. See https://openlayers.org/en/' + path + '/doc/errors/#' + code + ' for details.'; super(message); /** * Error code. The meaning of the code can be found on * https://openlayers.org/en/latest/doc/errors/ (replace `latest` with * the version found in the OpenLayers script's header comment if a version * other than the latest is used). * @type {number} * @api */ this.code = code; /** * @type {string} */ this.name = 'AssertionError'; // Re-assign message, see https://github.com/Rich-Harris/buble/issues/40 this.message = message; } } export default AssertionError;
Bump to version with package data fix
from setuptools import setup, find_packages setup(name='rnaseq-lib', version='1.0a11', description='', url='http://github.com/jvivian/rnaseq-lib', author='John Vivian', author_email='jtvivian@gmail.com', license='MIT', package_dir={'': 'src'}, packages=find_packages('src'), package_data={'rnaseq_lib.utils': ['data/*']}, install_requires=['pandas', 'numpy', 'seaborn', 'requests'])
from setuptools import setup, find_packages setup(name='rnaseq-lib', version='1.0a10', description='', url='http://github.com/jvivian/rnaseq-lib', author='John Vivian', author_email='jtvivian@gmail.com', license='MIT', package_dir={'': 'src'}, packages=find_packages('src'), package_data={'rnaseq_lib.utils': ['data/*']}, install_requires=['pandas', 'numpy', 'seaborn', 'requests'])
Change fields to the schema agreed
from eduid_am.exceptions import UserDoesNotExist def attribute_fetcher(db, user_id): attributes = {} user = db.registered.find_one({'_id': user_id}) if user is None: raise UserDoesNotExist("No user matching _id='%s'" % user_id) else: email = user.get('email', None) if email: attributes['mail'] = email attributes['mailAliases'] = [{ 'email': email, 'verified': user.get('verified', False), }] # This values must overwrite existent values for attr in ('givenName', 'sn', 'displayName', 'passwords', 'date'): value = user.get(attr, None) if value is not None: attributes[attr] = value return attributes
from eduid_am.exceptions import UserDoesNotExist def attribute_fetcher(db, user_id): attributes = {} user = db.registered.find_one({'_id': user_id}) if user is None: raise UserDoesNotExist("No user matching _id='%s'" % user_id) else: # white list of valid attributes for security reasons for attr in ('email', 'date', 'verified'): value = user.get(attr, None) if value is not None: attributes[attr] = value # This values must overwrite existent values for attr in ('screen_name', 'last_name', 'first_name', 'passwords'): value = user.get(attr, None) if value is not None: attributes[attr] = value return attributes
Add a test for `notes` attribute
# coding: utf-8 import unittest from lastpass.account import Account class AccountTestCase(unittest.TestCase): def setUp(self): self.id = 'id' self.name = 'name' self.username = 'username' self.password = 'password' self.url = 'url' self.group = 'group' self.notes = 'notes' self.account = Account(self.id, self.name, self.username, self.password, self.url, self.group, self.notes) def test_id_returns_the_correct_value(self): self.assertEqual(self.account.id, self.id) def test_name_returns_the_correct_value(self): self.assertEqual(self.account.name, self.name) def test_username_returns_the_correct_value(self): self.assertEqual(self.account.username, self.username) def test_password_returns_the_correct_value(self): self.assertEqual(self.account.password, self.password) def test_url_returns_the_correct_value(self): self.assertEqual(self.account.url, self.url) def test_group_returns_the_correct_value(self): self.assertEqual(self.account.group, self.group) def test_notes_returns_the_correct_value(self): self.assertEqual(self.account.notes, self.notes)
# coding: utf-8 import unittest from lastpass.account import Account class AccountTestCase(unittest.TestCase): def setUp(self): self.id = 'id' self.name = 'name' self.username = 'username' self.password = 'password' self.url = 'url' self.group = 'group' self.account = Account(self.id, self.name, self.username, self.password, self.url, self.group) def test_id_returns_the_correct_value(self): self.assertEqual(self.account.id, self.id) def test_name_returns_the_correct_value(self): self.assertEqual(self.account.name, self.name) def test_username_returns_the_correct_value(self): self.assertEqual(self.account.username, self.username) def test_password_returns_the_correct_value(self): self.assertEqual(self.account.password, self.password) def test_url_returns_the_correct_value(self): self.assertEqual(self.account.url, self.url) def test_group_returns_the_correct_value(self): self.assertEqual(self.account.group, self.group)
Add new function to DramaModel
(function(){ 'use strict'; angular .module('secondLead.common') .factory('DramaModel',['Restangular', function (Restangular){ var baseDramas = Restangular.all('dramas'); function extract (result){ return result.data; }; return { getAll: baseDramas.getList().$object, getSome: function (genre){ return $http.get('/dramas/filter', {params: {genre: genre}}).then(extract); }, getOne: function (dramaID){ return Restangular.one('dramas', dramaID).get() }, delete: function (userID, listID, dramaID){ return Restangular.one("users", userID).one("lists", listID).one("dramas", dramaID).remove() }, add: function (userID, listID, dramaID){ return Restangular.one("users", userID).one("lists", listID).all("dramas").post({id: dramaID}) } }; }]) })();
(function(){ 'use strict'; angular .module('secondLead.common') .factory('DramaModel',['Restangular', function (Restangular){ var baseDramas = Restangular.all('dramas'); return { getAll: baseDramas.getList().$object, getOne: function (dramaID){ return Restangular.one('dramas', dramaID).get() }, delete: function (userID, listID, dramaID){ return Restangular.one("users", userID).one("lists", listID).one("dramas", dramaID).remove() }, add: function (userID, listID, dramaID){ return Restangular.one("users", userID).one("lists", listID).all("dramas").post({id: dramaID}) } }; }]) })();
Make careerop only display active ops
#-*- coding: utf-8 -*- from datetime import datetime from django.shortcuts import render_to_response from django.shortcuts import get_object_or_404 from django.template import RequestContext from apps.careeropportunity.models import CareerOpportunity def index(request): opportunities = CareerOpportunity.objects.filter(start__lte=datetime.now(), end__gte=datetime.now()) return render_to_response('careeropportunity/index.html', \ {'opportunities': opportunities}, \ context_instance=RequestContext(request)) def details(request, opportunity_id): opportunity = get_object_or_404(CareerOpportunity, pk=opportunity_id) return render_to_response('careeropportunity/details.html', \ {'opportunity': opportunity}, \ context_instance=RequestContext(request))
#-*- coding: utf-8 -*- from django.shortcuts import render_to_response from django.shortcuts import get_object_or_404 from django.template import RequestContext from apps.careeropportunity.models import CareerOpportunity import datetime def index(request): opportunities = CareerOpportunity.objects.all() return render_to_response('careeropportunity/index.html', \ {'opportunities': opportunities}, \ context_instance=RequestContext(request)) def details(request, opportunity_id): opportunity = get_object_or_404(CareerOpportunity, pk=opportunity_id) return render_to_response('careeropportunity/details.html', \ {'opportunity': opportunity}, \ context_instance=RequestContext(request))
Install default dotfiles with package
from distutils.core import setup setup(name='Pyranha', description='Elegant IRC client', version='0.1', author='John Reese', author_email='john@noswap.com', url='https://github.com/jreese/pyranha', classifiers=['License :: OSI Approved :: MIT License', 'Topic :: Communications :: Chat :: Internet Relay Chat', 'Development Status :: 2 - Pre-Alpha', ], license='MIT License', packages=['pyranha', 'pyranha.irc'], package_data={'pyranha': ['dotfiles/*']}, scripts=['bin/pyranha'], )
from distutils.core import setup setup(name='Pyranha', description='Elegant IRC client', version='0.1', author='John Reese', author_email='john@noswap.com', url='https://github.com/jreese/pyranha', classifiers=['License :: OSI Approved :: MIT License', 'Topic :: Communications :: Chat :: Internet Relay Chat', 'Development Status :: 2 - Pre-Alpha', ], license='MIT License', packages=['pyranha', 'pyranha.irc'], package_data={'pyranha': []}, scripts=['bin/pyranha'], )
Rename source to data for
'use strict'; var RSVP = require('rsvp'); var fork = require('child_process').fork; module.exports = function (language, source) { return new RSVP.Promise(function (resolve) { var child = fork(__dirname); var output = ''; var timeout = setTimeout(function () { console.error(language + ' processor timeout'); child.kill(); }, 1000); child.on('stderr', function (data) { console.error(language + ' processor errors'); console.error(data); }); child.on('message', function (message) { output += message; }); child.on('exit', function () { clearTimeout(timeout); resolve(output); }); child.send({ language: language, data: source}); }); };
'use strict'; var RSVP = require('rsvp'); var fork = require('child_process').fork; module.exports = function (language, source) { return new RSVP.Promise(function (resolve) { var child = fork(__dirname); var output = ''; var timeout = setTimeout(function () { console.error(language + ' processor timeout'); child.kill(); }, 1000); child.on('stderr', function (data) { console.error(language + ' processor errors'); console.error(data); }); child.on('message', function (message) { output += message; }); child.on('exit', function () { clearTimeout(timeout); resolve(output); }); child.send({ language: language, source: source }); }); };
Use proper setting for static files in development
from django.conf import settings from django.conf.urls import patterns, url, include from django.conf.urls.static import static from django.contrib.gis import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from huts.urls import hut_patterns, api_patterns admin.autodiscover() # main site urlpatterns = patterns('', url(r'', include((hut_patterns, 'huts', 'huts'))), url(r'^api/', include((api_patterns, 'huts_api', 'huts_api'))), ) # admin urlpatterns += patterns('', url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)), ) # serve static and media files during development urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
from django.conf import settings from django.conf.urls import patterns, url, include from django.conf.urls.static import static from django.contrib.gis import admin from huts.urls import hut_patterns, api_patterns admin.autodiscover() # main site urlpatterns = patterns('', url(r'', include((hut_patterns, 'huts', 'huts'))), url(r'^api/', include((api_patterns, 'huts_api', 'huts_api'))), ) # admin urlpatterns += patterns('', url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)), ) # serve static and media files during development urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
[Security] Change the phrasing of the deauthenticated event
<?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\Security\Http\Event; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Contracts\EventDispatcher\Event; /** * Deauthentication happens in case the user has changed when trying to refresh the token. * * @author Hamza Amrouche <hamza.simperfit@gmail.com> */ class DeauthenticatedEvent extends Event { private $originalToken; private $refreshedToken; public function __construct(TokenInterface $originalToken, TokenInterface $refreshedToken) { $this->originalToken = $originalToken; $this->refreshedToken = $refreshedToken; } public function getRefreshedToken(): TokenInterface { return $this->refreshedToken; } public function getOriginalToken(): TokenInterface { return $this->originalToken; } }
<?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\Security\Http\Event; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Contracts\EventDispatcher\Event; /** * Deauthentication happens in case the user has changed when trying to refresh it. * * @author Hamza Amrouche <hamza.simperfit@gmail.com> */ class DeauthenticatedEvent extends Event { private $originalToken; private $refreshedToken; public function __construct(TokenInterface $originalToken, TokenInterface $refreshedToken) { $this->originalToken = $originalToken; $this->refreshedToken = $refreshedToken; } public function getRefreshedToken(): TokenInterface { return $this->refreshedToken; } public function getOriginalToken(): TokenInterface { return $this->originalToken; } }
Remove todo comment, no settings support
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Jon Surrell # Copyright (c) 2013 Jon Surrell # # License: MIT # """This module exports the Ghc plugin class.""" from SublimeLinter.lint import Linter, util class Ghc(Linter): """Provides an interface to ghc.""" syntax = ('haskell', 'haskell-sublimehaskell') cmd = ('ghc', '-fno-code', '-Wall', '-Wwarn', '-fno-helpful-errors') regex = r'^.+:(?P<line>\d+):(?P<col>\d+):\s+(?P<warning>Warning:\s+)?(?P<message>.+)$' multiline = True # No stdin tempfile_suffix = 'hs' # ghc writes errors to STDERR error_stream = util.STREAM_STDERR defaults = {} inline_settings = None inline_overrides = None comment_re = None
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Jon Surrell # Copyright (c) 2013 Jon Surrell # # License: MIT # """This module exports the Ghc plugin class.""" from SublimeLinter.lint import Linter, util class Ghc(Linter): """Provides an interface to ghc.""" syntax = ('haskell', 'haskell-sublimehaskell') cmd = ('ghc', '-fno-code', '-Wall', '-Wwarn', '-fno-helpful-errors') regex = r'^.+:(?P<line>\d+):(?P<col>\d+):\s+(?P<warning>Warning:\s+)?(?P<message>.+)$' multiline = True # No stdin tempfile_suffix = 'hs' # ghc writes errors to STDERR error_stream = util.STREAM_STDERR # @todo allow some settings defaults = {} inline_settings = None inline_overrides = None comment_re = None
Use named tuple for return value
# from subprocess import CalledProcessError from collections import namedtuple import subprocess CommandResult = namedtuple("Result", ['rc', 'out', 'err']) def run_through_shell(command, enable_shell=False): """ Retrieves output of command Returns tuple success (boolean)/ stdout(string) / stderr (string) Don't use this function with programs that outputs lots of data since the output is saved in one variable """ returncode = None stderr = None try: proc = subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=enable_shell) out, stderr = proc.communicate() out = out.decode("UTF-8") stderr = stderr.decode("UTF-8") returncode = proc.returncode except OSError as e: out = e.strerror stderr = e.strerror except subprocess.CalledProcessError as e: out = e.output return CommandResult(returncode, out, stderr)
# from subprocess import CalledProcessError import subprocess def run_through_shell(command, enable_shell=False): """ Retrieves output of command Returns tuple success (boolean)/ stdout(string) / stderr (string) Don't use this function with programs that outputs lots of data since the output is saved in one variable """ returncode = None try: proc = subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=enable_shell) out, stderr = proc.communicate() out = out.decode("UTF-8") stderr = stderr.decode("UTF-8") returncode = proc.returncode except OSError as e: out = e.strerror stderr = e.strerror except subprocess.CalledProcessError as e: out = e.output return returncode, out, stderr
Fix typos in "No ~/.humbugrc found" error message (imported from commit b0c8aab4668751d9b1d12792d249645498a95932)
from __future__ import absolute_import from django.core.management.base import BaseCommand from zephyr.models import get_user_profile_by_email import os from ConfigParser import SafeConfigParser class Command(BaseCommand): help = """Reset all colors for a person to the default grey""" def handle(self, *args, **options): config_file = os.path.join(os.environ["HOME"], ".humbugrc") if not os.path.exists(config_file): raise RuntimeError("No ~/.humbugrc found") config = SafeConfigParser() with file(config_file, 'r') as f: config.readfp(f, config_file) api_key = config.get("api", "key") email = config.get("api", "email") user_profile = get_user_profile_by_email(email) user_profile.api_key = api_key user_profile.save()
from __future__ import absolute_import from django.core.management.base import BaseCommand from zephyr.models import get_user_profile_by_email import os from ConfigParser import SafeConfigParser class Command(BaseCommand): help = """Reset all colors for a person to the default grey""" def handle(self, *args, **options): config_file = os.path.join(os.environ["HOME"], ".humbugrc") if not os.path.exists(config_file): raise RuntimeError("Not ~/.humbughrc") config = SafeConfigParser() with file(config_file, 'r') as f: config.readfp(f, config_file) api_key = config.get("api", "key") email = config.get("api", "email") user_profile = get_user_profile_by_email(email) user_profile.api_key = api_key user_profile.save()
Correct data type for sms domain definition
/* * This program is part of the OpenLMIS logistics management information system platform software. * Copyright © 2013 VillageReach * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. *   * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License along with this program.  If not, see http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.  */ package org.openlmis.core.domain; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import java.util.Date; @Getter @Setter @NoArgsConstructor public class SMS { private String message; private String phoneNumber; private String direction; private Date dateSaved; private Boolean sent; }
/* * This program is part of the OpenLMIS logistics management information system platform software. * Copyright © 2013 VillageReach * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. *   * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License along with this program.  If not, see http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.  */ package org.openlmis.core.domain; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import java.util.Date; @Getter @Setter @NoArgsConstructor public class SMS { private String message; private String phoneNumber; private String direction; private Date dateSaved; //adding one column private Integer sent; }
Change form submit url to match change in folder heirarchy
<html> <body> <?php if (array_key_exists('submit', $_POST)): ?> Data From Sensor #<?php echo $_POST["uid"]; ?><br> Level: <?php echo $_POST["level"]; ?><br> Max Level: <?php echo $_POST["levelmax"]; ?> <br> Fill Percentage: <?php echo 100*(intval($_POST["level"])/intval($_POST["levelmax"])) ?><br> Battery Level: <?php echo $_POST["battlevel"]; ?><br> <?php else: ?> <form action="/public/GroupDesignProjectServer/backend..php" method="post"> Bin Level: <input type="text" name="level"><br> Bin Level Max: <input type="text" name="levelmax"><br> Battery Level: <input type="text" name="battlevel"><br> UID: <input type="text" name="uid"><br> <input type="submit" name="submit"> </form> <?php endif ?> </body> </html>
<html> <body> <?php if (array_key_exists('submit', $_POST)): ?> Data From Sensor #<?php echo $_POST["uid"]; ?><br> Level: <?php echo $_POST["level"]; ?><br> Max Level: <?php echo $_POST["levelmax"]; ?> <br> Fill Percentage: <?php echo 100*(intval($_POST["level"])/intval($_POST["levelmax"])) ?><br> Battery Level: <?php echo $_POST["battlevel"]; ?><br> <?php else: ?> <form action="/public/test2.php" method="post"> Bin Level: <input type="text" name="level"><br> Bin Level Max: <input type="text" name="levelmax"><br> Battery Level: <input type="text" name="battlevel"><br> UID: <input type="text" name="uid"><br> <input type="submit" name="submit"> </form> <?php endif ?> </body> </html>
Switch to hashicorp version of msgpack
package raftmdb import ( "bytes" "encoding/binary" "github.com/hashicorp/go-msgpack/codec" ) // Decode reverses the encode operation on a byte slice input func decodeMsgPack(buf []byte, out interface{}) error { r := bytes.NewBuffer(buf) hd := codec.MsgpackHandle{} dec := codec.NewDecoder(r, &hd) return dec.Decode(out) } // Encode writes an encoded object to a new bytes buffer func encodeMsgPack(in interface{}) (*bytes.Buffer, error) { buf := bytes.NewBuffer(nil) hd := codec.MsgpackHandle{} enc := codec.NewEncoder(buf, &hd) err := enc.Encode(in) return buf, err } // Converts bytes to an integer func bytesToUint64(b []byte) uint64 { return binary.BigEndian.Uint64(b) } // Converts a uint to a byte slice func uint64ToBytes(u uint64) []byte { buf := make([]byte, 8) binary.BigEndian.PutUint64(buf, u) return buf }
package raftmdb import ( "bytes" "encoding/binary" "github.com/ugorji/go/codec" ) // Decode reverses the encode operation on a byte slice input func decodeMsgPack(buf []byte, out interface{}) error { r := bytes.NewBuffer(buf) hd := codec.MsgpackHandle{} dec := codec.NewDecoder(r, &hd) return dec.Decode(out) } // Encode writes an encoded object to a new bytes buffer func encodeMsgPack(in interface{}) (*bytes.Buffer, error) { buf := bytes.NewBuffer(nil) hd := codec.MsgpackHandle{} enc := codec.NewEncoder(buf, &hd) err := enc.Encode(in) return buf, err } // Converts bytes to an integer func bytesToUint64(b []byte) uint64 { return binary.BigEndian.Uint64(b) } // Converts a uint to a byte slice func uint64ToBytes(u uint64) []byte { buf := make([]byte, 8) binary.BigEndian.PutUint64(buf, u) return buf }
Fix pytype issue in signal handling code. PiperOrigin-RevId: 408605103 Change-Id: If724504629a50d5cb7a099cf0263ba642e95345d
# Copyright 2018 DeepMind Technologies Limited. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A thin wrapper around Python's builtin signal.signal().""" import signal import types from typing import Any, Callable _Handler = Callable[[], Any] def add_handler(signo: signal.Signals, fn: _Handler): # The function signal.signal expects the handler to take an int rather than a # signal.Signals. def _wrapped(signo: int, frame: types.FrameType): del signo, frame return fn() signal.signal(signo.value, _wrapped)
# Copyright 2018 DeepMind Technologies Limited. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A thin wrapper around Python's builtin signal.signal().""" import signal import types from typing import Any, Callable _Handler = Callable[[], Any] def add_handler(signo: signal.Signals, fn: _Handler): def _wrapped(signo: signal.Signals, frame: types.FrameType): del signo, frame return fn() signal.signal(signo, _wrapped)
Add policy description for image size This commit adds policy doc for image size policies. Partial implement blueprint policy-docs Change-Id: I0de4aaa47e21c4e156569eebcb495412ab364417
# Copyright 2016 Cloudbase Solutions Srl # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from nova.policies import base BASE_POLICY_NAME = 'os_compute_api:image-size' image_size_policies = [ base.create_rule_default( BASE_POLICY_NAME, base.RULE_ADMIN_OR_OWNER, """Add 'OS-EXT-IMG-SIZE:size' attribute in the image response.""", [ { 'method': 'GET', 'path': '/images/{id}' }, { 'method': 'GET', 'path': '/images/detail' } ]), ] def list_rules(): return image_size_policies
# Copyright 2016 Cloudbase Solutions Srl # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_policy import policy from nova.policies import base BASE_POLICY_NAME = 'os_compute_api:image-size' image_size_policies = [ policy.RuleDefault( name=BASE_POLICY_NAME, check_str=base.RULE_ADMIN_OR_OWNER), ] def list_rules(): return image_size_policies
Fix invalid path when publishing vendor config.
<?php namespace Kurt\Repoist; use Illuminate\Support\ServiceProvider; use Kurt\Repoist\Commands\MakeCriterionCommand; use Kurt\Repoist\Commands\MakeRepositoryCommand; class RepoistServiceProvider extends ServiceProvider { /** * Commands to be registered. * @var array */ private $repoistCommands = [ MakeCriterionCommand::class, MakeRepositoryCommand::class, ]; /** * Bootstrap the application services. * * @return void */ public function boot() { // } /** * Register the application services. * * @return void */ public function register() { $this->mergeConfigFrom(__DIR__.'/config/repoist.php', 'repoist'); $this->publishes([ __DIR__.'/config/repoist.php' => config_path('repoist.php') ], 'repoist-config'); $this->registerCommands(); } /** * Registers repoist commands. */ public function registerCommands() { $this->commands($this->repoistCommands); } }
<?php namespace Kurt\Repoist; use Illuminate\Support\ServiceProvider; use Kurt\Repoist\Commands\MakeCriterionCommand; use Kurt\Repoist\Commands\MakeRepositoryCommand; class RepoistServiceProvider extends ServiceProvider { /** * Commands to be registered. * @var array */ private $repoistCommands = [ MakeCriterionCommand::class, MakeRepositoryCommand::class, ]; /** * Bootstrap the application services. * * @return void */ public function boot() { // } /** * Register the application services. * * @return void */ public function register() { $this->mergeConfigFrom(__DIR__.'/config/repoist.php', 'repoist'); $this->publishes([ __DIR__.'/config/package.php' => config_path('repoist.php') ], 'repoist-config'); $this->registerCommands(); } /** * Registers repoist commands. */ public function registerCommands() { $this->commands($this->repoistCommands); } }